How to crop an image in OpenCV using Python

后端 未结 9 2201
面向向阳花
面向向阳花 2020-11-22 08:45

How can I crop images, like I\'ve done before in PIL, using OpenCV.

Working example on PIL

im = Image.open(\'0.png\').convert(\'L\')
im = im.crop((1         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 09:13

    Robust crop with opencv copy border function:

    def imcrop(img, bbox):
       x1, y1, x2, y2 = bbox
       if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
            img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
       return img[y1:y2, x1:x2, :]
    
    def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
        img = cv2.copyMakeBorder(img, - min(0, y1), max(y2 - img.shape[0], 0),
                                -min(0, x1), max(x2 - img.shape[1], 0),cv2.BORDER_REPLICATE)
       y2 += -min(0, y1)
       y1 += -min(0, y1)
       x2 += -min(0, x1)
       x1 += -min(0, x1)
       return img, x1, x2, y1, y2
    

提交回复
热议问题