学习记录技术分享小站

间隔图像文字识别优化

在使用Tesseract-OCR进行文字识别的时候,在图片内容发生变化的时候才进行识别能减少重复识别

背景

每隔一段时间在设定区域截图,然后调用Tesseract-OCR进行图像识别。这期间图像可能没有发生改变,如果直接调用Tesseract-OCR就重复操作了

比较图片MD5值

  • 编写MD5码函数

    def getMD5(path):
      with open(path, 'rb') as fp:
          data = fp.read()
      file_md5 = hashlib.md5(data).hexdigest()
      return file_md5
  • 调用函数比较MD5码
lastMD5 = None
newMD5 = None
while(1):
    # 截图
    ImageGrab.grab((pic_top_left_x, pic_top_left_y,
        pic_lower_right_x, pic_lower_right_y)).save('pic.jpg')
    newMD5 = getMD5('pic.jpg')
    # 判断MD5是否相等
    if lastMD5 != newMD5:
        lastMD5 = newMD5
        #这里写你要执行的操作
    # interval_time为设定的识别间隔时间
    time.sleep(interval_time)

判断图片的主要颜色

  • 判断图片的主要颜色
def get_dominant_color(image):
    # 颜色模式转换,以便输出rgb颜色值
    image = image.convert('RGBA')
    # 生成缩略图,减少计算量,减小cpu压力
    # image.thumbnail((100, 50))
    max_score = 0
    dominant_color = 0

    for count, (r, g, b, a) in image.getcolors(image.size [0] * image.size [1]):
        # 跳过纯黑色
        if a == 0:
            continue
        saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0) [1]
        y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
        y = (y - 16.0) / (235 - 16)
        # 忽略高亮色
        if y > 0.9:
            continue
        score = (saturation + 0.1) * count
        if score > max_score:
            max_score = score
            dominant_color = (r, g, b)
    return dominant_color
  • 将返回的数值进行判断
mainColor = get_dominant_color(Image.open('pic.jpg'))
            mainRed = mainColor[0]
            mainGreen = mainColor[1]
            mainBule = mainColor[2]
            mainColorRight = (200 < mainRed < 220) and (192 < mainGreen < 218) and (185 < mainBule < 205)
间隔图像文字识别优化

https://www.yuliu.tech/archives/125/

作者

羽流

发布时间

2020-01-21

许可协议

CC BY-SA 4.0

添加新评论