Search code examples
pythonpython-3.ximage-processingpython-imaging-librarycrop

Detect text position in an image and crop it in Python


I have this picture Text in an image

I want to detect that text position, and crop the image focusing only at that text.

this my code:

from PIL import Image 
# Opens a image in RGB mode 
im = Image.open(r"image.jpg") 
# Size of the image in pixels (size of orginal image) 
# (This is not mandatory) 
width, height = im.size 
print(im.size)
# Setting the points for cropped image 
left = 5
top = height / 4
right = 164
bottom = 3 * height / 4
# Cropped image of above dimension 
# (It will not change orginal image) 
im1 = im.crop((left, top, right, bottom)) 
# Shows the image in image viewer 
im1.save("new.jpg")

This code work fine, but the position of the text in the image not static. I want the code automatically detect the position of the text then crop it.


Solution

  • You can use getbbox() to get the bounding box:

    image=Image.open('text.jpg') 
    x1,y1,x2,y2=image.getbbox() 
    print(x1,y1,x2,y2)   
    

    Output

    16 192 208 216
    

    enter image description here