Raspberry Pi Barcode Scanner with Webcam and Python

Previously, I shared an article describing how to create an online barcode reader using Node.js, which turned Raspberry Pi into a web server. Today, I want to do another experiment – building a  Raspberry Pi barcode scanner with a USB webcam. For taking HD video and photo, you can choose Raspberry Pi camera module.

Raspberry Pi Webcam

How to Use Webcam with Raspberry Pi

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

ls /dev/video*

linux webcam detection

Install fswebcam:

sudo apt-get install fswebcam

Take a picture from webcam:

fswebcam test.jpg

Raspberry Pi webcam capture

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

Building Custom C/C++ Extension for Python

Download Dynamsoft Barcode Reader C/C++ SDK for Raspberry Pi.

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
        return list;
    return Py_None;

static PyMethodDef Methods[] =
     {"initLicense", initLicense, METH_VARARGS, NULL},
     {"decodeFile", decodeFile, METH_VARARGS, NULL},
     {NULL, NULL, 0, NULL}

     (void) Py_InitModule("dbr", Methods);

Create setup.py:

from distutils.core import setup, Extension

module_dbr = Extension('dbr', 
                        sources = ['dbr.c'], 

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

Python custom extension 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.

Opencv for Raspberry Pi

Raspberry Pi Barcode Scanner in Python

Create cam_reader.py:

	vc = cv2.VideoCapture(0)
	cache = ""
	results = None

	if vc.isOpened(): # try to get the first frame
		rval, frame = vc.read()
	    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:


Run the script:

python cam_reader.py

Capture and read barcode by pressing key ‘C’.

Raspberry Pi Barcode Scanner Result

Source Code


  • http://www.dynamsoft.com/ Xiao Ling

    Sure. The SDK supports linear barcode, QR code, DataMatrix and PDF417.

  • Manoj

    Can this be used for linear barcodes?

  • http://www.dynamsoft.com/ Xiao Ling

    Sorry, I don’t have a pi camera. You can have a try with current code.

  • Milan Siddhapara

    Is there any changes in code or configuration if i used pi camera instead of USB camera in raspberry?