티스토리 뷰

728x90
반응형

https://m.blog.naver.com/PostView.naver?blogId=oralol&logNo=222222465522&proxyReferer= 

 

파이썬코딩 - QR코드, 바코드 스캐너 리더기 만들기(opencv, pyzbar)

파이썬으로 QR코드, 바코드 스캐너를 쉽게 만들 수 있습니다. opencv 으로 웹캠을 작동시키고, pyzbar 으...

blog.naver.com

https://blog.naver.com/PostView.nhn?blogId=zzang9ha&logNo=221660190400 

 

라즈베리파이 - QR코드 인식

바코드, QR 코드를 라즈베리파이의 파이썬에서 읽기 < OpenCV가 설치되 있어야 합니다.> https:...

blog.naver.com

 

from imutils.video import VideoStream
from pyzbar import pyzbar
import argparse
import datetime
import imutils
import time
import cv2
from playsound import playsound
import numpy as np


#바코드 이미지 인식 개선을 위한 함수(별소용이없다..)
def autocrop(image, threshold=0):
    """Crops any edges below or equal to threshold
    Crops blank image to 1x1.
    Returns cropped image.
    """
    if len(image.shape) == 3:
        flatImage = np.max(image, 2)
    else:
        flatImage = image
    assert len(flatImage.shape) == 2

    rows = np.where(np.max(flatImage, 0) > threshold)[0]
    if rows.size:
        cols = np.where(np.max(flatImage, 1) > threshold)[0]
        image = image[cols[0]: cols[-1] + 1, rows[0]: rows[-1] + 1]
    else:
        image = image[:1, :1]

    return image


#argument parser(csv 텍스트파일에 바코드정보를 입력 저장한다)
ap = argparse.ArgumentParser()
ap.add_argument("-o","--output",type=str,default="barcodes.csv",help="path to output CSV file containing barcodes")
args = vars(ap.parse_args())


#from there, initialize our video stream and open our CSV file
print("[INFO] starting video stream...")

#camera setting
resolution = (1296, 976)
vs = VideoStream(usePiCamera=True,resolution=resolution,
                    framerate=24).start()


time.sleep(2.0)

#open output CSV file for writing and initialize the set of barcodes 
csv = open(args["output"],"w")
found = set() #found에 인식된 바코드가 리스트로 저장된다.

#bool _ 인식 완료 감지
isComplete = False

#carturing + processing frame
#loop over the frames from video stream
while True:
    #frame = 비디오 스트림
    frame = vs.read()
    frame = imutils.resize(frame, width = 1200)

    #crop def 이미지 인식 개선 함수..
    crop = autocrop(frame,50)

    #barcode in frame and decode
    # barcodes = pyzbar.decode(frame)
    barcodes = pyzbar.decode(crop) #barcodes에 바코드 정보를 담는다


    #loop over the detected barcodes 
    for barcode in barcodes:
        #draw red box
        (x,y,w,h) = barcode.rect
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)

        #bype to text
        barcodeData = barcode.data.decode("utf-8")
        barcodeType = barcode.type

        #data , type on image
        text = "{} ({})".format(barcodeData,barcodeType)
        cv2.putText(frame,text,(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),2)

        #found 리스트에 바코드 정보가 중복되지 않는다면 CSV file에 입력,저장한다.
        if barcodeData not in found:
            csv.write("{},{}\n".format(datetime.datetime.now(),barcodeData))
            csv.flush()
            found.add(barcodeData)
            print("인식 성공 :",barcodeData)
            playsound("barcode_beep.mp3")
        else :
            # csv.write("{},{}\n".format(datetime.datetime.now(),barcodeData))
            # csv.flush()
            #print type , data to the terminal
            print("이미 인식된 코드 [INFO] Found {} barcode: {}".format(barcodeData,barcodeType))
            playsound("barcode_beep.mp3")
            isComplete= True
        break

    #종료
    if isComplete:
    	##완료시 수행할 코드 적어주면 된다.
        print("recognition complete")
        break
            
            

    #show output image
    cv2.imshow("Barcode Scanner",frame)
    key = cv2.waitKey(1) & 0xFF

    #q press loop break
    if key == ord("q"):
        break

#close the output CSV file do a bit of clean up
print("[INFO] cleaning up...")
csv.close()
cv2.destroyAllWindows()
vs.stop()

 

큐알과 큰 사이즈의 2d 바코드는 잘 인식되지만

작은 사이즈의 바코드는 해상도 문제로 잘 인식되지 않는다..

해결방안 아직 못찾음 ..

qqq

728x90
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함
반응형