python2 使用zbar进行识别
import cv2
from PIL import Image
import zbar
def decode():
scanner = zbar.ImageScanner()
scanner.parse_config('enable')
img = Image.open('1.jpg').convert('L')
width,height = img.size
raw = img.tobytes()
zbarimage = zbar.Image(width,height,'Y800',raw)
scanner.scan(zbarimage)
data = ''
for symbol in zbarimage:
data +=symbol.data
print(data)
decode()
import cv2
from PIL import Image
import zbar
def detect():
camera = cv2.VideoCapture(0)
while True:
flag,frame = camera.read()
data = decode(frame)
if decode(frame) !='':
with open('data.txt','a') as f:
f.write(data)
break
cv2.waitKey(1)
cv2.imshow('camera',frame)
camera.release()
cv2.destroyAllWindows()
def decode(frame):
scanner = zbar.ImageScanner()
scanner.parse_config('enable')
img = Image.fromarray(frame).convert('L')
width,height = img.size
raw = img.tobytes()
zbarimage = zbar.Image(width,height,'Y800',raw)
scanner.scan(zbarimage)
data = ''
for symbol in zbarimage:
data +=symbol.data
print(data)
return data
#detect()
python3 使用pyzbar进行识别
#coding: utf-8
import cv2
import pyzbar.pyzbar as pyzbar
from PIL import Image
import pymysql
#存入数据库
def database(data):
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='test',charset='utf8')
cursor = db.cursor() #建立游标对象
sql_create = 'create table tb2(id varchar(250))'
cursor.execute(sql_create)
sql_insert = '''insert into tb2(id) values(%s)'''
cursor.execute(sql_insert,data)
db.commit()
sql_select = 'select * from tb2'
cursor.execute(sql_selet)
result = cursor.fetchall()
for row in result:
id = row[0]
print(id)
cursor.close()
db.close()
#摄像头识别
def decode(frame):
#picture 从摄像头获取二维码的注释掉下面一行代码
frame = Image.open('1.jpg')
#camera
barcodes = pyzbar.decode(frame)
data = ''
for barcode in barcodes:
data+=barcode.data.decode("utf-8")
print(data)
return data
def detect():
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
data = decode(frame)
if data!='':
database(str(data)) #写入数据库
with open('data.txt','w') as f:#写入txt文档
f.write(data)
break
#写入csv
with open('datacsv.csv','w') as f:
writer = csv.writer(f)
writer.writerow(['坐标',decode(frame)])
break
cv2.waitKey(1)
cv2.imshow("camera", frame)
camera.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
detect()