티스토리 뷰
<라즈베리파이 카메라를 활용하여 QR,바코드를 인식해보자 ! >
>>> 참고 사이트 (두개의 과정은 같지만 아래거는 영어고 더 자세하다.)
https://blog.naver.com/PostView.nhn?blogId=zzang9ha&logNo=221660190400
라즈베리파이 - QR코드 인식
바코드, QR 코드를 라즈베리파이의 파이썬에서 읽기 < OpenCV가 설치되 있어야 합니다.> https:...
blog.naver.com
https://pyimagesearch.com/2018/05/21/an-opencv-barcode-and-qr-code-scanner-with-zbar/
An OpenCV barcode and QR code scanner with ZBar - PyImageSearch
In this tutorial you will learn how to create an OpenCV barcode and QR code scanner/reader using Python, OpenCV, and the ZBar library.
pyimagesearch.com
1. 바코드 디코딩을 위한 ZBar (Python 바인딩 포함) 설치 : 파이썬 환경
ZBar 라이브러리는 OpenCV와 함께 바코드 및 QR 코드를 스캔하고 디코딩하는 데 사용됩니다.
(설치 전에 OpenCV와 Playsound 설치되어있어야한다.)
(가상 환경 만들어서 실행하는 게 좋다.)
> pip install opencv-python ( 웹캠 작동 )
> pip install playsound ( 소리 .mp3 재생 )
$ sudo apt-get install libzbar0
// (pyzbar는 sudo 명령어로 설치가 안되는 경우도 있음)
//pip3 인지 pip 인지 확인 ! 버전에따라 다르다 !!
$ sudo pip3 install pyzbar
2. 실시간 바코드 디코딩 코드 작성
2-1. 바코드 이미지를 스캔해보자
Before we implement real-time barcode and QR code reading, let’s first start with a single image scanner to get our feet wet.
** 같은 경로에 바코드 이미지.png 있어야한다. (코드는 참고 사이트에서 가져왔다.)
# import the necessary packages
# 필요한 패키지 임포트
from pyzbar import pyzbar
import argparse
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help = "path to inpuit image")
args = vars(ap.parse_args())
# load the input image
image = cv2.imread(args["image"])
# find the barcodes in the image and decode each of the barcodes
# 이미지에서 바코드 찾기
barcodes = pyzbar.decode(image)
# loop over the detected barcodes
for barcode in barcodes:
# extract the bounding box location of the barcode and draw the
# bounding box surrounding the barcode on the image
# 이미지에서 바코드의 경계 상자부분을 그리고, 바코드의 경계 상자부분(?)을 추출한다.
(x, y, w, h) = barcode.rect
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
# the barcode data is a bytes object so if we want to draw it on
# our output image we need to convert it to a string first
# 바코드 데이터는 바이트 객체이므로, 어떤 출력 이미지에 그리려면 가장 먼저 문자열로 변환해야 한다.
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
# draw the barcode data and barcode type on the image
# 이미지에서 바코드 데이터와 테입(유형)을 그린다
text = "{} ({})".format(barcodeData, barcodeType)
cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 0, 255), 2)
# print the barcode type and data to the terminal
# 터미널을 통해 바코드 유형과 데이터를 출력
print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))
# show the output image
# 이미지 출력을 보여준다.
cv2.imshow("Image", image)
cv2.waitKey(0)
실행 코드
//python3 barcode_scanner_image.py --image 파일이름.png
$ python3 barcode_scanner.image.py --image barcode.png
2-2 실시간으로 인식, 탐지하기
2-2-1. 설치 먼저
pip install imutils
: videoStream을 위해서 설치한다.
** 같은 경로에 바코드 이미지.png 와 소리.mp3 파일 같이있어야한다.
# import the necessary packages
from imutils.video import VideoStream
from pyzbar import pyzbar
import argparse
import datetime
import imutils
import time
import cv2
# construct the argument parser and parse the arguments
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, let’s initialize our video stream and open our CSV file:
# initialize the video stream and allow the camera sensor to warm up
# 비티오 스트림 초기화 및 카메라 센서가 예열되도록 함
print("[INFO] starting video stream...")
# vs = VideoStream(src=0).start()
vs = VideoStream(src=0).start() # USB 웹캠 카메라 사용시
#vs = VideoStream(usePiCamera=True).start() # 파이 카메라 사용시
time.sleep(2.0)
# open the output CSV file for writing and initialize the set of
# barcodes found thus far
# 작성을 위해 출력된 CSV 파일을 열고, 지금까지 찾은 바코드 세트 초기화
csv = open(args["output"], "w")
found = set()
### Let’s begin capturing + processing frames:
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it to
# have a maximum width of 400 pixels
frame = vs.read()
frame = imutils.resize(frame, width=400)
# find the barcodes in the frame and decode each of the barcodes
# 프레임에서 바코드를 찾고, 각 바코드들 마다 디코드
barcodes = pyzbar.decode(frame)
### Let’s proceed to loop over the detected barcodes
# loop over the detected barcodes
for barcode in barcodes:
# extract the bounding box location of the barcode and draw
# the bounding box surrounding the barcode on the image
# 이미지에서 바코드의 경계 상자부분을 그리고, 바코드의 경계 상자부분(?)을 추출한다.
(x, y, w, h) = barcode.rect
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
# the barcode data is a bytes object so if we want to draw it
# on our output image we need to convert it to a string first
# 바코드 데이터는 바이트 객체이므로, 어떤 출력 이미지에 그리려면 가장 먼저 문자열로 변환해야 한다.
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
# draw the barcode data and barcode type on the image
# 이미지에서 바코드 데이터와 테입(유형)을 그린다
text = "{} ({})".format(barcodeData, barcodeType)
cv2.putText(frame, text, (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# if the barcode text is currently not in our CSV file, write
# the timestamp + barcode to disk and update the set
# 현재 바코드 텍스트가 CSV 파일안에 없을경우, timestamp, barcode를 작성하고 업데이트
if barcodeData not in found:
csv.write("{},{}\n".format(datetime.datetime.now(),
barcodeData))
csv.flush()
found.add(barcodeData)
# show the output frame
cv2.imshow("Barcode Scanner", frame)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
# q를 누르면 loop를 break함
if key == ord("q"):
break
# close the output CSV file do a bit of cleanup
print("[INFO] cleaning up...")
csv.close()
cv2.destroyAllWindows()
vs.stop()
오류
AttributeError: 'PiVideoStream' object has no attribute 'shape'
해결
>>>라즈베리와 카메라 연결 문제
1.라즈베리파이 설정(카메라)
sudo raspi-config
1-1. 인터페이스 탭 -> 카메라 활성화
interface -> camera 활성화
1-2. 재부팅
혹은 라즈베리 카메라를 바르게 꽂는다. 파란줄이 바깥으로가게.
[ 다음 문제 ]
1. 실시간으로 QR은 인식하지만 바코드 정보 저장 안 된다.
2. 바코드 정보를 저장해야한다.
2-3. 인식된 정보 기록
>>참고사이트
https://m.blog.naver.com/PostView.naver?blogId=oralol&logNo=222222465522&proxyReferer=
파이썬코딩 - QR코드, 바코드 스캐너 리더기 만들기(opencv, pyzbar)
파이썬으로 QR코드, 바코드 스캐너를 쉽게 만들 수 있습니다. opencv 으로 웹캠을 작동시키고, pyzbar 으...
blog.naver.com
argparse는 python에 기본으로 내장되어 있다. 파일 실행할 때 옵션을 추가할 수 있다.
>>참고 https://greeksharifa.github.io/references/2019/02/12/argparse-usage/
Python, Machine & Deep Learning
Python, Machine Learning & Deep Learning
greeksharifa.github.io
: barcodes.csv 파일에 바코드 정보 기록된다.
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
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()
#bool _
isComplete = False
#carturing + processing frame
#loop over the frames from video strea
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)
#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 = our 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
#close
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()
>>>결과
시간 + 바코드 정보로 저장된다.
2022-03-10 16:29:40.750418 , 9791158392550
'Iot > 라즈베리파이' 카테고리의 다른 글
라즈베리파이_네이버 책 검색 api (0) | 2022.03.10 |
---|---|
라즈베리파이_ 실시간 바코드 인식 pyzbar + playsound (0) | 2022.03.10 |
라즈베리파이 _OpenCV 설치하기 (0) | 2022.03.08 |
라즈베리파이_google Speech to Text (0) | 2022.03.07 |
라즈베리파이_Google Assistant (AI) 버튼 제어 (0) | 2022.03.06 |
- Total
- Today
- Yesterday
- 후디니
- DeepLeaning
- Python
- 라즈베리파이
- ai film
- AI
- Express
- RNN
- CNC
- Midjourney
- colab
- krea
- imgtoimg
- Java
- oculuspro
- Arduino
- opencv
- sequelize
- Unity
- VR
- google ai studio
- runwayai
- MQTT
- TouchDesigner
- three.js
- node.js
- houdini
- docker
- 유니티
- ai image generator
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |