Home > Blockchain >  How to remove blank space from cropped image om opencv?
How to remove blank space from cropped image om opencv?

Time:06-19

I am trying to crop a specific part of a frame in opencv to get a cropped image of the detections from mobilenet ssd model. The code to crop the image is like this

for box_id in boxes_ids:
                        x,y,w,h,id = box_id
                        crop=frame[y:h,x:w]
                        cv2.imshow("d",crop)
                        cv2.waitKey(5)

This code is producing a blank space towards the right of all the images that I extract :

Cropped Image

Please tell me how can i fix this.

CodePudding user response:

try using Pillow that helps

def trim(im, color):
    bg = Image.new(im.mode, im.size, color)
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)

This function will probably take it out, just be carefull that this will only work if the segment of image has consistent pixels

CodePudding user response:

as said before in the comments, there is a minimum window width, and smaller crops will be drawn on some neutral background.

but maybe it's more intuitive to draw the crop into an empty image, conserving its original position:

for box_id in boxes_ids:
    x,y,w,h,id = box_id
    draw = np.zeros(frame.shape, np.uint8)    
    draw[y:h,x:w] = frame[y:h,x:w]
    cv2.imshow("d",draw)
    cv2.waitKey(5)
  • Related