How to remove whitespace from an image in OpenCV?

后端 未结 2 1872
名媛妹妹
名媛妹妹 2020-12-14 19:03

I have the following image which has text and a lot of white space underneath the text. I would like to crop the white space such that it looks like the second image.

2条回答
  •  温柔的废话
    2020-12-14 19:47

    Opencv reads the image as a numpy array and it's much simpler to use numpy directly (scikit-image does the same). One possible way of doing it is to read the image as grayscale or convert to it and do the row-wise and column-wise operations as shown in the code snippet below. This will remove the columns and rows when all pixels are of pixel_value (white in this case).

    def crop_image(filename, pixel_value=255):
        gray = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
        crop_rows = gray[~np.all(gray == pixel_value, axis=1), :]
        cropped_image = crop_rows[:, ~np.all(crop_rows == pixel_value, axis=0)]
        return cropped_image
    

    and the output:

提交回复
热议问题