[Solved] Remove white space from an image using python


The code is almost perfect. It just can’t crop on the right side because of the scrollbar. And it does not consider some padding (which you liked according the comments).

The thing I removed is the topology modification.

import numpy as np
import cv2

img = cv2.imread('cropwhitefromimage.png')
scrollbarright = 20
img = img[:, :-scrollbarright]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = 255*(gray < 128).astype(np.uint8)
coords = cv2.findNonZero(gray)
x, y, w, h = cv2.boundingRect(coords)
padding = 10
rect = img[y-padding:y+h+padding, x-padding:x+w+padding]
cv2.imshow("Cropped", rect)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("cropwhitefromimage_result.png", rect)

4

solved Remove white space from an image using python