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

How to extract text from the highlighted text from an image

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

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))

我已经根据我的图片设置了坐标,你可以根据你的调整,我需要提取矩形框下突出显示的文字。 我是这个领域的新手,请忽略我可能犯的任何错误。

这是我对问题的部分解决方案。

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

预处理将帮助您删除不需要的伪影。

例如你可以做 thresholding: Thresholding-result

median过滤:Median-filter result

我用的是thresholding,那你可以用pytesseract库。该库包含很多 .

对于非英语语言,您可以遵循此 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)