Created
July 7, 2023 16:24
-
-
Save gsoykan/5c902f84f473dc58c99fded708f66b70 to your computer and use it in GitHub Desktop.
cropping a bounding box and segmentation box from image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def crop_all_components(self, | |
page_img_path: str, | |
save_root_folder: str, | |
original_img_shape: Tuple[int, int, int], # h, w, c | |
transformed_img_shape: Tuple[int, int, int]): | |
comic_series, page = page_img_path.split('/')[-2:] | |
page = page.split('.')[0] | |
scale_h_w = np.array(original_img_shape[:2]) / np.array(transformed_img_shape[:2]) | |
img = cv2.imread(page_img_path) | |
def crop_with_mask(mask): | |
mask_resized = cv2.resize(mask, (original_img_shape[:2][1], original_img_shape[:2][0])) | |
contours, _ = cv2.findContours(mask_resized, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
largest_contour = max(contours, key=cv2.contourArea) | |
blank_mask = np.zeros_like(img) | |
cv2.drawContours(blank_mask, contours, -1, (255, 255, 255), thickness=cv2.FILLED) | |
masked_image = cv2.bitwise_and(img, blank_mask) | |
x, y, w, h = cv2.boundingRect(largest_contour) | |
cropped_image = masked_image[y:y + h, x:x + w] | |
return cropped_image | |
def crop(bb, | |
scale: Optional[float] = None, | |
make_square: bool = False): | |
x_min, y_min, x_max, y_max = bb | |
if scale is not None or make_square: | |
center_x = (x_min + x_max) // 2 | |
center_y = (y_min + y_max) // 2 | |
width = x_max - x_min | |
height = y_max - y_min | |
if make_square: | |
width, height = max(width, height), max(width, height) | |
if scale is not None: | |
width, height = width * scale, height * scale | |
x_min, x_max = center_x - width // 2, center_x + width // 2 | |
y_min, y_max = center_y - height // 2, center_y + height // 2 | |
x_min, x_max = int(x_min * scale_h_w[1]), int(x_max * scale_h_w[1]) | |
y_min, y_max = int(y_min * scale_h_w[0]), int(y_max * scale_h_w[0]) | |
return img[y_min:y_max, x_min:x_max] | |
# save comic book panel | |
panel_path = os.path.join(save_root_folder, | |
'panel', | |
str(comic_series), | |
str(page), | |
f'{self.box_id}.jpg') | |
os.makedirs(os.path.dirname(panel_path), exist_ok=True) | |
cv2.imwrite(panel_path, crop(self.box)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment