需要用pytesseract识别黑色背景上的红色文本:程序无法识别红色
我们先来看一张图片:
我现在的任务是用pytesseract从这张图片中提取文字。
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = "tesseract/tesseract.exe"
image_path = 'img4.png'
img = cv2.imread(image_path)
# cropped_img = img[195:820, 760:1160] this is for other photo
gray_img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY) # COLOR_BGRA2GRAY
text = pytesseract.image_to_string(gray_img, config='--oem 3 --psm 6')
print(text)
程序输出的结果是:
Day 1382, 03:23:17:
因为红色的文字变成了很深的灰色,tesseract看不见它。
我已经尝试了很多方法来转换这个深色,但都太老旧了,没什么效果。
比如,这段代码:
new_img = np.where(
(gray_img == 31).all(axis=2),
np.full_like(gray_img, 255),
gray_img,
)
2 个回答
0
程序看不到红色
这个问题是可以解决的。
代码片段:
import cv2
import pytesseract
#pytesseract.pytesseract.tesseract_cmd = "tesseract/tesseract.exe"
image = cv2.imread("img4.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# use Tesseract to OCR the image
text = pytesseract.image_to_string(image)
print(text)
cv2.waitKey(0)
输出结果:
Day_1382, 03:23:17: Your Baby Dodo.-.t.vi.20
(Dodo) was killed by 123 - Lvl 75= COA ry
AKnights of apocalypse)!
2
为了让你的文字识别更准确,你需要先做一些准备工作。这里有一种方法可以参考:
import cv2
import pytesseract
%matplotlib notebook
import matplotlib.pyplot as plt
pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract-OCR/tesseract.exe"
im = cv2.cvtColor(cv2.imread("text.png"), cv2.COLOR_BGR2RGB)
r, g, b = cv2.split(im) # maybe group text according to color if you want?
plt.imshow(r)
rThreshold = cv2.threshold(r, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
text = pytesseract.image_to_string(rThreshold)
print(text)
比如,你可以使用红色通道来处理图片:
然后再设置一个阈值,这样你就能得到这些文字:
Day 1382, 03:23.17. Your Baby Dodo - Li 20
(Dodo) was killed by 123 - Lvl 75-364901198
(Knights of apocalypse)!
我觉得,如果能有更多的例子会更好,这样你就能更清楚地了解你的文字大概是什么样子的。希望这些对你有帮助!