Crop black edges with OpenCV

后端 未结 7 1496
遥遥无期
遥遥无期 2020-12-01 01:08

I think it should be a very simple problem, but I cannot find a solution or an effective keyword for search.

I just have this image.

7条回答
  •  遥遥无期
    2020-12-01 01:16

    I am not sure whether all your images are like this. But for this image, below is a simple python-opencv code to crop it.

    first import libraries :

    import cv2
    import numpy as np
    

    Read the image, convert it into grayscale, and make in binary image for threshold value of 1.

    img = cv2.imread('sofwin.png')
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    _,thresh = cv2.threshold(gray,1,255,cv2.THRESH_BINARY)
    

    Now find contours in it. There will be only one object, so find bounding rectangle for it.

    contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    cnt = contours[0]
    x,y,w,h = cv2.boundingRect(cnt)
    

    Now crop the image, and save it into another file.

    crop = img[y:y+h,x:x+w]
    cv2.imwrite('sofwinres.png',crop)
    

    Below is the result :

    enter image description here

提交回复
热议问题