zxing 本是java的二维码识别包,python要调用zxing就需要java的环境,java可以自己百度安装,不做过多介绍。
pip install jpype # python调java的包
pip install zxing
javase.jar
core.jar
下载链接:https://download.csdn.net/download/qq_40430818/20232432
import os
import sys
from jpype import *
Base_DIR=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(Base_DIR)
class ZXQRcode(object):
def __init__(self):
# jar包的路径
self.jar_path = Base_DIR + '/static/java/javase.jar'
self.jar_path2 = Base_DIR + '/static/java/core.jar'
# 启动JVM
try:
startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=%s;%s" % (self.jar_path, self.jar_path2))
except:
pass
# 加载需要加载的类
self.File = JClass("java.io.File")
self.ImageIO = JClass("javax.imageio.ImageIO")
self.BufferedImageLuminanceSource = JClass("com.google.zxing.client.j2se.BufferedImageLuminanceSource")
self.Hashtable = JClass("java.util.Hashtable")
self.MultiFormatReader = JClass("com.google.zxing.MultiFormatReader")
self.HybridBinarizer = JClass("com.google.zxing.common.HybridBinarizer")
self.DecodeHintType = JClass("com.google.zxing.DecodeHintType")
self.BinaryBitmap = JClass("com.google.zxing.BinaryBitmap")
self.BitMatrix = JClass("com.google.zxing.common.BitMatrix")
self.Detector = JClass("com.google.zxing.qrcode.detector.Detector")
self.DetectorResult = JClass("com.google.zxing.common.DetectorResult")
# 释放JVM
def dels(self):
import jpype
try:
jpype.shutdownJVM()
except Exception as e:
pass
# 解析二维码
def analysis_QR(self, image_path):
# 读入图片
try:
imageFile = self.File(image_path)
image = self.ImageIO.read(imageFile)
source = self.BufferedImageLuminanceSource(image)
hybridBinarizer = self.HybridBinarizer(source)
matrix = hybridBinarizer.getBlackMatrix()
binaryBitmap = self.BinaryBitmap(hybridBinarizer)
hints = self.Hashtable()
hints.put(self.DecodeHintType.CHARACTER_SET, "UTF-8")
detectorResult = self.Detector(matrix).detect(hints)
resultPoints = self.MultiFormatReader().decodeWithState(binaryBitmap).getResultPoints()
coordinateList = [str(resultPoints[0]), str(resultPoints[1]), str(resultPoints[2])]
matrix1 = detectorResult.getBits()
result = self.MultiFormatReader().decode(binaryBitmap, hints)
return result.getText(), matrix1, coordinateList
except Exception as e:
return False
if __name__ == "__main__":
image_path = r"E:\liziimage\b_lizi\st1618198605.jpg"
zx = ZXQRcode()
print(zx.analysis_QR(image_path))
zx.dels()