Cropping image

As all you know sometimes cropping image can be challenging. Some days ago I had some issues in cropping part of my training image. My problem was my region wasn’t rectangular, so here is my solution to non-rectangular region cropping. I hope in would be useful for us as well 🙂

import cv2
import numpy as np

def cropping_region(path, corner_points):
      This function crops part of the image using corners of cropping region.
      c_point: corner points (e.g., [(444, 203), (623, 243), (691, 177), (581, 26)] )
      path: path to image
    img = cv2.imread(path, -1)
    corner_points_arr=np.array([corner_points], dtype=np.int32)
    # mask 
    mask = np.zeros(img.shape, dtype=np.uint8) 

    # fill the the match region 
    channel_count = img.shape[2]  
    ignore_mask = (255,)*channel_count
    cv2.fillPoly(mask, corner_points_arr, ignore_mask)

    # apply the mask
    wanted_region = cv2.bitwise_and(img, mask)
    return wanted_region

Leave a Reply

Your email address will not be published. Required fields are marked *