Crop black edges with OpenCV

后端 未结 7 1507
遥遥无期
遥遥无期 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:31

    How about a slick little recursive function?

    import cv2
    import numpy as np
    def trim(frame):
        #crop top
        if not np.sum(frame[0]):
            return trim(frame[1:])
        #crop bottom
        elif not np.sum(frame[-1]):
            return trim(frame[:-2])
        #crop left
        elif not np.sum(frame[:,0]):
            return trim(frame[:,1:]) 
        #crop right
        elif not np.sum(frame[:,-1]):
            return trim(frame[:,:-2])    
        return frame
    

    Load and threshold the image to ensure the dark areas are black:

    img = cv2.imread("path_to_image.png")   
    thold = (img>120)*img
    

    Then call the recursive function

    trimmedImage = trim(thold)
    

提交回复
热议问题