当前位置: 首页 > 工具软件 > python-zxing > 使用案例 >

python zxing识别二维码、条形码

郎泰平
2023-12-01

项目地址:https://github.com/oostendo/python-zxing

项目实际就是下载3个jar包,subprocess调用一下而已,比较简单。

1、下载3个依赖包,放在python-zxing中。

相关命令:

git clone https://github.com/oostendo/python-zxing.git

cd python-zxing

wget http://central.maven.org/maven2/com/google/zxing/core/3.3.3/core-3.3.3.jar

wget http://central.maven.org/maven2/com/google/zxing/javase/3.3.3/javase-3.3.3.jar

wget http://central.maven.org/maven2/com/beust/jcommander/1.72/jcommander-1.72.jar

2、执行命令:setup.py install
E:\python-zxing>python setup.py install
running install
running build
running build_py
creating build
creating build\lib
creating build\lib\zxing
copying zxing\tests.py -> build\lib\zxing
copying zxing\__init__.py -> build\lib\zxing
running install_lib
creating C:\Python27\Lib\site-packages\zxing
copying build\lib\zxing\tests.py -> C:\Python27\Lib\site-packages\zxing
copying build\lib\zxing\__init__.py -> C:\Python27\Lib\site-packages\zxing
byte-compiling C:\Python27\Lib\site-packages\zxing\tests.py to tests.pyc
byte-compiling C:\Python27\Lib\site-packages\zxing\__init__.py to __init__.pyc
running install_egg_info
Removing C:\Python27\Lib\site-packages\zxing-0.1-py2.7.egg-info
Writing C:\Python27\Lib\site-packages\zxing-0.1-py2.7.egg-info

3、这里看到zxing被安装到了C:\Python27\Lib\site-packages\zxing
将core-3.3.3.jar、javase-3.3.3.jar、jcommander-1.72.jar复制到:\Python27\Lib\site-packages\zxing这个目录下
3、修改上面路径下的__init__.py文件
  libs = ["javase/javase.jar", "core/core.jar"]
改为
  libs = [r"C:\Python27\Lib\site-packages\zxing\javase-3.3.3.jar", r"C:\Python27\Lib\site-packages\zxing\core-3.3.3.jar", r"C:\Python27\Lib\site-packages\zxing\jcommander-1.72.jar"]

loc = ".."
改为:
loc = ""

    for result in file_results:
      lines = stdout.split("\n")
改为
    for result in file_results:
      print result
      lines = stdout.split("\n")

4.运行tests即可输出
E:\python-zxing\zxing>tests.py
file:///E:/python-zxing/zxing/sample.png (format: QR_CODE, type: URI):
Raw result:
http://tinyurl.com/openmichiganrsvp
Parsed result:
http://tinyurl.com/openmichiganrsvp
Found 4 result points.
  Point 0: (75.5,273.5)
  Point 1: (75.5,75.5)
  Point 2: (273.5,75.5)
  Point 3: (246.5,246.5)


注意,如果你自己使用时,识别的图片路径是绝对路径,会报错:
from zxing import *
import sys
def test_codereader(image_path):
  zx = BarCodeReader()
  barcode = zx.decode(image_path)
  print barcode.data

if __name__=="__main__":
   test_codereader(sys.argv[1]) 

E:\>python mywork.py e:\pic\sample.png
报错:
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical
        at java.base/sun.nio.fs.WindowsUriSupport.fromUri(WindowsUriSupport.java:122)
        at java.base/sun.nio.fs.WindowsFileSystemProvider.getPath(WindowsFileSystemProvider.java:93)
        at java.base/java.nio.file.Path.of(Path.java:203)
        at java.base/java.nio.file.Paths.get(Paths.java:97)
        at com.google.zxing.client.j2se.CommandLineRunner.expand(CommandLineRunner.java:112)
        at com.google.zxing.client.j2se.CommandLineRunner.main(CommandLineRunner.java:76)
        
你只需要改变一下传入路径,变为:
E:\>python mywork.py file:/e:/pic/sample.png
file:/e:/pic/sample.png (format: QR_CODE, type: URI):
Raw result:
http://tinyurl.com/openmichiganrsvp
Parsed result:
http://tinyurl.com/openmichiganrsvp
Found 4 result points.
  Point 0: (75.5,273.5)
  Point 1: (75.5,75.5)
  Point 2: (273.5,75.5)
  Point 3: (246.5,246.5)


http://tinyurl.com/openmichiganrsvp

 

所有py文件代码:

__init__.py:

########################################################################
#
#  zxing.py -- a quick and dirty wrapper for zxing for python
#
#  this allows you to send images and get back data from the ZXing
#  library:  http://code.google.com/p/zxing/
#
#  by default, it will expect to be run from the zxing source code directory
#  otherwise you must specify the location as a parameter to the constructor
#

__version__ = '0.3'
import subprocess, re, os

class BarCodeReader():
  location = ""
  command = "java"
  libs = [r"C:\Python27\Lib\site-packages\zxing\javase-3.3.3.jar", r"C:\Python27\Lib\site-packages\zxing\core-3.3.3.jar", r"C:\Python27\Lib\site-packages\zxing\jcommander-1.72.jar"]
  args = ["-cp", "LIBS", "com.google.zxing.client.j2se.CommandLineRunner"]

  def __init__(self, loc=""):
    if not len(loc):
      if (os.environ.has_key("ZXING_LIBRARY")):
        loc = os.environ["ZXING_LIBRARY"]
      else:
        loc = ""

    self.location = loc

  def decode(self, files, try_harder = False, qr_only = False):
    cmd = [self.command]
    cmd += self.args[:] #copy arg values
    if try_harder:
      cmd.append("--try_harder")
    if qr_only:
      cmd.append("--possibleFormats=QR_CODE")

    libraries = [self.location + "/" + l for l in self.libs]

    cmd = [ c if c != "LIBS" else os.pathsep.join(libraries) for c in cmd ]

    # send one file, or multiple files in a list
    SINGLE_FILE = False
    if type(files) != type(list()):
      cmd.append(files)
      SINGLE_FILE = True
    else:
      cmd += files

    (stdout, stderr) = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True).communicate()
    codes = []
    file_results = stdout.split("\nfile:")
    for result in file_results:
      print result
      lines = stdout.split("\n")
      if re.search("No barcode found", lines[0]):
        codes.append(None)
        continue

      codes.append(BarCode(result))

    if SINGLE_FILE:
      return codes[0]
    else:
      return codes

#this is the barcode class which has
class BarCode:
  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))))

    return


if __name__ == "__main__":
  print("ZXing module")

tests.py:

#!/usr/bin/env python
from zxing import *

zxing_location = ".."
testimage = "sample.png"




def test_barcode_parser():
  text = """
file:/home/oostendo/Pictures/datamatrix/4-contrastcrop.bmp (format: DATA_MATRIX, type: TEXT):
Raw result:
36MVENBAEEAS04403EB0284ZB
Parsed result:
36MVENBAEEAS04403EB0284ZB
Also, there were 4 result points.
  Point 0: (24.0,18.0)
  Point 1: (21.0,196.0)
  Point 2: (201.0,198.0)
  Point 3: (205.23952,21.0)
"""
  
  barcode = BarCode(text)  
  if (barcode.format != "DATA_MATRIX"):
    return 0

  if (barcode.raw != "36MVENBAEEAS04403EB0284ZB"):
    return 0

  if (barcode.data != "36MVENBAEEAS04403EB0284ZB"):
    return 0

  if (len(barcode.points) != 4 and barcode.points[0][0] != 24.0):
    return 0

  return 1


def test_codereader():
  #~ zx = BarCodeReader(zxing_location)
  zx = BarCodeReader()

  barcode = zx.decode(testimage)
  
  if re.match("http://", barcode.data):
    return 1

  return 0

if __name__=="__main__":
   test_codereader() 

参考:https://www.cnblogs.com/oucsheep/p/6269813.html作者写的更为详细

 类似资料: