- 安装opencv
先下载opencv官网的wle文件,然后在该目录,powershell敲击如下代码后tab键,然后安装
pip install opencv-python
- 安装tesseract 使用
先下载windows版本的,然后安装,使用中文字库的话需要去专门找一下,自带的下不下来,安装完后pip再安装一遍
pip install pytesseract
本地摄像头
import cv2
import numpy as np
import pytesseract as pt
from PIL import Image
path = r"D:\software\tesseract\tesseract.exe"""
pt.tesseract_cmd = path
font = cv2.FONT_HERSHEY_SIMPLEX
cap =cv2.VideoCapture(0,cv2.CAP_DSHOW)
kernel = np.ones((5, 5), np.uint8)
kernel2 = np.ones((7, 7), np.uint8)
while True:
ret,frame = cap.read()
frame = frame[0:417, 350:470]
x,y=frame.shape[0:2]
frame = cv2.resize(frame,(int(y/2),int(x/2)))
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
frame = cv2.dilate(frame, kernel, 1)
frame = cv2.erode(frame, kernel, 1)
frame = cv2.erode(frame, kernel2, 1)
frame = cv2.dilate(frame, kernel, 1)
cv2.blur(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), (5, 5))
ret,thresh1=cv2.threshold(frame,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# frame = cv2.erode(frame, kernel, iterations=1)
text =pt.image_to_string(frame,config='--psm 10 --oem 1 -c tessedit_char_whitelist=0123456789')
cv2.putText(thresh1, text, (20, 20), font, 1.2, (0, 0, 0), 2)
cv2.imshow('frame',thresh1)
c = cv2.waitKey(1)
if c == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
网络ip摄像头(安卓手机使用IP摄像头这个软件,把自己变成电脑摄像头)
#coding=utf-8
import cv2 as cv
import threading
import time
import numpy as np
import pytesseract as pt
from PIL import Image
from queue import Queue
path = r"D:\software\tesseract\tesseract.exe"""
pt.tesseract_cmd = path
font = cv.FONT_HERSHEY_SIMPLEX
kernel = np.ones((5, 5), np.uint8)
kernel2 = np.ones((7, 7), np.uint8)
def show_cam():
while True:
image = cv.cvtColor(image_np,cv.COLOR_BGR2GRAY)
ret,image=cv.threshold(image,0,255,cv.THRESH_BINARY | cv.THRESH_OTSU)
text =pt.image_to_string(image,lang="chi_sim")
q.put(text)
if cv.waitKey(25) & 0xFF == ord('l'):
break
return
if __name__ == '__main__':
q = Queue(maxsize=1)
cv.namedWindow("camera",1)
#开启ip摄像头
video="http://admin:admin@192.168.3.3:8081/"
cap =cv.VideoCapture(video)
ret, image_np = cap.read()
thread=threading.Thread(target=show_cam)
thread.start()
i=0
while True:
# Start Camera, while true, camera will run
ret, image_np = cap.read()
# Set height and width of webcam
height = 600
width = 1000
if not q.empty():
text=q.get()
i=20
if i>0:
cv.putText(image_np, text, (100, 100), font, 5, (0, 0, 0), 3)
i=i-1
# Set camera resolution and create a break function by pressing 'q'
cv.imshow('object detection', cv.resize(image_np, (width, height)))
if cv.waitKey(25) & 0xFF == ord('q'):
cap.release()
cv.destroyAllWindows()
break
然后就可以识别啦!坑比较多,大家慢慢踩!