gpt4 book ai didi

python - 使用 Tesseract 识别页面上的单个字符

转载 作者:行者123 更新时间:2023-12-04 15:34:59 27 4
gpt4 key购买 nike

enter image description here

此图像返回空字符串;

基本上我正在尝试为 WOW 游戏制作一个机器人,但我对这个 OCR 东西真的很陌生。我不能让 tesseract 来阅读这张图片;我想要一个无序列表的字符,如果可能的话,包含它们的每个方块的坐标。有没有办法做到这一点?

感谢您的时间!

这是我的代码:

from PIL import Image
import cv2
from pytesseract import image_to_string

column = Image.open('photo.png')
gray = column.convert('L')
blackwhite = gray.point(lambda x: 255 if x < 200 else 0, '1')
blackwhite.save("code_bw.jpg")


print(image_to_string(cv2.imread("code_bw.jpg")))

最佳答案

您需要进行一些预处理以隔离文本字符。一个简单的方法是通过大津阈值获得二值图像,然后我们可以使用纵横比+轮廓面积找到轮廓和过滤。这将为我们提供文本的边界框坐标,我们可以将其绘制到蒙版上。我们用输入图像按位和掩码来获得我们清洁过的图像,然后将其放入 OCR。结果如下:

检测到的文本字符

enter image description here

结果

enter image description here

OCR 的结果

A
A R
P

代码
import cv2
import pytesseract
import numpy as np

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

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and filter using aspect ratio and area
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
x,y,w,h = cv2.boundingRect(c)
ar = w / float(h)
if area > 1000 and ar > .85 and ar < 1.2:
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.rectangle(mask, (x, y), (x + w, y + h), (255,255,255), -1)
ROI = original[y:y+h, x:x+w]

# Bitwise-and to isolate characters
result = cv2.bitwise_and(original, mask)
result[mask==0] = 255

# OCR
data = pytesseract.image_to_string(result, lang='eng',config='--psm 6')
print(data)

cv2.imshow('image', image)
cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.waitKey()

关于python - 使用 Tesseract 识别页面上的单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60066481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com