如何使用pytesseract获得每一行的信心

Bol*_*boa 4 ocr tesseract image-processing python-3.x python-tesseract

我已经成功设置Tesseract并且可以将图像转换为文本...

text = pytesseract.image_to_string(Image.open(image))
Run Code Online (Sandbox Code Playgroud)

但是,我需要获得每一行的置信度值。我找不到使用pytesseract做到这一点的方法。有人知道怎么做吗?

我知道这可以使用PyTessBaseAPI,但我不能使用它,我花了几个小时试图设置它但没有运气,所以我需要一种使用pytesseract来做到这一点的方法。

Bol*_*boa 14

找了很久,终于找到了办法。相反image_to_string,应该使用image_to_data. 但是,这将为您提供每个单词的统计信息,而不是每一行...

text = pytesseract.image_to_data(Image.open(file_image), output_type='data.frame')
Run Code Online (Sandbox Code Playgroud)

所以我所做的是将它保存为一个数据框,然后用于pandasgroup by block_num,因为每行都使用 OCR 分组为块,我还删除了所有没有置信度值 (-1) 的行...

text = text[text.conf != -1]
lines = text.groupby('block_num')['text'].apply(list)
Run Code Online (Sandbox Code Playgroud)

使用相同的逻辑,您还可以通过计算同一块内所有单词的平均置信度来计算每行的置信度......

conf = text.groupby(['block_num'])['conf'].mean()
Run Code Online (Sandbox Code Playgroud)


San*_*Dey 6

@Srikar Appalaraju 是对的。以下面的示例图像为例:

\n

在此输入图像描述

\n

现在使用以下代码:

\n
text = pytesseract.image_to_data(gray, output_type=\'data.frame\')\ntext = text[text.conf != -1]\ntext.head()\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n

请注意,所有五行都具有相同的block_num,因此如果我们使用该列进行分组,则所有 5 个单词(文本)将被分组在一起。但这不是我们想要的,我们只想对属于第一行的前 3 个单词进行分组,并且为了正确地(以通用方式)对足够大的图像进行分组,我们需要按所有单词进行分组4 列page_numblock_numpar_numline_num同时计算第一行的置信度,如以下代码片段所示:

\n
lines = text.groupby([\'page_num\', \'block_num\', \'par_num\', \'line_num\'])[\'text\'] \\\n                                     .apply(lambda x: \' \'.join(list(x))).tolist()\nconfs = text.groupby([\'page_num\', \'block_num\', \'par_num\', \'line_num\'])[\'conf\'].mean().tolist()\n    \nline_conf = []\n    \nfor i in range(len(lines)):\n    if lines[i].strip():\n        line_conf.append((lines[i], round(confs[i],3)))\n
Run Code Online (Sandbox Code Playgroud)\n

具有以下所需的输出:

\n
[(\'Ying Thai Kitchen\', 91.667),\n (\'2220 Queen Anne AVE N\', 88.2),\n (\'Seattle WA 98109\', 90.333),\n (\'\xc2\xab (206) 285-8424 Fax. (206) 285-8427\', 83.167),\n (\'\xe2\x80\x98uw .yingthaikitchen.com\', 40.0),\n (\'Welcome to Ying Thai Kitchen Restaurant,\', 85.333),\n (\'Order#:17 Table 2\', 94.0),\n (\'Date: 7/4/2013 7:28 PM\', 86.25),\n (\'Server: Jack (1.4)\', 83.0),\n (\'44 Ginger Lover $9.50\', 89.0),\n (\'[Pork] [24#]\', 43.0),\n (\'Brown Rice $2.00\', 95.333),\n (\'Total 2 iten(s) $11.50\', 89.5),\n (\'Sales Tax $1.09\', 95.667),\n (\'Grand Total $12.59\', 95.0),\n (\'Tip Guide\', 95.0),\n (\'TEK=$1.89, 18%=62.27, 20%=82.52\', 6.667),\n (\'Thank you very much,\', 90.75),\n (\'Cone back again\', 92.667)]\n
Run Code Online (Sandbox Code Playgroud)\n