[Python] uses the Zxing module in the Windows system to realize QR code, barcode reading

Source: Internet
Author: User
Tags java se



?? Need to implement Python to read the QR code, barcode information in the picture. The previous period of time research using Zbarlight module, a lot of effort to install debugging, but found some pictures are not read correctly, and if the image of the two-dimensional code tilt, can not read, can not meet the requirements. Yesterday, trying to try zxing, download zxing module after installation, but has been an error. Open Module Source code careful analysis, the original module is called by the Java program, using zxing Java Library to achieve, through the analysis of command line output to get decoded results. Busy more than a day, a variety of testing, check data, and finally solved the problem. The commissioning process is very difficult, and the practice is now organized as follows (Windows 10 system):


? First, the JDK must be installed because a Java program needs to be called.
    • Download the Java installer and follow the prompts to install it step-by-step.


: http://www.oracle.com/technetwork/java/javase/downloads/index.html.


    • Set environment variables.


Add the JAVA_HOME environment variable whose value is set to the JDK installation directory. Add the directory where the JAVA run program resides (%java_home%\bin) to path.


    • Enter and execute on the command linejava -version, and if there is no problem, the installation is successful.
Download the jar library file for zxing and the required Java library files.
    • Download zxing core and zxing Java SE Extensions library files.


Login URL http://www.mvnrepository.com, enter "Zxing" in the search field and find the two libraries, download the library file and rename it to Core.jar and Javase.jar respectively.


    • Download the Jcommander library file.


In the test, after installing the above two libraries, still error messages, errors in the message that the Jcommander module can not find, and later downloaded the library file, after many times debugging, and finally success. Login URL http://www.mvnrepository.com, enter "Jcommander" in the search field and find it, you can find this library, download the library file and rename it to Jcommander.jar.


    • Create a directory and copy the above three jar files into it.


This directory can be created in the Java installation directory. I created a folder named Jar in the Java directory and copied the above three files into it.


    • Set environment variables.


Add the ZXING_JAR_PATH environment variable, set its value to the absolute path of the folder created above, and my path is "D:\java\jar".


? Third, in the zxing source code based on the modification, the realization of two-dimensional code, barcode decoding function, the addition of two functions to resolve the image is not supported in Windows absolute path of the problem.
#import module
Import subprocess, re, os

Class BarCodeReader():
    """
    The decoder class, call java to execute the ZXing library command to achieve decoding, and obtain the result by analyzing the output.
    This module is modified on the basis of ZXing source code and has a large change.
    """

    ZXing library path
    Location = ""
    ZXing library
    Libs = ["javase.jar", "core.jar", "jcommander.jar"]
    #subprocess.PopenParameter
    Args = ["java", "-cp", "LIBS", "com.google.zxing.client.j2se.CommandLineRunner"]

    Def __init__(self, loc=None):
        """
        Initialization function, parameter loc sets the location of the ZXing library
        """
        
        #If loc is empty or not a string object, read the value of the environment variable ZXING_JAR_PATH (set to an empty string if not found)
        If not loc or not isinstance(loc,str):
            Loc = os.environ.get("ZXING_JAR_PATH", "")
        
        #If loc is not empty, add ‘\‘ at the end, otherwise set to the default value (ie in the zxing subdirectory of the current directory)
        If loc:
            Loc = loc.rstrip("\\") + "\\"
        Else:
            Loc = "zxing\\"
    
        #Set location
        Self.location = loc

    Def decode(self, files, try_harder = False, qr_only = False):
        """
        The decoding method, the parameter files can be a file name (string), or a list of file names.
        """
        
        #Add the appropriate option according to the try_harder and qr_only parameter settings
        If try_harder:
            Self.args.append("--try_harder")
        If qr_only:
            Self.args.append("--possibleFormats=QR_CODE")

        #Add path to ZXing library
        Libraries = [self.location + lib for lib in self.libs]
        
        #Generate command list
        Cmd = [ c if c != "LIBS" else os.pathsep.join(libraries) for c in self.args ]
        
        #Single file flag set to False
        SINGLE_FILE = False
        
        #If files is not a list, add the file files to the cmd list, and the single file flag is set to True.
        If not isinstance(files, list):
            Cmd.append(files)
            SINGLE_FILE = True
        # Otherwise, add the file list files to the cmd list
        Else:
            Cmd += files
        
        #Execute commands with subprocess.Popen function
        (stdout, stderr) = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True).communicate()
        
        #Initialize the code list
        Codes = []
        
        #Analyze output
        File_results = stdout.split("\nfile:")
        For result in file_results:
            Lines = result.split("\n")
            If re.search("No barcode found", lines[0]):
                Codes.append(None)
            Else:
                Codes.append(BarCode(result))

        #If it is a single file, return the first BarCode object; otherwise, return a list of BarCode objects
        If SINGLE_FILE:
            Return codes[0]
        Else:
            Return codes

Class BarCode:
    """
    The BarCode information class contains information about the decoding.
    This module basically uses the ZXing source code, adding several properties for ease of use.
    """
    Format = ""
    Points = []
    Data = ""
    Raw = ""

    Def __init__(self, zxing_output):
        Lines = zxing_output.split("\n")
        Raw_block = False
        Parsed_block = False
        Point_block = False

        Self.points = []
        For l in lines:
            m = re.search("format:\s([^,]+)", l)
            If not raw_block and not parsed_block and not point_block and m:
                Self.format = m.group(1)
                Continue

            If not raw_block and not parsed_block and not point_block and l == "Raw result:":
                Raw_block = True
                Continue

            If raw_block and l != "Parsed result:":
                Self.raw += l + "\n"
                Continue

            If raw_block and l == "Parsed result:":
                Raw_block = False
                Parsed_block = True
                Continue

            If parsed_block and not re.match("Found\s\d\sresult\spoints", l):
                Self.data += l + "\n"
                Continue

            If parsed_block and re.match("Found\s\d\sresult\spoints", l):
                Parsed_block = False
                Point_block = True
                Continue

            If point_block:
                m = re.search("Point\s(\d+):\s\(([\d\.]+),([\d\.]+)\)", l)
                If (m):
                    Self.points.append((float(m.group(2)), float(m.group(3))))
        
        # Remove extra line breaks
        Self.raw = self.raw.rstrip("\n")
        Self.data = self.data.rstrip("\n")

    @property
    Def Format(self):
        """
        Return encoding format
        """
        Return self.format
        
    @property
    Def Data(self):
        """
        Return encoded data
        """
        Return self.data
        
    @property
    Def Points(self):
        """
        Return coordinate point
        """
        Return self.points
        
    @property
    Def RawData(self):
        """
        Return the decoded raw data
        """
        Return self.raw

Def GetCodeString(filename):
    """
    The decoding function only processes a single file, and the parameter is the file name (including the path).
    Returns the encoded string, or an empty string if the barcode is not successfully decoded or the barcode is not found.
    """
    
    #Replace ‘\’ with ‘/’
    Filename = filename.replace("\\", "/")

    #If you have a drive letter (absolute path), precede it with ‘file:/‘
    If re.match(‘^[A-Za-z]:‘, filename):
        Filename = "file:/" + filename

    #Create a decoder object
    Zxcode = BarCodeReader()

    #Decode and save the result to barcode
    Barcode = zxcode.decode(filename)

    #If the result is None, return an empty string, otherwise return the encoded string
    If barcode is None:
        Return ""
    Else:
        Return barcode.Data

Def GetCodeObject(filename):
    """
    The decoding function only processes a single file, and the parameter is the file name (including the path).
    Returns the encoding object with the following properties:
        Data, encoding information;
        Format, encoding category;
Points, coordinate points;
         RawData, unprocessed encoding information.
     If the barcode is not successfully decoded or the barcode is not found, return None
     """
    
     #Replace ‘\’ with ‘/’
     Filename = filename.replace("\\", "/")

     #If you have a drive letter (absolute path), precede it with ‘file:/‘
     If re.match(‘^[A-Za-z]:‘, filename):
         Filename = "file:/" + filename

     #Create a decoder object
     Zxcode = BarCodeReader()
     #Decode and save the result to barcode
     Barcode = zxcode.decode(filename)

     #Return result
     Return barcode
? Iv. testing. Save the above code in the zxing.py file and edit the test code as follows:
from zxing import GetCodeString,GetCodeObject
result = GetCodeString("d:\\barcode.png")
print(result)
result = GetCodeObject("d:\\qr.png")
if result:
    print("Format:", result.Format)
    print("Data:  ", result.Data)
    print("Points:")
    for point in result.Points:
        print(point)
? Five, you can install the above code into the Python library (registered aszxingmodule).
    • Download the Python-zxing module. For https://github.com/oostendo/python-zxing.

    • Unzip to the Python-zxing folder.

    • Replace the contents of the __init__.py file in the Python-zxing\zxing folder with the third-step code.

    • Open the command line under the Python-zxing folder and run itpython setup.py install.

    • You can also use the fourth step of the code to test.


[Python] uses the Zxing module in the Windows system to realize QR code, barcode reading


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.