Crop black edges with OpenCV

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

    import numpy as np
    
    def autocrop(image, threshold=0):
        """Crops any edges below or equal to threshold
    
        Crops blank image to 1x1.
    
        Returns cropped image.
    
        """
        if len(image.shape) == 3:
            flatImage = np.max(image, 2)
        else:
            flatImage = image
        assert len(flatImage.shape) == 2
    
        rows = np.where(np.max(flatImage, 0) > threshold)[0]
        if rows.size:
            cols = np.where(np.max(flatImage, 1) > threshold)[0]
            image = image[cols[0]: cols[-1] + 1, rows[0]: rows[-1] + 1]
        else:
            image = image[:1, :1]
    
        return image
    

提交回复
热议问题