How to crop an image in OpenCV using Python

后端 未结 9 2110
面向向阳花
面向向阳花 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:02

    here is some code for more robust imcrop ( a bit like in matlab )

    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 = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
                   (np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
        y1 += np.abs(np.minimum(0, y1))
        y2 += np.abs(np.minimum(0, y1))
        x1 += np.abs(np.minimum(0, x1))
        x2 += np.abs(np.minimum(0, x1))
        return img, x1, x2, y1, y2
    

提交回复
热议问题