如何从图像中突出显示的文本中提取文本

2024-10-03 06:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从图像中突出显示用户名的代码,我想从该图像中提取文本,即用户名。下面是代码

import matplotlib.pyplot as plt
import cv2
import easyocr
from pylab import rcParams
from IPython.display import Image
rcParams['figure.figsize'] = 8, 16
reader = easyocr.Reader(['en'])
output = reader.readtext('MP-SAMPLE1.jpg')
cord = output[-106][0]
x_min, y_min = [int(min(idx)) for idx in zip(*cord)]
x_max, y_max = [int(max(idx)) for idx in zip(*cord)]

image = cv2.imread('MP-SAMPLE1.jpg')
cv2.rectangle(image,(x_min,y_min),(x_max,y_max),(0,0,255),2)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

我已经根据我的图像设置了坐标,你可以根据你的图像进行调整,我需要提取矩形框下高亮显示的文本。 我是这个领域的新手,请忽略我会犯的任何错误

enter image description here

enter image description here


Tags: 代码from图像image文本importpltmin
1条回答
网友
1楼 · 发布于 2024-10-03 06:32:46

这是我对这个问题的部分解决办法

既然你是初学者,让我给你一个建议,总是从预处理开始

预处理将帮助您删除不需要的工件

例如,您可以执行thresholding:Thresholding-result

median筛选:Median-filter result

我使用了thresholding,然后您可以使用pytesseract库。该库包含大量的configuration options

对于非英语语言,您也可以遵循此tutorial

因此,您希望文本位于FATHERS HUSBANDS旁边。因此,我们可以这样做

    1. 将图像转换为文本

      • text = pytesseract.image_to_string(Image.open(f_name), lang='eng')
        
    1. 从文本中,找到FATHERS HUSBANDS的等价物

      • for line in text.split('\n'):
            if "FATHERS HUSBANDS" in line:
                name = line.split('.')[1].split(',')[0]
                print(name)
        
      • 结果:

        • GRAMONAN GROVER
          

姓氏正确,但名字部分正确,应该是BRAJMONAN

我写下了这个答案,希望你能找到你的答案。祝你好运

代码:


import os
import cv2
import pytesseract

from PIL import Image

img = cv2.imread("FXSCh.jpg")
gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold
gry = cv2.threshold(gry, 0, 255,
                    cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

f_name = "{}.png".format(os.getpid())
cv2.imwrite(f_name, gry)

text = pytesseract.image_to_string(Image.open(f_name), lang='eng')

for line in text.split('\n'):
    if "FATHERS HUSBANDS" in line:
        name = line.split('.')[1].split(',')[0]
        print(name)

os.remove(f_name)

cv2.imshow("Image", img)
cv2.imshow("Output", gry)
cv2.waitKey(0)

相关问题 更多 >