Web Demos

BARCODE READER SDK DEMO

Explore the flexibe barcode reading settings to optimize for your specific usage scenario.

WEB TWAIN SDK DEMO

Try the most popular web scanner features: scan images, import local images and PDF files, edit, save to local, upload to database, and etc.

BARCODE READER JAVASCRIPT DEMO

Transform any camera-equipped devices into real-time, browser-based barcode and QR code scanners.

MRZ SCANNER WEB DEMO

Detects the machine-readable zone of a passport, scans the text, and parses into human-readable data.

APP STORE DEMOS

BARCODE READER SDK FOR IOS

BARCODE READER SDK FOR ANDROID

VIEW MORE DEMOS >

Raspberry Pi Barcode Scanner with Webcam and Python

Jun 14, 2017

In this post, we will talk about building a Raspberry Pi barcode scanner with a USB webcam and Python by using Dynamsoft’s C/C++ barcode reader SDK.

Watch the video and see how the Raspberry Pi Barcode Scanner works:

How to Use Webcam with Raspberry Pi

To check whether the Linux system can identify the USB webcam, use the following commands:

lsusb
ls /dev/video*

Install fswebcam:

sudo apt-get install fswebcam

Take a picture from webcam:

fswebcam test.jpg

If the webcam can work well, you can take the next step.

Building Custom C/C++ Extension for Python

Get Dynamsoft Barcode Reader C/C++ SDK for Raspberry Pi Beta
Download free trial >

Extract the package and generate the symbolic link:

sudo ln -s <Your library path>/libDynamsoftBarcodeReader.so /usr/lib/libDynamsoftBarcodeReader.so

Create dbr.c in which you need to glue Dynamsoft Barcode Reader APIs to Python native code:

static PyObject *
initLicense(PyObject *self, PyObject *args)
{
    char *license;
    if (!PyArg_ParseTuple(args, "s", &license)) {
    return NULL;
    }
    printf("License: %s\n", license);
    int ret = DBR_InitLicense(license);
    return Py_BuildValue("i", ret);
}
 
static PyObject *
decodeFile(PyObject *self, PyObject *args)
{
    char *pFileName;
    if (!PyArg_ParseTuple(args, "s", &pFileName)) {
        return NULL;
    }
     
    // Dynamsoft Barcode Reader: init
    __int64 llFormat = (OneD | QR_CODE | PDF417 | DATAMATRIX);
    int iMaxCount = 0x7FFFFFFF;
    ReaderOptions ro = {0};
    pBarcodeResultArray pResults = NULL;
     
    ro.llBarcodeFormat = llFormat;
    ro.iMaxBarcodesNumPerPage = iMaxCount;
 
    // Decode barcode image
    int ret = DBR_DecodeFile(pFileName, &ro, &pResults);
    printf("DecodeFile ret: %d\n", ret);
     
    {
        int count = pResults->iBarcodeCount;
        pBarcodeResult* ppBarcodes = pResults->ppBarcodes;
        pBarcodeResult tmp = NULL;
 
        PyObject* list = PyList_New(count);
        PyObject* result = NULL;
        int i = 0;
        for (; i < count; i++)
        {
            tmp = ppBarcodes[i];
            result = PyString_FromString(tmp->pBarcodeData);
            PyList_SetItem(list, i, Py_BuildValue("iN", (int)tmp->llFormat, result));
        }
        // release memory
        DBR_FreeBarcodeResults(&pResults);
        return list;
    }
     
    return Py_None;
}
 
static PyMethodDef Methods[] =
{
     {"initLicense", initLicense, METH_VARARGS, NULL},
     {"decodeFile", decodeFile, METH_VARARGS, NULL},
     {NULL, NULL, 0, NULL}
};
 
PyMODINIT_FUNC
initdbr(void)
{
     (void) Py_InitModule("dbr", Methods);

Create setup.py:

from distutils.core import setup, Extension
 
module_dbr = Extension('dbr', 
                        sources = ['dbr.c'], 
                        include_dirs=['/home/pi/Desktop/dbr/include'],
                        library_dirs=['/home/pi/Desktop/dbr/lib'],
                        libraries=['DynamsoftBarcodeReader'])
 
setup (name = 'DynamsoftBarcodeReader',
        version = '1.0',
        description = 'Python barcode extension',
        ext_modules = [module_dbr])

Build and install the Python module:

python setup.py build
sudo python setup.py install

Note: if you see the error message “fatal error: Python.h: No such file or directory“, please install python-dev:

sudo apt-get install python-dev

Installing OpenCV on Raspbian Jessie

To capture images from a webcam, we can use OpenCV. Read the excellent article that demonstrates how to install OpenCV on Raspbian Jessie.

Raspberry Pi Barcode Scanner in Python

Create cam_reader.py:

cv2.namedWindow("preview")
    vc = cv2.VideoCapture(0)
    cache = ""
    results = None
 
    if vc.isOpened(): # try to get the first frame
        initLicense("64E4EE3532B813C8EA8EA5F34E7B4528")
        rval, frame = vc.read()
    else:
        rval = False
 
    while rval:
        cv2.imshow("preview", frame)
        rval, frame = vc.read()
 
        key = cv2.waitKey(20)
        if key == ord('c'):
            cache = getImageName()
            cv2.imwrite(cache, frame)
            results = decodeFile(cache)
            print "Total count: " + str(len(results))
            for result in results:
                print "barcode format: " + formats[result[0]]
                print "barcode value: " + result[1] + "\n*************************"
        elif key == 27:
            break
 
    cv2.destroyWindow("preview")

Run the script:

python cam_reader.py

Capture and read barcode by pressing key ‘C’.

Raspberry Pi Barcode Scanner with Webcam and Python

Source Code

https://github.com/dynamsoftlabs/webcam-barcode-scanner-for-pi

Subscribe Newsletter

Subscribe to our mailing list to get the monthly update.

Subscribename@email.com