如何从裁剪图像中对蓝色背景上带有白色字符的文本进行 OCR?

How to OCR a text with white colour characters on a blue background from a cropped image?

首先,我想使用鼠标事件裁剪图像,然后打印裁剪图像内的文本。我尝试了 OCR 脚本,但都无法用于下面附上的这张图片。我认为原因是文本有蓝底白字。

你能帮我做这个吗?

全图:

裁剪后的图片:

我试过的一个例子是:

import pytesseract
import cv2
import numpy as np

pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files\Tesseract-OCR\tesseract.exe'

img = cv2.imread('D:/frame/time 0_03_.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
adaptiveThresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 35, 30)
inverted_bin=cv2.bitwise_not(adaptiveThresh)

#Some noise reduction
kernel = np.ones((2,2),np.uint8)
processed_img = cv2.erode(inverted_bin, kernel, iterations = 1)
processed_img = cv2.dilate(processed_img, kernel, iterations = 1)
 
#Applying image_to_string method
text = pytesseract.image_to_string(processed_img)
 
print(text)

[编辑]

对于任何想知道的人,问题中的图像在发布我的答案后已更新。那是原始图像:

因此,我原来的答案输出如下。

这是新发布的图片:

特定的土耳其语字符,尤其是最后一个词,仍然没有被正确检测到(因为我现在仍然不能使用 lang='tur'),但至少 ÖÜ 可以使用 lang='deu' 来检测,我已经安装了:

text = pytesseract.image_to_string(mask, lang='deu').strip().replace('\n', '').replace('\f', '')
print(text)
# GÖKYÜZÜ AVCILARI ILE TEKE TEK KLASIGI

[/编辑]


我不会在这里使用 cv2.adaptiveThreshold,而是简单地 cv2.threshold 使用 cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV。由于逗号触及图像边框,我将通过 cv2.copyMakeBorder 添加另一个一个像素宽的边框以正确捕获逗号。所以,这就是完整的代码(替换 \f 是因为我的 pytesseract 版本):

import cv2
import pytesseract

img = cv2.imread('n7nET.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mask = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)[1]
mask = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_CONSTANT, 0)
text = pytesseract.image_to_string(mask).strip().replace('\n', '').replace('\f', '')
print(text)
# 2020'DE SALGINI BILDILER, YA 2021'DE?

输出对我来说似乎是正确的——当然,对于这个带有上面的点的特殊(我假设是土耳其语)大写 I 字符来说不是。不幸的是,我不能 运行 pytesseract.image_to_string(..., lang='tur'),因为它根本没有安装。也许,也可以在这里查看以获取正确的字符。

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
PyCharm:       2021.1.1
OpenCV:        4.5.1
pytesseract:   5.0.0-alpha.20201127
----------------------------------------