import os
import numpy as np
import cv2
from time import time
camera=cv2.VideoCapture(0)
camera.set(3,128) #设置分辨率
camera.set(4,128)
camera.set(5,120)
def equalize_transfrom(gray_img):
return cv2.equalizeHist(gray_img)
start = time()
#gray = cv2.blur(gray,(5,5))
#gray = equalize_transfrom(gray)
#ret,det = cv2.threshold(gray,40,255,cv2.THRESH_BINARY)
#det = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,3,3)
#det= gray #cv2.medianBlur(det,3)
memfile = './data.png'
kernel = np.ones((3,3),np.uint8)
#erosion = cv2.erode(src,kernel)
while True:
(grabbed,scr)=camera.read()
gray = cv2.cvtColor(scr,cv2.COLOR_RGB2GRAY)
ret,det = cv2.threshold( equalize_transfrom(gray) ,40,255,cv2.THRESH_BINARY) #直方图均衡之后二值化
cv2.blur(det,(5,5)) #模糊
cv2.medianBlur(det,5)
#det = cv2.dilate(det,kernel)
contours,hierarchy = cv2.findContours(det,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) #扫描轮廓
#print("number of contours:%d" % len(contours))
mask = np.zeros([128, 128], np.uint8)
for i in range(len(contours)):
sz = len( contours[i] ) #轮廓像素个数
ln = cv2.arcLength(contours[i],True) #获取轮廓周长面积
ar = cv2.contourArea(contours[i])
if sz>10 and sz<100 and ln<ar:
x,y,w,h = cv2.boundingRect(contours[i]) #获取轮廓框
if y<100:
#print( [len(contours[i]),ln,ar,x,y] )
for row in range(y,y+h-1): #遍历高
for col in range(x,x+w-1): #遍历宽
if( det[row,col] == 0 ):
mask[row,col] = 255
mask = 255-mask
#mask = cv2.erode(mask,kernel)
cv2.imshow("scr",mask)
cv2.waitKey(1)
cv2.imwrite(memfile,mask)
with os.popen('gocr -a 90 -C 0123456789A=+ -i '+memfile, "r") as p:
line = p.readline()
if( line.find('_')<0 ):print (line)
while line:line = p.readline()
#print (line)
if cv2.waitKey(1) & 0xFF == 27:
break
cv2.destroyAllWindows()
print(time() - start)
print('end')