Ashwin Guna
Ashwin Guna

Reputation: 11

How to break the duplicate values?

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
        
        barcode_info = barcode.data.decode('utf-8')
     
            cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
            print(barcode_info)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, barcode_info, (x + 6, y - 6), font, 2.0, (255, 255, 255), 1)

            with open("barcode_result.txt", mode ='w') as file:
                file.write("Recognized Barcode:" + barcode_info)
            #time.sleep(0.5)
    return frame
def main():
    
    camera = cv2.VideoCapture(0)
    ret, frame = camera.read()
    
    while ret:
        ret, frame = camera.read()
        frame = read_barcodes(frame)
        cv2.imshow('Barcode/QR code reader', frame)
        if cv2.waitKey(1) & 0xFF == 27:
            break
    
    camera.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

i want to break the for loop and stop printing duplicate values

Upvotes: 0

Views: 109

Answers (1)

Chandler Bong
Chandler Bong

Reputation: 461

You can remove the duplicates in 2 ways.

First one:

 def read_barcodes(frame):
    processed = []   # <=== added this line
    barcodes = pyzbar.decode(frame)
    for barcode in barcodes:
      if barcode not in processed:  # <== added this condition
        x, y , w, h = barcode.rect
    
        barcode_info = barcode.data.decode('utf-8')
 
        cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
        print(barcode_info)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, barcode_info, (x + 6, y - 6), font, 2.0, (255, 255, 255), 1)

        with open("barcode_result.txt", mode ='w') as file:
            file.write("Recognized Barcode:" + barcode_info)
        #time.sleep(0.5)
        processed.append(barcode)   # <=== added this line
return frame

Second one: You can just do this

for barcode in set(barcodes):

A set removes all the duplicates automatically.

Upvotes: 2

Related Questions