Click here to Skip to main content
14,367,300 members

Inside Dynamsoft Barcode SDK: Unveiling the Algorithm Intermediate Results

20 Sep 2019CPOL
In this article, we show you how to get intermediate results of Dynamsoft Barcode Reader SDK using Python and C code.

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

Dynamsoft Barcode Reader, as an enterprise-class barcode decoding SDK, opens a brand-new set of APIs allowing developers to peek the intermediate results of the algorithm in the latest version 7.x series. For professional developers, intermediate results are not only useful for learning how the SDK works and debugging programs in terms of some adverse cases (low-light environments, moving objects, etc.) but also available for further usage like image processing.

In this article, we show you how to get intermediate results of Dynamsoft Barcode Reader SDK using Python and C code.

About Dynamsoft Barcode Reader

Dynamsoft's Barcode Reader SDK enables you to embed barcode reading functionality efficiently in your web, desktop, or mobile application using just a few lines of code, which saves your development time and cost. With the SDK, you can create high-speed and reliable barcode scanner software to meet your business needs.

License

Get a FREE 30-day trial license.

Supported Barcode Symbologies

Linear Barcodes (1D): Code 39, Code 93, Code 128, Codabar, Interleaved 2 of 5, EAN-8, EAN-13, UPC-A, UPC-E, Industrial 2 of 5.

2D Barcodes: QR Code, DataMatrix, PDF417 and Aztec Code.

Developer’s Guide

https://www.dynamsoft.com/help/Barcode-Reader/devguide/index.html

API Documentation

https://www.dynamsoft.com/help/Barcode-Reader/index.html

Code Gallery

https://www.dynamsoft.com/Downloads/Dynamic-Barcode-Reader-Sample-Download.aspx

Online Demo

https://demo.dynamsoft.com/DBR/BarcodeReaderDemo.aspx

Anatomizing the Intermediate Results of Dynamsoft Barcode Algorithm

Intermediate Result Types

The supported intermediate result types include:

IRT_NO_RESULT  No intermediate result.
IRT_ORIGINAL_IMAGE  Original image.
IRT_COLOUR_CLUSTERED_IMAGE  Color clustered image. Available in v8.x.
IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE  Colour converted grayscale image.
IRT_TRANSFORMED_GRAYSCALE_IMAGE  Transformed grayscale image.
IRT_PREDETECTED_REGION  Predetected region.
IRT_PREPROCESSED_IMAGE  Preprocessed image.
IRT_BINARIZED_IMAGE  Binarized image.
IRT_TEXT_ZONE  Text zone.
IRT_CONTOUR  Contour.
IRT_LINE_SEGMENT  Line segment
IRT_FORM  Form. Available in v8.x.
IRT_SEGMENTATION_BLOCK  Segmentation block. Available in v8.x.
IRT_TYPED_BARCODE_ZONE  Typed barcode zone.

JSON template usage

To export expected intermediate results, configure the parameter JSON template as follows:

"IntermediateResultSavingMode" : {
         "FolderPath" : "d:\\",
         "Mode" : "IRSM_BOTH"
      },
"IntermediateResultTypes" : [
         "IRT_ORIGINAL_IMAGE",
         "IRT_COLOUR_CLUSTERED_IMAGE",
         "IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",
         "IRT_BINARIZED_IMAGE"
      ],

Note: The "IntermediateResultSavingMode" key is required for setting the output directory.

How to set intermediate result types in C code

There is a DBR_InitRuntimeSettingsWithString() function used for loading the JSON template of the global configurations.

DBR_InitRuntimeSettingsWithString()

DBR_API int DBR_InitRuntimeSettingsWithString ( void *  barcodeReader,
    const char *  content,
    const ConflictMode conflictMode,
    char  errorMsgBuffer[],
    const int  errorMsgBufferLen 
  )    

Initializes runtime settings with the parameters obtained from a JSON string.

Parameters

[in] barcodeReader Handle of the barcode reader instance.
[in] content A JSON string that represents the content of the settings.
[in] conflictMode The parameter setting mode, which decides whether to inherit parameters from a previous template setting or to overwrite previous settings with the new template.
[in,out] errorMsgBuffer The buffer is allocated by the caller and the recommending length is 256. The error message will be copied to the buffer.
[in] errorMsgBufferLen The length of the allocated buffer.

Returns

Returns error code. Returns 0 if the function operates successfully. You can call DBR_GetErrorString() to get detailed error message.

Code Snippet:

void* barcodeReader = DBR_CreateInstance();
DBR_InitLicense(barcodeReader, "t0260NwAAAHV***************");
char errorMessage[256];
DBR_InitRuntimeSettingsWithString(barcodeReader, "{\"Version\":\"3.0\", \"ImageParameter\":{\"Name\":\"IP1\", \"IntermediateResultSavingMode\": {
\"Mode\": \"IRSM_BOTH\",\"FolderPath\": \"d:\\IR\"},\"TerminatePhase\": \"TP_BARCODE_RECOGNIZED\", \"IntermediateResultTypes\": [\"IRT_BINARIZED_IMAGE\"],},}}", CM_OVERWRITE, errorMessage, 256);
DBR_DestroyInstance(barcodeReader);

How to use Python to read barcodes with intermediate results

Build a C extension

Install Dynamsoft Barcode Reader to get the header file and shared libraries.

Install the build dependencies:

pip install opencv-python numpy

Create a CPython method called setParameters() in dbr.c file:

static PyObject *
setParameters(PyObject *obj, PyObject *args)
{
    DynamsoftBarcodeReader *self = (DynamsoftBarcodeReader *)obj;

    char *json;
    if (!PyArg_ParseTuple(args, "s", &json))
    {
        return NULL;
    }

    char errorMessage[256];
    int ret = DBR_InitRuntimeSettingsWithString(self->hBarcode, json, CM_OVERWRITE, errorMessage, 256);

    return Py_BuildValue("i", ret);
}

The method takes a JSON string as the input. The "DynamsoftBarcodeReader" is a data structure representing the Python barcode module.

Here is the full code:

https://github.com/dynamsoft-dbr/python/blob/7.x/src/dbr.c

Create a setup.py file for building the Python extension:

from distutils.core import setup, Extension
import sys
import os
import numpy
from distutils.command.install import install

# NumPy header file path.
numpy_include = os.path.join(os.path.dirname(
    numpy.__file__), "core", "include", "numpy")
print(numpy_include)

# Customization for different platforms
dbr_lib_dir = ''
dbr_dll = ''
dbr_include = ''
dbr_lib_name = 'DynamsoftBarcodeReader'

if sys.platform == "linux" or sys.platform == "linux2":
    # linux
    dbr_lib_dir = '/usr/lib'
elif sys.platform == "darwin":
    # OS X
    dbr_lib_dir = '/usr/lib'
    pass
elif sys.platform == "win32":
    # Windows
    dbr_lib_name = 'DBRx64'
    dbr_lib_dir = r'c:\Program Files (x86)\Dynamsoft\Barcode Reader 7.1\Components\C_C++\Lib'
    dbr_dll = r'c:\Program Files (x86)\Dynamsoft\Barcode Reader 7.1\Components\C_C++\Redist\x64'

module_dbr = Extension('dbr', sources=['dbr.c'], include_dirs=[
                       numpy_include], library_dirs=[dbr_lib_dir], libraries=[dbr_lib_name])

class CustomInstall(install):
    def run(self):
        install.run(self)
        if sys.platform == "win32":
            import shutil
            from distutils.sysconfig import get_python_lib
            src = dbr_dll
            dst = get_python_lib()

            if os.path.isdir(src):
                lst = os.listdir(src)
                for f in lst:
                    dll = os.path.join(src, f)
                    shutil.copy2(dll, dst)
            else:
                shutil.copy2(src, dst)

setup(name='dbr',
      version='7.1',
      description='Python barcode extension',
      author='Dynamsoft',
      author_email='support@dynamsoft.com',
      url='https://www.dynamsoft.com/Products/Dynamic-Barcode-Reader.aspx',
      license='https://www.dynamsoft.com/Products/barcode-reader-license-agreement.aspx',
      ext_modules=[module_dbr],
      long_description='Dynamsoft Barcode Reader is a software development toolkit which enables barcode recognition of Code 39, Code 129, QR Code, DataMatrix, PDF417 and Aztec.',
      platforms=['Windows', 'Linux', 'macOS'],
      cmdclass={'install': CustomInstall}
      )

For Windows, you have to update dbr_lib_dir and dbr_dll if you change the default installation path.

dbr_lib_dir = r'c:\Program Files (x86)\Dynamsoft\Barcode Reader 7.1\Components\C_C++\Lib'
    dbr_dll = r'c:\Program Files (x86)\Dynamsoft\Barcode Reader 7.1\Components\C_C++\Redist\x64'

For Linux and macOS, copy shared libraries to /usr/lib or alternative LD_LIBRARY_PATH.

dbr_lib_dir = '/usr/lib'

Build the Python barcode extension:

Python setup.py build install

A simple Python barcode app

Create a test.py file:

import sys
import cv2
import os
import json
from dbr import DynamsoftBarcodeReader
dbr = DynamsoftBarcodeReader()

def decodeFile(fileName, templateName=""):
    # 1D, PDF417, QRCODE, DataMatrix, Aztec Code
    barcodeTypes = 0x3FF | 0x2000000 | 0x4000000 | 0x8000000 | 0x10000000
    results = dbr.decodeFile(fileName, barcodeTypes, templateName)

    for result in results:
        print("barcode format: " + result[0])
        print("barcode value: " + result[1])

if __name__ == "__main__":
    print("OpenCV version: " + cv2.__version__)
    barcode_image = ""
    if sys.version_info < (3, 0):
        barcode_image = raw_input("Enter the barcode file: ")
    else:
        barcode_image = input("Enter the barcode file: ")

    if not os.path.isfile(barcode_image):
        print("It is not a valid file.")
    else:
        dbr.initLicense('LICENSE-KEY')
        # Set dbr parameters
        templateName = "dbr"
        settings = {
            "ImageParameter": {"name": templateName,
                               "IntermediateResultSavingMode": {
                                   "Mode": "IRSM_BOTH",
                                   "FolderPath": "d:\\IR"
                               },
                               "TerminatePhase": "TP_BARCODE_RECOGNIZED",
                               "IntermediateResultTypes": [
                                   "IRT_BINARIZED_IMAGE"],
                               },
        }
        params = json.dumps(settings)
        ret = dbr.setParameters(params)
        decodeFile(barcode_image, templateName)

Get a FREE 30-day trial license and update the code:

dbr.initLicense('LICENSE-KEY')

Double-check whether the output directory exists:

"FolderPath": "d:\\IR"

The code snippet here shows the wanted intermediate result is the binarized image:

"IntermediateResultTypes": ["IRT_BINARIZED_IMAGE"],
},

Run the app:

Python test.py

Image 1

The file names started with ‘[ID*’ are the intermediate results of running the barcode decoding algorithms.

Source Code

https://github.com/dynamsoft-dbr/python

What’s Coming Up?

Dynamsoft plans to provide more flexible APIs and customizable parameters in the future. The secret algorithms of Dynamsoft Barcode Reader consist of imaging processing, barcode localization, and barcode decoding. Developers would be permitted to use images generated by some third-party image processing libraries as input. It aims to maximize the barcode reading performance.

Technical Support

If you have any questions about Dynamsoft Barcode Reader SDK, please feel free to contact support@dynamsoft.com.

Release History

v7.1, 08/15/2019

NEW

  • Added automatic blurry frame filtering for the video frame decoding, reducing incorrect barcode recognition.
  • Added three arguments for the CICM_GENERAL of ColourConversionModes to set the weights for the color conversion, providing more flexibility to deal with various kinds of backgrounds by using different weights of three colors: red, green and blue.
  • For C/C++ - Added a new struct FrameDecodingParameters, added methods DBR_InitFrameDecodingParameters()/InitFrameDecodingParameters(), and DBR_StartFrameDecodingEx()/StartFrameDecodingEx() to start a new thread to decode barcodes.
  • For .NET - Added a new struct FrameDecodingParameters, added methods InitFrameDecodingParameters(), and StartFrameDecodingEx() to start a new thread to decode barcodes.

IMPROVED

  • The output of intermediate results can be saved either directly to a folder or to memory or both, by introducing a new parameter, intermediateResultSavingMode, to the struct PublicRuntimeSettings.

FIXED

  • Updated PDF component to v10.3.2.0806
  • Fixed a bug that the deblur function might malfunction in some rare cases.
  • Fixed a bug that the coordinates of barcodes may be calculated incorrectly under some situations.
  • Fixed a bug that the parameter, RequireStartStopChars, might malfunction in some rare cases.
  • Fixed a bug that the angle of barcodes might not be calculated correctly sometimes.
  • Fixed a bug that GetIntermediateResults would throw exception "Value cannot be null.\r\nParameter name: destination"(for .NET version)
  • Fixed a misspelling on Dynamsoft.Barcode.EnumBinarizationMode.BM_LOCAL_BLCOK(for .NET version)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Xiao Ling
Technical Writer Dynamsoft
Canada Canada
Xiao Ling is A technical content writer at Dynamsoft, the leading company of document capture and image processing SDKs.
He is in charge of managing Dynamsoft blog site codepool.biz and Dynamsoft GitHub community.

Comments and Discussions

 
QuestionSponsors Pin
Rick York20-Sep-19 8:34
mveRick York20-Sep-19 8:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 20 Sep 2019

Tagged as

Stats

881 views