Opencv 이용
더보기
def to_padding(image):
height = image.shape[0]
width = image.shape[1]
top, bottom, left, right = 0, 0, 0, 0
if height > width:
left, right = (height - width) // 2, (height - width) // 2
else:
top, bottom = (width - height) // 2, (width - height) // 2
new_image = cv.copyMakeBorder(image, top, bottom, left, right, cv.BORDER_CONSTANT, value=(0, 0, 0))
# cv.imshow('test', new_image)
# cv.waitKey(0)
return new_image
Opencv 없이 붙이기
더보기
def resize_aspect_ratio(img, final_h, final_w):
height, width, channel = img.shape
ratio = 0
# height = 8914
# width = 6457
target_w_size = final_w
target_h_size = final_h
h_ratio = target_h_size / height
target_h, target_w = int(height * h_ratio), int(width * h_ratio)
diff = target_w_size - target_w
if diff > 0:
resized = cv2.resize(img, (target_w, target_h), interpolation=interpolation)
pad_array = np.ones(shape=(target_h_size, diff, 3), dtype=np.uint8)
# pad_array = np.full(shape=(target_h_size, diff, 3), 255)
resized = np.append(resized, pad_array, axis=1)
ratio = h_ratio
else:
w_ratio = target_w_size / width
target_h, target_w = int(height * w_ratio), int(width * w_ratio)
diff = target_h_size - target_h
resized = cv2.resize(img, (target_w, target_h), interpolation=interpolation)
pad_array = np.ones(shape=(diff, target_w_size, 3), dtype=np.uint8)
resized = np.append(resized, pad_array, axis=0)
ratio = w_ratio
cv2.imshow('test', resized)
cv2.waitKey(0)
여기서
target_w_size, target_h_size가 원하는 이미지의 크기이고,
이미지가 비율을 일정하게 유지하면서 padding을 붙여서 원하는 크기의 이미지로 resize하는 코드
'기록해둘 코드 > python' 카테고리의 다른 글
Opencv를 이용하여 Fafce Align 하기! (1) | 2022.09.29 |
---|