76 lines
2.8 KiB
Python
76 lines
2.8 KiB
Python
import cv2
|
|
import numpy as np
|
|
from PIL import Image
|
|
import logging
|
|
|
|
# 로거 인스턴스 가져오기
|
|
logger = logging.getLogger('default_logger')
|
|
|
|
def pil_to_cv(image_pil):
|
|
try:
|
|
"""PIL 이미지를 OpenCV 이미지(numpy array)로 변환"""
|
|
image_np = np.array(image_pil)
|
|
# Convert RGB to BGR
|
|
return image_np[:, :, ::-1]
|
|
except Exception as e:
|
|
logger.error(f"pil_to_cv 처리 중 에러 발생 : {e}")
|
|
return image_pil
|
|
|
|
def cv_to_pil(image_cv):
|
|
try:
|
|
"""OpenCV 이미지(numpy array)를 PIL 이미지로 변환"""
|
|
# Convert BGR to RGB
|
|
return Image.fromarray(image_cv[:, :, ::-1])
|
|
except Exception as e:
|
|
logger.error(f"cv_to_pil 처리 중 에러 발생 : {e}")
|
|
return image_cv
|
|
|
|
|
|
def crop_by_boxline(image_pil, crop_percent):
|
|
try:
|
|
image_cv = pil_to_cv(image_pil)
|
|
height, width = image_cv.shape[:2]
|
|
crop_height = int(height * crop_percent)
|
|
crop_width = int(width * crop_percent)
|
|
start_row, start_col = crop_height // 2, crop_width // 2
|
|
end_row, end_col = height - start_row, width - start_col
|
|
cropped_image_cv = image_cv[start_row:end_row, start_col:end_col]
|
|
return cv_to_pil(cropped_image_cv)
|
|
except Exception as e:
|
|
logger.error(f"crop_by_boxline 처리 중 에러 발생 : {e}")
|
|
return image_pil
|
|
|
|
def rotate_by_angle(image_pil, angle, color):
|
|
try:
|
|
image_cv = pil_to_cv(image_pil)
|
|
height, width = image_cv.shape[:2]
|
|
center = (width // 2, height // 2)
|
|
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
|
|
if color == "white":
|
|
rotated_image_cv = cv2.warpAffine(image_cv, rotation_matrix, (width, height), borderValue=(255, 255, 255))
|
|
elif color == "transparent":
|
|
rotated_image_cv = cv2.warpAffine(image_cv, rotation_matrix, (width, height), borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0, 0))
|
|
return cv_to_pil(rotated_image_cv)
|
|
except Exception as e:
|
|
logger.error(f"rotate_by_angle 처리 중 에러 발생 : {e}")
|
|
return image_pil
|
|
|
|
def mirror_by_image(image_pil):
|
|
try:
|
|
image_cv = pil_to_cv(image_pil)
|
|
flipped_image_cv = cv2.flip(image_cv, 1)
|
|
return cv_to_pil(flipped_image_cv)
|
|
except Exception as e:
|
|
logger.error(f"mirror_by_image 처리 중 에러 발생 : {e}")
|
|
return image_pil
|
|
|
|
def flip_and_rotate_image(image_pil):
|
|
try:
|
|
cropped_image_pil = crop_by_boxline(image_pil, crop_percent=0.05)
|
|
mirror_image_pil = mirror_by_image(cropped_image_pil)
|
|
rotated_image_pil = rotate_by_angle(mirror_image_pil, angle=7, color="white")
|
|
return rotated_image_pil
|
|
except Exception as e:
|
|
logger.error(f"flip_and_rotate_image 처리 중 에러 발생 : {e}")
|
|
return image_pil
|