从具有不同行颜色的图像(OCR)中读取数字表

2024-04-20 07:10:26 发布

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

我想从附加图像(png文件)中读取数字表

enter image description here

我的代码如下:

import cv2
import imutils
import pytesseract
import os

image = cv2.imread(os.path.join(image_path, image_name))
image = imutils.resize(image, width=500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

thresh = 255 - cv2.GaussianBlur(thresh, (5,5), 0)
data = pytesseract.image_to_string(thresh, lang='eng', config='--psm 6')

print(data)

结果是:

0.74 0.73 0.72
0.72 0.71 0.71
0.71 0.70 0.70

如我们所见,它遗漏了以蓝色突出显示的行

我的问题是,我们是否可以调整图像,以便正确地读取丢失的行


Tags: 文件path图像imageimportdatapngos
1条回答
网友
1楼 · 发布于 2024-04-20 07:10:26

我可以通过将图像大小调整2倍来读取数据

from PIL import Image
import pytesseract

img = Image.open('PBdvo.png')
img_larger = img.resize((img.width*2,img.height*2)) 
data = pytesseract.image_to_string(img_larger)
print(data)

结果:

0.74 0.73 0.72
0.73 0.72 0.72
0.72 0.71 0.71
0.71 0.70 0.70

编辑:根据你的新的、更大的图像,我做了如下调整:

from PIL import ImageFilter

img = Image.open('doc0m.png') 
img_larger = img.resize((round(img.width*2.5),round(img.height*2.5))) 
img_enhanced_more = img_larger.filter(ImageFilter.EDGE_ENHANCE_MORE)
data = pytesseract.image_to_string(img_enhanced_more)

然后我注意到数据是以列的形式返回的,因此如果您希望以行的形式返回数据,可以执行以下操作:

for i in zip(*[column.split('\n') for column in data.split('\n\n')]): 
    print(i) 

其中:

('1.04', '1.03', '1.03', '1.02', '1.01')
('1.02', '1.01', '1.00', '1.00', '0.99')
('1.00', '0.99', '0.98', '0.97', '0.97')
('0.97', '0.97', '0.96', '0.95', '0.95')
('0.95', '0.95', '0.94', '0.93', '0.92')
('0.93', '0.92', '0.92', '0.91', '0.30')
('0.91', '0.90', '0.90', '0.89', '0.88')
('0.89', '0.88', '0.88', '0.87', '0.86')
('0.87', '0.86', '0.86', '0.85', '0.84')
('0.85', '0.84', '0.84', '0.83', '0.82')
('0.83', '0.82', '0.82', '0.81', '0.80')
('0.81', '0.80', '0.80', '0.79', '0.78')
('0.79', '0.78', '0.78', '0.77', '0.76')
('0.77', '0.76', '0.76', '0.75', '0.74')
('0.76', '0.75', '0.75', '0.74', '0.73')
('0.75', '0.74', '0.74', '0.73', '0.72')
('0.74', '0.74', '0.73', '0.72', '0.72')
('0.73', '0.73', '0.72', '0.71', '0.71')
('0.72', '0.72', '0.71', '0.70', '0.70')
('0.71', '0.71', '0.70', '0.69', '0.69')
('0.71', '0.70', '0.69', '0.69', '0.68')
('0.70', '0.69', '0.68', '0.68', '0.67')
('0.69', '0.68', '0.67', '0.67', '0.66')
('0.68', '0.67', '0.67', '0.66', '0.65')
('0.67', '0.66', '0.66', '0.65', '0.64')
('0.66', '0.65', '0.65', '0.64', '0.63')
('0.65', '0.65', '0.64', '0.63', '0.63')
('0.64', '0.64', '0.63', '0.62', '0.62')
('0.63', '0.63', '0.62', '0.62', '0.61')
('0.63', '0.62', '0.61', '0.61', '0.60')
('0.62', '0.61', '0.60', '0.60', '0.59')

相关问题 更多 >