Giter Site home page Giter Site logo

yushulx / python-barcode-qrcode-sdk Goto Github PK

View Code? Open in Web Editor NEW
49.0 3.0 24.0 144.36 MB

Build Python barcode QR code SDK with Dynamsoft Barcode Reader.

Home Page: https://pypi.org/project/barcode-qr-code-sdk/

License: MIT License

C 79.91% Python 6.61% CMake 1.73% C++ 11.75%
barcode cpython python python-extension qr-code qrcode cmake cpp scikit-build wheel

python-barcode-qrcode-sdk's Introduction

Python Extension: Barcode and QR Code SDK

The project is a CPython binding to Dynamsoft C/C++ Barcode Reader SDK. It aims to help developers build Python barcode and QR code scanning apps on Windows, Linux and macOS. Besides desktop PCs, it can work well on embedded and IoT devices such as Raspberry Pi and Jetson Nano. You are free to customize the Python API for Dynamsoft Barcode Reader.

About Dynamsoft Barcode Reader

Supported Python Edition

  • Python 3.x

Install Dependencies

pip install opencv-python

Command-line Usage

$ scanbarcode <file-name> -l <license-key>

# Show the image with OpenCV
$ scanbarcode <file-name> -u 1 -l <license-key>

python barcode QR code scanner

How to Build the Python Barcode and QR Code Extension

  • Create a source distribution:

    python setup.py sdist
  • setuptools:

    python setup_setuptools.py build
    python setup_setuptools.py develop # Copy libraries to barcodeQrSDK folder
  • scikit-build:

    python setup.py build
    python setup.py develop # Copy libraries to barcodeQrSDK folder
  • Build wheel:

    pip wheel . --verbose
    # Or
    python setup_setuptools.py bdist_wheel
    # Or
    python setup.py bdist_wheel

Quick Start

  • Console App

    import barcodeQrSDK
    
    # set license
    barcodeQrSDK.initLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")
    
    reader = barcodeQrSDK.createInstance()
    
    results, elapsed_time = reader.decodeFile("test.png")
    for result in results:
        print(result.format)
        print(result.text)
        print(result.x1)
        print(result.y1)
        print(result.x2)
        print(result.y2)
        print(result.x3)
        print(result.y3)
        print(result.x4)
        print(result.y4)
  • Video App

    import barcodeQrSDK
    import numpy as np
    import cv2
    import json
    
    g_results = None
    
    def callback(results, elapsed_time):
        global g_results
        g_results = (results, elapsed_time)
    
    def run():
        # set license
        barcodeQrSDK.initLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")
    
        # initialize barcode scanner
        scanner = barcodeQrSDK.createInstance()
        params = scanner.getParameters()
        # Convert string to JSON object
        json_obj = json.loads(params)
        # json_obj['ImageParameter']['ExpectedBarcodesCount'] = 999
        params = json.dumps(json_obj)
        ret = scanner.setParameters(params)
        
        scanner.addAsyncListener(callback)
    
        cap = cv2.VideoCapture(0)
        while True:
            ret, image = cap.read()
            if image is not None:
                scanner.decodeMatAsync(image)
                
            if g_results != None:
                print('Elapsed time: ' + str(g_results[1]) + 'ms')
                cv2.putText(image, 'Elapsed time: ' + str(g_results[1]) + 'ms', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
                for result in g_results[0]:
                    x1 = result.x1
                    y1 = result.y1
                    x2 = result.x2
                    y2 = result.y2
                    x3 = result.x3
                    y3 = result.y3
                    x4 = result.x4
                    y4 = result.y4
                    
                    cv2.drawContours(image, [np.int0([(x1, y1), (x2, y2), (x3, y3), (x4, y4)])], 0, (0, 255, 0), 2)
                    cv2.putText(image, result.text, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
    
            cv2.imshow('Barcode QR Code Scanner', image)
            ch = cv2.waitKey(1)
            if ch == 27:
                break
        
        scanner.clearAsyncListener()
    
    if __name__ == '__main__':
        run()

    Python barcode and QR code scanner

Methods

  • barcodeQrSDK.initLicense('YOUR-LICENSE-KEY') # set barcode SDK license globally

    barcodeQrSDK.initLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")
  • barcodeQrSDK.createInstance() # create a barcode reader instance

    reader = barcodeQrSDK.createInstance()
  • decodeFile(filename) # decode barcode and QR code from an image file

    results, elapsed_time = reader.decodeFile("test.png")
  • decodeMat(Mat image) # decode barcode and QR code from Mat

    image = cv2.imread("test.png")
    results = reader.decodeMat(image)
    for result in results:
        print(result.format)
        print(result.text)
        print(result.x1)
        print(result.y1)
        print(result.x2)
        print(result.y2)
        print(result.x3)
        print(result.y3)
        print(result.x4)
        print(result.y4)
  • getParameters() # return JSON string

    params = reader.getParameters()
  • setParameters(JSON string) # set barcode SDK parameters

    import json
    json_obj = json.loads(params)
    json_obj['ImageParameter']['DPMCodeReadingModes'][0]['Mode'] = 'DPMCRM_GENERAL'
    json_obj['ImageParameter']['LocalizationModes'][0]['Mode'] = 'LM_STATISTICS_MARKS'
    params = json.dumps(json_obj)
    ret = reader.setParameters(params)
  • addAsyncListener(callback function) # start a native thread and register a Python function for receiving barcode QR code results

  • decodeMatAsync(<opencv mat data>) # decode barcode QR code from OpenCV Mat asynchronously

    def callback(results, elapsed_time):
        print(results)
                                                        
    import cv2
    image = cv2.imread("test.png")
    reader.addAsyncListener(callback)
    reader.decodeMatAsync(image)
    sleep(1)
  • clearAsyncListener() # stop the native thread and clear the registered Python function

  • decodeBytes(bytes, width, height, stride, imageformat) # 0: gray; 1: rgb888

    import cv2
    image = cv2.imread("test.png")
    results, elapsed_time = scanner.decodeBytes(image.tobytes(), image.shape[1], image.shape[0], image.strides[0], barcodeQrSDK.ImagePixelFormat.IPF_BGR_888)
  • decodeBytesAsync # decode image byte array asynchronously

    def callback(results, elapsed_time):
        print(results)
                                                        
    import cv2
    image = cv2.imread("test.png")
    imagebytes = image.tobytes()
    scanner.decodeBytesAsync(image.tobytes(), image.shape[1], image.shape[0], image.strides[0], barcodeQrSDK.ImagePixelFormat.IPF_BGR_888)
    sleep(1)

Online Documentation for Dynamsoft C/C++ Barcode SDK

To customize Python API based on C/C++, please refer to the online documentation.

Supported Barcode Symbologies

  • Linear Barcodes (1D)

    • Code 39 (including Code 39 Extended)
    • 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 (including Micro QR Code)
    • Data Matrix
    • PDF417 (including Micro PDF417)
    • Aztec Code
    • MaxiCode (mode 2-5)
  • Patch Code

  • GS1 Composite Code

python-barcode-qrcode-sdk's People

Contributors

claire-chan avatar vincy1993 avatar yushulx avatar zorowang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

python-barcode-qrcode-sdk's Issues

Error importing on Mac

Hi.

I'm trying to test this but have trouble importing dbr. I followed the instructions on the README but I'm getting the following error when calling import dbr

dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/dbr.cpython-37m-darwin.so, 2): Symbol not found: _DBR_CreateInstance Referenced from: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/dbr.cpython-37m-darwin.so Expected in: flat namespace in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/dbr.cpython-37m-darwin.so

Any help would be really appreciated
Thanks.

speed of your code

Hi .
I want to know how much is the speed of your code in raspberry zero or another versions?
how much fps?

thanks in advance

Cannot read DataMatrix from own images & setParameters leads to TypeError: DBR_InitRuntimeSettingsWithString() failed

Upon successful installation, I am running now into another strange behavior. I am able to read DataMatrix from the provided sample images at Dynamsoft\Barcode Reader 7.2\Images, as:

import os
from dbr import DynamsoftBarcodeReader

dbr = DynamsoftBarcodeReader()
key = "t0068M***"
dbr.initLicense(key)

def decodeFile(fileName):
    try:
        results = dbr.decodeFile(fileName, dbr.BF_ALL)
        if results:
            for result in results:
                print("barcode value: " + result[1])
        else:
            print('Nothing Found.')
    except Exception as err:
        print(err)

decodeFile(r'Dynamsoft\Barcode Reader 7.2\Images\DataMatrix.tif')
barcode value: DataMatrix.No.2
barcode value: DataMatrix.No.1
barcode value: DataMatrix.No.4
barcode value: DataMatrix.No.3

However, I am not able to read datamatrix from my own jpg images, for example:
BF1907025131

The interesting part is that using Dynamsoft Barcode Reader SDK Windows Desktop version or on the online demo, I am able to read the datamatrix for the very same images, well only when Coverage option is chosen!

UPDATE:
It was pointed out to me from the support team that setting up the right parameters indeed helps a lot. I am now setting up the parameters in the DynamsoftBarcodeReader() instance similar to the Coverage option in online demo. I do it as follows based on the examples provided in the Dynamsoft\Barcode Reader 7.2\examples\command-line\test.py:

    dbr.initLicense(key)        
    # Get default barcode params
    params = dbr.getParameters()
    # Convert string to JSON object
    json_obj = json.loads(params)
    # Update JSON object
    templateName = json_obj['ImageParameter']['Name']
    
    # DPM
    json_obj['ImageParameter']['DeblurLevel'] = 9
    json_obj['ImageParameter']['ScaleDownThreshold'] = 99999

    # LocalizationModes
    json_obj['ImageParameter']['LocalizationModes'][0]['Mode'] = 'LM_STATISTICS_MARKS'
    json_obj['ImageParameter']['LocalizationModes'][0]['Mode'] = 'LM_LINES'
    json_obj['ImageParameter']['LocalizationModes'][0]['Mode'] = 'LM_STATISTICS'
    
    # Convert JSON object to string
    params = json.dumps(json_obj)
    # Set parameters
    ret = dbr.setParameters(params)

But this returns a new error:

        16     # Set parameters
---> 17     ret = dbr.setParameters(params)
       18 

TypeError: DBR_InitRuntimeSettingsWithString() failed

I think it complains about the format of the params, but whatever I have tried does not work. The params looks like this (I believe it is a string-quoted json):

'{
    "ImageParameter": {
        "BarcodeColourModes": [
            {
                "LightReflection": 1,
                "Mode": "BICM_DARK_ON_LIGHT"
            }
        ],
        "BarcodeComplementModes": [
            {
                "Mode": "BCM_SKIP"
            }
        ],
        "BarcodeFormatIds": [
            "BF_ALL"
        ],
        "BinarizationModes": [
            {
                "BlockSizeX": 0,
                "BlockSizeY": 0,
                "EnableFillBinaryVacancy": 1,
                "ImagePreprocessingModesIndex": -1,
                "Mode": "BM_LOCAL_BLOCK",
                "ThreshValueCoefficient": 10
            }
        ],
        "ColourClusteringModes": [
            {
                "Mode": "CCM_SKIP"
            }
        ],
        "ColourConversionModes": [
            {
                "BlueChannelWeight": -1,
                "GreenChannelWeight": -1,
                "Mode": "CICM_GENERAL",
                "RedChannelWeight": -1
            }
        ],
        "DPMCodeReadingModes": [
            {
                "Mode": "DPMCRM_GENERAL"
            }
        ],
        "DeblurLevel": 9,
        "DeformationResistingModes": [
            {
                "Mode": "DRM_SKIP"
            }
        ],
        "Description": "",
        "ExpectedBarcodesCount": 0,
        "ExtendedBarcodeFormatIds": null,
        "FormatSpecificationNameArray": null,
        "GrayscaleTransformationModes": [
            {
                "Mode": "GTM_ORIGINAL"
            }
        ],
        "ImagePreprocessingModes": [
            {
                "Mode": "IPM_GENERAL"
            }
        ],
        "IntermediateResultSavingMode": {
            "Mode": "IRSM_MEMORY"
        },
        "IntermediateResultTypes": [
            "IRT_NO_RESULT"
        ],
        "LocalizationModes": [
            {
                "Mode": "LM_STATISTICS"
            },
            {
                "Mode": "LM_SCAN_DIRECTLY",
                "ScanStride": 0
            },
            {
                "Mode": "LM_STATISTICS"
            },
            {
                "Mode": "LM_LINES"
            }
        ],
        "MaxAlgorithmThreadCount": 4,
        "Name": "currentRuntimeSettings",
        "PDFRasterDPI": 300,
        "Pages": "",
        "RegionDefinitionNameArray": null,
        "RegionPredetectionModes": [
            {
                "Mode": "RPM_GENERAL"
            }
        ],
        "ResultCoordinateType": "RCT_PIXEL",
        "ReturnBarcodeZoneClarity": 0,
        "ScaleDownThreshold": 99999,
        "TerminatePhase": "TP_BARCODE_RECOGNIZED",
        "TextAssistedCorrectionMode": {
            "BottomTextPercentageSize": 0,
            "LeftTextPercentageSize": 0,
            "Mode": "TACM_VERIFYING",
            "RightTextPercentageSize": 0,
            "TopTextPercentageSize": 0
        },
        "TextFilterModes": [
            {
                "MinImageDimension": 65536,
                "Mode": "TFM_GENERAL_CONTOUR",
                "Sensitivity": 0
            }
        ],
        "TextResultOrderModes": [
            {
                "Mode": "TROM_CONFIDENCE"
            },
            {
                "Mode": "TROM_POSITION"
            },
            {
                "Mode": "TROM_FORMAT"
            }
        ],
        "TextureDetectionModes": [
            {
                "Mode": "TDM_GENERAL_WIDTH_CONCENTRATION",
                "Sensitivity": 5
            }
        ],
        "Timeout": 10000
    },
    "Version": "3.0"
}'

I am running out of options! What is going on here?

error: command 'cl.exe' failed: No such file or directory

Environments:

  • Dynamsoft Barcode Reader 7.2 (license activated)
  • Windows 10
  • Visual Studio 2019 (16.3.4)
  • Python 3.7.3
  • Opencv-python 4.1.0.25
  • Numpy 1.16.4

Based on the instructions:

  • SET VS90COMNTOOLS=%VS160COMNTOOLS%
  • Edited setup.py with the right paths to libs and dlls.

Also note that I followed this instruction to install C++ build tools for Visual Studio. Further I have set 'cl.exe' path the environment variable (C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\bin\Hostx64\x64).

Whatever I do I get the following error when running in an Anaconda prompt:

cd src
python setup.py build install
python3 setup.py build install

running build
running build_ext
building 'dbr' extension
cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -IC:\Users\MajidMortazavi\Anaconda3\lib\site-packages\numpy\core\include\numpy -IC:\Users\MajidMortazavi\Anaconda3\include -IC:\Users\MajidMortazavi\Anaconda3\include /Tcdbr.c /Fobuild\temp.win-amd64-3.7\Release\dbr.obj
error: command 'cl.exe' failed: No such file or directory

I am guessing that still I have still issues with C++ build tools for Visual Studio and Paths!!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.