Skip to content

Instantly share code, notes, and snippets.

@khchanel
Created August 26, 2020 11:06
Show Gist options
  • Save khchanel/38f13d489a716739fe21475da4ff97a9 to your computer and use it in GitHub Desktop.
Save khchanel/38f13d489a716739fe21475da4ff97a9 to your computer and use it in GitHub Desktop.
import pyzbar.pyzbar as pyzbar
import cv2
def detectBarcodes(img):
codes = pyzbar.decode(img)
for code in codes:
print(f'type={code.type}')
print(f'data={code.data}')
return codes
if __name__ == "__main__":
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)
while cap.isOpened():
# capture frame
ret, frame = cap.read()
# convert frame to grayscale image for detection
image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# detect barcodes
detections = detectBarcodes(image)
for barcode in detections:
points = barcode.polygon
print(f'points={points}')
# draw lines connecting points
n = len(points)
for i in range(0, n):
# cv2.rectangle(frame, points[0], points[2], (255, 0, 0), 2)
cv2.line(frame, points[i], points[(i + 1) % n], (255, 0, 0), 2)
# draw data text
x = barcode.rect.left
y = barcode.rect.top
print(f'coord x={x} y={y}')
cv2.putText(frame, str(barcode.data), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA)
# render
x = cv2.imshow('frame', frame)
# exit on q
key = cv2.waitKey(1)
if cv2.getWindowProperty('frame', 0) == -1 or key & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
cap.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment