当前位置:   article > 正文

python zxing识别二维码、条形码_python pyzxing

python pyzxing

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

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

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

相关命令:

  1. git clone https://github.com/oostendo/python-zxing.git
  2. cd python-zxing
  3. wget http://central.maven.org/maven2/com/google/zxing/core/3.3.3/core-3.3.3.jar
  4. wget http://central.maven.org/maven2/com/google/zxing/javase/3.3.3/javase-3.3.3.jar
  5. 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:

  1. ########################################################################
  2. #
  3. # zxing.py -- a quick and dirty wrapper for zxing for python
  4. #
  5. # this allows you to send images and get back data from the ZXing
  6. # library: http://code.google.com/p/zxing/
  7. #
  8. # by default, it will expect to be run from the zxing source code directory
  9. # otherwise you must specify the location as a parameter to the constructor
  10. #
  11. __version__ = '0.3'
  12. import subprocess, re, os
  13. class BarCodeReader():
  14. location = ""
  15. command = "java"
  16. 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"]
  17. args = ["-cp", "LIBS", "com.google.zxing.client.j2se.CommandLineRunner"]
  18. def __init__(self, loc=""):
  19. if not len(loc):
  20. if (os.environ.has_key("ZXING_LIBRARY")):
  21. loc = os.environ["ZXING_LIBRARY"]
  22. else:
  23. loc = ""
  24. self.location = loc
  25. def decode(self, files, try_harder = False, qr_only = False):
  26. cmd = [self.command]
  27. cmd += self.args[:] #copy arg values
  28. if try_harder:
  29. cmd.append("--try_harder")
  30. if qr_only:
  31. cmd.append("--possibleFormats=QR_CODE")
  32. libraries = [self.location + "/" + l for l in self.libs]
  33. cmd = [ c if c != "LIBS" else os.pathsep.join(libraries) for c in cmd ]
  34. # send one file, or multiple files in a list
  35. SINGLE_FILE = False
  36. if type(files) != type(list()):
  37. cmd.append(files)
  38. SINGLE_FILE = True
  39. else:
  40. cmd += files
  41. (stdout, stderr) = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True).communicate()
  42. codes = []
  43. file_results = stdout.split("\nfile:")
  44. for result in file_results:
  45. print result
  46. lines = stdout.split("\n")
  47. if re.search("No barcode found", lines[0]):
  48. codes.append(None)
  49. continue
  50. codes.append(BarCode(result))
  51. if SINGLE_FILE:
  52. return codes[0]
  53. else:
  54. return codes
  55. #this is the barcode class which has
  56. class BarCode:
  57. format = ""
  58. points = []
  59. data = ""
  60. raw = ""
  61. def __init__(self, zxing_output):
  62. lines = zxing_output.split("\n")
  63. raw_block = False
  64. parsed_block = False
  65. point_block = False
  66. self.points = []
  67. for l in lines:
  68. m = re.search("format:\s([^,]+)", l)
  69. if not raw_block and not parsed_block and not point_block and m:
  70. self.format = m.group(1)
  71. continue
  72. if not raw_block and not parsed_block and not point_block and l == "Raw result:":
  73. raw_block = True
  74. continue
  75. if raw_block and l != "Parsed result:":
  76. self.raw += l + "\n"
  77. continue
  78. if raw_block and l == "Parsed result:":
  79. raw_block = False
  80. parsed_block = True
  81. continue
  82. if parsed_block and not re.match("Found\s\d\sresult\spoints", l):
  83. self.data += l + "\n"
  84. continue
  85. if parsed_block and re.match("Found\s\d\sresult\spoints", l):
  86. parsed_block = False
  87. point_block = True
  88. continue
  89. if point_block:
  90. m = re.search("Point\s(\d+):\s\(([\d\.]+),([\d\.]+)\)", l)
  91. if (m):
  92. self.points.append((float(m.group(2)), float(m.group(3))))
  93. return
  94. if __name__ == "__main__":
  95. print("ZXing module")

tests.py:

  1. #!/usr/bin/env python
  2. from zxing import *
  3. zxing_location = ".."
  4. testimage = "sample.png"
  5. def test_barcode_parser():
  6. text = """
  7. file:/home/oostendo/Pictures/datamatrix/4-contrastcrop.bmp (format: DATA_MATRIX, type: TEXT):
  8. Raw result:
  9. 36MVENBAEEAS04403EB0284ZB
  10. Parsed result:
  11. 36MVENBAEEAS04403EB0284ZB
  12. Also, there were 4 result points.
  13. Point 0: (24.0,18.0)
  14. Point 1: (21.0,196.0)
  15. Point 2: (201.0,198.0)
  16. Point 3: (205.23952,21.0)
  17. """
  18. barcode = BarCode(text)
  19. if (barcode.format != "DATA_MATRIX"):
  20. return 0
  21. if (barcode.raw != "36MVENBAEEAS04403EB0284ZB"):
  22. return 0
  23. if (barcode.data != "36MVENBAEEAS04403EB0284ZB"):
  24. return 0
  25. if (len(barcode.points) != 4 and barcode.points[0][0] != 24.0):
  26. return 0
  27. return 1
  28. def test_codereader():
  29. #~ zx = BarCodeReader(zxing_location)
  30. zx = BarCodeReader()
  31. barcode = zx.decode(testimage)
  32. if re.match("http://", barcode.data):
  33. return 1
  34. return 0
  35. if __name__=="__main__":
  36. test_codereader()

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/243053
推荐阅读
相关标签
  

闽ICP备14008679号