简体   繁体   中英

Crop bounding box from PyTesseract

I am using pytesseract to determine individual characters on an image. I am using the image_to_boxes function which provides me with the character and co-ordinates. However, I need to crop the individual characters into single image files. Currently, the code below will create the bounding box however I need it to crop the characters and save it into separate image files for each character.

filename = 'image.png'

# read the image and get the dimensions
img = cv2.imread(filename)
h, w, _ = img.shape # assumes color image

# run tesseract, returning the bounding boxes
boxes = pytesseract.image_to_boxes(img) 

# draw the bounding boxes on the image
for b in boxes.splitlines():
    b = b.split(' ')
    img = cv2.rectangle(img, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 255, 0), 2)

You can use pillow's crop function:

from PIL import Image
img = Image.open("samp.png")

text = pytesseract.image_to_boxes(img).split("\n")

for i in text:
    if i:
        (left, upper, right, lower) = list(map(int, i.split(" ")[1:-1]))
        im_crop = img.crop((left, upper, right, lower))
        plt.imshow(im_crop)
        plt.show()

OR

roi = img[lower:upper, left:right]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM