通过包围框从图像中提取选定的文本 [英] Extracting selected text by bounding box from an image

查看:95
本文介绍了通过包围框从图像中提取选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过在图像上加上边框来获取选定的文本. 例如,如果仅通过边界框选择单词,并且我想获取该文本并将其转换为文本文件. 请查看我的代码并进行一些检查,以便我可以实现该功能.

I am trying to fetch selected text by bounding box on an Image. like if only on word is selected by bounding box and I want to fetch that text and convert it into the text file. Please see my code and give some review so I can implement that functionality.

到目前为止,我已经完成了将PDF文件转换为带有文本边界框的图像的操作.

So far what I've done I've converted the PDF file to image with bounding box over the text.

import numpy as np
import csv
import io
from PIL import Image
import pytesseract
from wand.image import Image as wi
from pytesseract import Output
import cv2

pdf = wi(filename="samplecompany.pdf", resolution=100)
pdfImg = pdf.convert('jpg')
j = 1
for img in pdfImg.sequence:
    page = wi(image=img)
    page.save(filename=str(j)+".jpg")
    img1 = cv2.imread(str(j)+".jpg")

    d = pytesseract.image_to_data(img1, output_type=Output.DICT)
    n_boxes = len(d['level'])
    print(n_boxes)
    for i in range(n_boxes):
        (x, y, w, h) = (d['left'][i], d['top']
                        [i], d['width'][i], d['height'][i])
        print((x, y, w, h))
        cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv2.imwrite(str(j)+".jpg", img1)

    cv2.waitKey(0)
    j += 1

此代码运行良好,我需要使用边界框位置从创建的图像中提取所需的文本

this code is working fine I need to fetch desired text from images which I've created.using bounding box location

推荐答案

您可以使用此代码从图像中获取自定义文本,并进行相应的更改和修改 这也将您的文本保存到文本文件中

You can use this code to get custom text from a an image and change and modify accordingly and this is also save your text to an text file

import io
import cv2
import numpy as np
import pytesseract
from PIL import Image
from pytesseract import Output
from wand.image import Image as wi
import sys


pdf = wi(filename="Resume.pdf", resolution=100)
pdfImg = pdf.convert('jpg')
j = 1
imgBlobs = []
img1= []
for img in pdfImg.sequence:
    page = wi(image=img)
    page.save(filename=str(j)+".jpg")
    img1.append(cv2.imread(str(j)+".jpg"))
    j += 1

extracted_text = []

for img2 in img1:
    d = pytesseract.image_to_data(img2, output_type=Output.DICT)
    n_boxes = len(d['level'])
    print(n_boxes)
    extracted_text.append(d['text'][9])
    (x, y, w, h) = (d['left'][9], d['top'][9], d['width'][9], d['height'][9])
    cv2.rectangle(img2, (x, y), (x + w, y + h), (0, 255, 0), 2)


    cv2.imshow('img', img2)

    print(d)


with open('Prototype.txt', 'w') as filehandle:
        for listitem in extracted_text:
            filehandle.write('%s\n' % listitem)

这篇关于通过包围框从图像中提取选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆