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

2024-05-10 17:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我修改了我在网上找到的一些代码,这些代码使用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()

Webcam

NotePad


Tags: inimportinforeadifmaincodecv2
1条回答
网友
1楼 · 发布于 2024-05-10 17:52:29

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

您可能需要对append使用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)
    ...

相关问题 更多 >