import math ,pytesseract ,cv2
from PIL import Image
# 转化图像为白底黑字,一定要转化,能提高识别准确性
def transformedImage():
# 计算两个颜色之间的欧几里得距离
def color_distance(c1, c2):
r1, g1, b1, a1 = c1
r2, g2, b2, a2 = c2
return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2 + (a1-a2)**2)
# 打开原图
img = Image.open(r'screen\screen.png')
# 创建一个白色的背景图像
bg_img = Image.new('RGBA', img.size, (255, 255, 255, 255))
# 定义相似颜色的阈值,5~200之间为最佳值,5~500为有效值
threshold = 100
# 遍历所有像素点
for x in range(img.width):
for y in range(img.height):
# 获取当前像素点的颜色
color = img.getpixel((x, y))
# 如果原图当前坐标颜色与给定颜色相似,则在背景图中相同的坐标写入黑色像素点
if color_distance(color, (247, 245, 244, 255)) < threshold:
bg_img.putpixel((x, y), (0,0,0,255))
# 保存新图像
bg_img.save(r'screen\screen2.png')
characterRecognition()
# 文字识别
def characterRecognition():
# 感觉好像没有必要进行灰度和二值化处理了,白底黑字的准确性挺高的,代码留这,你们自己看着整
# 读取新图像
# img = cv2.imread(r'screen\screen2.png')
# # 将图片转换为灰度图像
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# # 对图像进行二值化处理
# thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# config = "--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789"
# text = pytesseract.image_to_string(thresh, config=config)
# 读取新图像
img = cv2.imread(r'screen\screen2.png')
# 进行文字识别
# --psm 7 单行识别 , --oem 3 使用 LSTM OCR 引擎 , -c tessedit_char_whitelist=0123456789 只识别数字字符
config = "--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789"
text = pytesseract.image_to_string(img, config=config)
# 防止识别不到报错
try:
# 去除其他符号,对数字进行重新整合
text = int(''.join(filter(str.isdigit, text)))
except Exception:
text = 1
if __name__ == "__main__":
transformedImage()