python zxing識別二維碼、條形碼

項目地址: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作者寫的更爲詳細

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章