我修改了我在网上找到的一些代码,这些代码使用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”模式打开文件,每次这样做时,文件都会在写入之前被擦除
您可能需要对append使用mode='a'
对于第二个问题,只需稍微移动循环,使其在else语句中执行。在代码中,它将忽略if语句写入文件
哦,对不起,我以前没见过你
您必须将代码=[]移出循环,就像在程序初始化时一样
比如:
我没有测试,因为我不能使用你的库
相关问题 更多 >
编程相关推荐