Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove white space from an image using python

There are multiple images that have white spaces that I need to remove. Simply to crop the image so as to get rid of the white spaces
Here’s the code I found but didn’t satisfy my needs

import numpy as np
import cv2

img = cv2.imread('Sample.png')
img = img[:-5,:-5] 
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = 255*(gray < 128).astype(np.uint8)
gray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((2, 2), dtype=np.uint8))
coords = cv2.findNonZero(gray)
x, y, w, h = cv2.boundingRect(coords)
rect = img[y:y+h, x:x+w] 
cv2.imshow("Cropped", rect)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("Output.png", rect)

Here’s the sample image

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And this is the desired output

enter image description here

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading