网络摄像头条形码阅读器:将多个条形码数据导出到记事本



我修改了一些在线代码,这些代码使用opencv/pyzbar从网络摄像头读取条形码。

它可以读取多个条形码,但当我厌倦了把它写在记事本上时,只会显示1个数据。

我尝试将读取的数据保存到数组/列表中并导出,但不起作用。

我怎样才能把所有不同的条形码都写在记事本上呢。

#import libraries
import cv2
import time
from pyzbar import pyzbar
def read_barcodes(frame):
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
x, y , w, h = barcode.rect
#1 Decode barcode/Create frame
barcode_info = barcode.data.decode('utf-8')
cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
#2 Create text on top of the barcode
cv2.putText(frame, barcode_info, (x + 6, y - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 255), 2)
#3 Export to text 
code = []
if barcode_info in code:
print("Duplicate")
else:
code.append(barcode_info)
print (code)
#set ={}
#set.update(barcode_info)
with open("barcode_result.txt", mode ='w') as file:
for x in code:
file.write("Recognized Barcode:" + x +"n")
return frame
def main():
#1 Open webcam using OpenCV
camera = cv2.VideoCapture(0)    #0(webcam) 1(camera)
ret, frame = camera.read()
#2 Loop till Esc is pressed
while ret:
ret, frame = camera.read()
frame = read_barcodes(frame)
cv2.imshow('Barcode/QR code reader', frame)
if cv2.waitKey(1) & 0xFF == 27:
break
#3 Close webcam
camera.release()
cv2.destroyAllWindows()
#4 
if __name__ == '__main__':
main()

网络摄像头

记事本

我没有阅读所有的代码,但似乎您使用'w'模式打开文件,每次这样做时,文件都会在写入之前被擦除。

您可能需要使用mode='a'进行追加。

对于第二个问题,只需稍微移动循环,使其在else语句中执行即可。在您的代码中,它会忽略if语句写入文件。

if barcode_info in code:
print("Duplicate")
else:
code.append(barcode_info)
print (code)
#set ={}
#set.update(barcode_info)
with open("barcode_result.txt", mode ='a') as file:
for x in code:
file.write("Recognized Barcode:" + x +"n")

哦,很抱歉之前没有看到

#3 Export to text 
code = []
if barcode_info in code: #this will never happen
print("Duplicate")

您必须将代码=[]移动到循环之外,就像在程序初始化时一样。

类似于:

#2 Loop till Esc is pressed
code = []
while ret:
ret, frame = camera.read()
frame = read_barcodes(frame)
cv2.imshow('Barcode/QR code reader', frame)
if cv2.waitKey(1) & 0xFF == 27:
break
#loop terminated, now write
with open("barcode_result.txt", mode ='a') as file:
for x in code:
file.write("Recognized Barcode:" + x +"n")
#3 Close webcam

我没有测试,因为我不能使用你的图书馆

def read_barcodes(frame):
...
#3 Export to text 
if barcode_info in code:
print("Duplicate")
else:
code.append(barcode_info)
print (code)
...

最新更新