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 whitespace of a image python opencv

I want to select a rectangular box from a image where all the content is placed. In other words I want remove the background of the image with unimportant(pixels which are not related to content) pixels. How ever the output image should be a rectangle.

What is the easiest way to do this in Python OpenCV?
(I will import files from a folder… Better if I could automate the process)

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

>Solution :

I hope what you asking is "Crop out the white spaces of image automatically".
Here we assume a binary image : pixels have high and low values.

def focusToContent(img):
    img_ = 255*(img < 128).astype(np.uint8) 
    coords = cv.findNonZero(img_) # Find all non-zero points (text)
    x, y, w, h = cv.boundingRect(coords) # Find minimum spanning bounding box
    
    rect = img[y:y+h, x:x+w] # Crop the image - note we do this on the original image
    rect_originalSized = cv.resize(rect,(img.shape))
    return rect_originalSized

img should be a opencv image (numpy array with proper data type)

Test the code

#testing
img = cv.imread(r"D:/ENTC/SEM_4/EN2550 - Fundamentals of Image Processing and Machine Vision/~images/int-rec/test/1650009171.5083215.png",0)
assert img is not None
focused = focusToContent(img)

fig,ax = plt.subplots(1,2)
ax[0].imshow(img,cmap="gray")
ax[1].imshow(focused,cmap="gray")
plt.show()

enter image description here

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