如何提升pytesseract识别在线图片数字的准确率?
优化pytesseract识别股票图表数字的方案需求
我需要从以下股票图表图片中提取数字数据,但pytesseract识别效果极差,希望得到有效优化方案:
已尝试的代码及问题
初始代码
import io import requests import pytesseract from PIL import Image response = requests.get("https://port.jpx.co.jp/jpx/chart/chart21.exe?template=ini/DayIndexCSV&basequote=151_2024&begin=2024/4/2&end=2024/04/02&mode=D") img = Image.open(io.BytesIO(response.content)) text = pytesseract.image_to_string(img) print(text) img.show() #Updated black and white version img.save('1.png') image = cv2.imread('1.png',0) _, thresh1 = cv2.threshold(image, 105, 255, cv2.THRESH_BINARY) _, thresh2 = cv2.threshold(image, 106, 255, cv2.THRESH_BINARY_INV) final_thresh = cv2.bitwise_and(thresh1, thresh2) im = Image.fromarray(final_thresh) text = pytesseract.image_to_string(im) print(text) im.show()
识别问题:大量数字(如2、4、5、6)被识别为“8”,分隔符有时识别为“.”有时为“,”。
裁剪聚焦区域尝试
w, h= img.size img2=img.crop((240, 185, w-220, h-220)) text = pytesseract.image_to_string(img2) print(text)
该区域真实值为“2,714.45”,但返回“eT AS”;添加配置后:
text = pytesseract.image_to_string(img2, config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789') print(text)
仅返回“1”。
调整DPI与阈值后的代码
from PIL import Image import pytesseract import requests import io response = requests.get("https://port.jpx.co.jp/jpx/chart/chart21.exe?template=ini/DayIndexCSV&basequote=151_2024&begin=2024/4/02&end=2024/04/02&mode=D") img = Image.open(io.BytesIO(response.content)) grayscale_image = img.convert("L") original_width, original_height = grayscale_image.size factor = 300/72 # enlarge from default 72 to 300 dpi new_width = int(original_width * factor) new_height = int(original_height * factor) enlarged_image = grayscale_image.resize((new_width, new_height)) threshold = 175 # found by trial/error (removes disturbing grid lines) bw_image = enlarged_image.point(lambda x: 0 if x < threshold else 255, '1') # mode='1' -> b/w w, h= bw_image.size bw_image=bw_image.crop((500, 0, w-300, h-480)) text = pytesseract.image_to_string(bw_image) print(text) bw_image.show()
输出结果仍有错误:
2U2d Ud Ue 2714.45 271445 2024/04/02
对应的处理后图片:
希望得到能精准识别图片中数字及日期的优化方案。
内容的提问来源于stack exchange,提问作者Wick
相关产品推荐
相关产品推荐

