Python - OpenCV pytesseract 不从裁剪图像中提取字符串

问题描述

我有一张图片(附件),想从表单中提取某些字段。例如名字“莎拉”,她的电子邮件地址等。我有感兴趣的区域,它被突出显示,然后被裁剪。出于某种原因,我从图像到字符串的输出显示为空?

所需的输出提取数据。请有人能指出我正确的方向吗? 我正在关注这个很棒的上下文教程:https://www.youtube.com/watch?v=cUOcY9ZpKxw

['','','']

代码如下:


import cv2
import numpy as np
import PyTesseract
import os
PyTesseract.PyTesseract.tesseract_cmd = r'Tesseract-OCR\tesseract.exe'

imgQ = cv2.imread('Sarah.png')

#cv2.imshow('output',imgQ)
#cv2.waitKey(0)

roi = [[(98,984),(680,1074),'text','Name'],[(740,980),(1320,1078),'Phone'],[(100,1418),(686,1518),'Email'],1416),(1318,1512),'ID'],[(110,1598),(676,1680),'City'],[(748,1592),(1328,1686),'Country']]

myData=[]
for x,r in enumerate(roi):
        #highlighted the regions
        cv2.rectangle(imgQ,(r[0][0],r[0][1]),(r[1][0],r[1][1]),(0,255,0),cv2.FILLED)
        imgShow = cv2.addWeighted(imgQ,0.99,imgQ,0.1,0)
        #crop regions
        imgCrop = imgShow[r[0][1]:r[1][1],r[0][0]:r[1][0]]
        cv2.imshow(str(x),imgCrop)
        if r[2] == 'text':

            print('{} :{}'.format(r[3],PyTesseract.image_to_string(imgCrop)))
            myData.append(PyTesseract.image_to_string(imgCrop))
print(myData)    
            

image example here (also used in tutorial)

解决方法

您的代码中的问题是以下行:

cv2.rectangle(img,(r[0][0],r[0][1]),(r[1][0],r[1][1]),(0,255,0),cv2.FILLED)
  • 这一行执行什么?

在给定图像中找到 roi 并用绿色填充。喜欢:

enter image description here

然后您尝试从这个绿色矩形读取数据 enumerate(roi) 次。


  • 第二,为什么imgShow = cv2.addWeighted(img,0.99,img,0.1,0)

  • 第三个imgCrop = imgShow[r[0][1]:r[1][1],r[0][0]:r[1][0]]

我们从 img 中裁剪怎么样?

  • enter image description here

  • enter image description here

  • enter image description here

  • ...

输出是

Name :Sarah

Phone :+ (00) 765-43-21

Email :[email protected]

ID :1356856

City :London

Country :United Kingdom

代码:


import cv2
from pytesseract import image_to_string

img = cv2.imread("hzt5U.png")
# gry = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# thr = cv2.adaptiveThreshold(gry,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,21,21)
# txt = image_to_string(thr,config="--psm 6")
# print(txt)

roi = [[(98,984),(680,1074),'text','Name'],[(740,980),(1320,1078),'Phone'],[(100,1418),(686,1518),'Email'],1416),(1318,1512),'ID'],[(110,1598),(676,1680),'City'],[(748,1592),(1328,1686),'Country']]

my_data = []

for x,r in enumerate(roi):
    # highlighted the regions
    # cv2.rectangle(img,cv2.FILLED)
    # imgShow = cv2.addWeighted(img,0)

    # crop regions
    # imgCrop = imgShow[r[0][1]:r[1][1],r[0][0]:r[1][0]]
    imgCrop = img[r[0][1]:r[1][1],r[0][0]:r[1][0]]
    cv2.imwrite("/Users/ahx/Desktop/res{}.png".format(x),imgCrop)
    cv2.imshow(str(x),imgCrop)
    cv2.waitKey(0)

    if r[2] == 'text':
        print('{} :{}'.format(r[3],image_to_string(imgCrop)))
        my_data.append(image_to_string(imgCrop))

# print(my_data)