OpenCV 使用Tesseract进行文本检测

  下载Tesseract,并记一下安装路径。
在这里插入图片描述
  在Pycharm中安装pytesseract.。在这里插入图片描述
  对下图进行文本检测,我自己在网上找了点其他类似的图,但不知道为什么效果并不是很好…
在这里插入图片描述
  首先进行单个字符的检测并打印边界框。主要使用两个函数:pytesseract.image_to_stringpytesseract.image_to_boxes

import cv2 as cv
import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'D:\\Program Files\\Tesseract-OCR\\tesseract.exe'
img = cv.imread('test5.jpg')
# tesseract只接受RGB,而opencv是BGR模式,需要进行转换
img = cv.cvtColor(img,cv.COLOR_BGR2RGB)
print(pytesseract.image_to_string(img)) # pytesseract.image_to_string 输出识别结果
# print(pytesseract.image_to_boxes(img)) # pytesseract.image_to_boxes 输出被识别目标及其边界框,包括x,y,w,h

# 在图像中画出所识别到的边界框并在其旁边放置所识别的文本(单个字符)
hImg,wImg,channel = img.shape
boxes = pytesseract.image_to_boxes(img)
for b in boxes.splitlines(): # 按行分割
    b = b.split(' ') # 按空格分割
    print(b) # 该列表元素依次为文本,边界框的x,y坐标,宽度和高度,类型为字符串    
    #其中一个输出为   ['M', '277', '508', '371', '594', '0'] 
    x,y,w,h = int(b[1]),int(b[2]),int(b[3]),int(b[4])
    # tesseract的坐标系定义和opncv好像有所区别
    cv.rectangle(img,(x,hImg-y),(w,hImg-h),(0,0,255),2)
    cv.putText(img,b[0],(x,hImg-y+25),cv.FONT_HERSHEY_COMPLEX_SMALL,1,(50,50,255),2)

cv.imshow('Result',img)
cv.waitKey(0)

  最后的检测结果在第二行bot那里有点不对劲…
在这里插入图片描述
  进行单词的检测,使用的函数为pytesseract.image_to_data

#检测单词
hImg,wImg,channel = img.shape
boxes = pytesseract.image_to_data(img)
print(boxes) #boxes类似于一个表格
for x,b in enumerate(boxes.splitlines()): #enumerate同时列出数据下标和数据
    if x != 0: #第一行为标题,不作为数据
        b = b.split() #此时的分隔符包括空格、换行(\n)、制表符(\t)等
        print(b)
        if len(b) == 12: #能识别出单词的b长度为12
            x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])
            cv.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) #此处返回的格式和之前不一样了
            cv.putText(img,b[11],(x,y),cv.FONT_HERSHEY_COMPLEX_SMALL,1,(50,50,255),2)

  结果中把数字作为一个整体也输出了…
在这里插入图片描述

  在检测单词的过程中只检测数字部分,通过设置pytesseract.image_to_data中的config参数来实现,在之前检测单个字符的pytesseract.image_to_boxes中设置config参数也可以达到同样的效果。

hImg,wImg,channel = img.shape
cong = r'--oem 3 --psm 6 outputbase digits'#设置
boxes = pytesseract.image_to_data(img,config=cong)
print(boxes)
for x,b in enumerate(boxes.splitlines()):
    if x != 0:
        b = b.split()
        print(b)
        if len(b) == 12:
            x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])
            cv.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
            cv.putText(img,b[11],(x,y),cv.FONT_HERSHEY_COMPLEX_SMALL,1,(50,50,255),2)

在这里插入图片描述
在这里插入图片描述
  学习链接

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值