Как декодировать Datamatrix с веб-камеры? - PullRequest
1 голос
/ 03 июня 2019

Я прочитал матрицу данных из изображений и сейчас пытаюсь прочитать это с веб-камеры, но она не работает, и я продолжаю получать ошибки.Я пробовал обнаружение штрих-кода / qrcode с сайта pyimagesearch.

Я использовал библиотеку Zbar, которая хорошо работает, но не поддерживает матрицу данных.Сейчас я пытаюсь использовать pylibdmtx, который хорошо работает с изображениями, но отстает и не обнаруживает видео.

код 1

from imutils.video import VideoStream
from pyzbar import pyzbar
from pydmtx import DataMatrix
import zxing
import argparse
import datetime
import imutils
import time
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
reader = zxing.BarCodeReader("/home/creator/.local/bin/zxing")
ap.add_argument("-o", "--output", type=str, default="barcodes.csv",
    help="path to output CSV file containing barcodes")
args = vars(ap.parse_args())

# initialize the video stream and allow the camera sensor to warm up
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
# 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 = open(args["output"], "w")
found = set()


# 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=40)

    # find the barcodes in the frame and decode each of the barcodes
    barcodes = pylibdmtx.decode(frame)

        # 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
        print("Data :",barcodeData,'\n')
        print("Type :",barcodeType)

        # 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
        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
    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()

код 1 выполняется, но он слишком медленный и ничего не обнаруживает.

Результат: если на камере отображается считанная матрица данных.

1 Ответ

0 голосов
/ 04 июня 2019
  • изменить строку 3 на:

из pylibdmtx import pylibdmtx

  • поскольку у меня не было zxing, я прокомментировал эти строки (4 и 13) в коде.

  • Декодер Datamatrix не имеет типа, подобного декодеру штрих-кода. Поэтому измените строку 52, как показано ниже:

    barcodeType = "DMC" # barcode.type

  • Добавлен оператор печати для просмотра декодированного вывода, как показано ниже внутри цикла:

для штрих-кода в штрих-кодах:

    print(barcode)

ВЫВОД:

Тип: DMC Декодированный (data = b'800400547311010400109085566 ', rect = Rect (left = 241, top = 238, width = 65, height = -83)) Данные: 800400547311010400109085566

Тип: DMC Декодированный (data = b'800040547311010400102325376 ', rect = Rect (left = 259, top = 140, width = -119, height = 110)) Данные: 800040547311010400102325376


ПОЖАЛУЙСТА, КТО-ТО ПОМОЖЕТ С ВОПРОСОМ МЕДЛЕННОСТИ, ПОТОМУ ЧТО Я НЕ МОГУ НАЙТИ ЭТОГО ПРИЧИНА.


...