使用pyzbar解析二维码图片

匿名 (未验证) 提交于 2019-12-02 23:34:01
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyBluewind/article/details/90340456

需要依赖pyzbar库,依赖zbar库,可搜索安装。

from pyzbar.pyzbar import decode from PIL import Image import os import cv2 import numpy as np   def test_image_dir():     for one in os.listdir("./images"):         # image=cv2.imread(filepath)         image = Image.open("./images/" + one)         results = decode(image)          info = "{}\t size: {} ".format(one, len(results))         for res in results:             info += "{}({}), {}\t".format(res.data, res.type, res.rect)         # print("size: {}".format(len(a)))         # print(a[0].type, a[0].data, a[0].rect)         print(info)   """ [     Decoded(         data=b'Foramenifera', type='CODE128',         rect=Rect(left=37, top=550, width=324, height=76),         polygon=[             Point(x=37, y=551), Point(x=37, y=625), Point(x=361, y=626),             Point(x=361, y=550)         ]     )     Decoded(         data=b'Rana temporaria', type='CODE128',         rect=Rect(left=4, top=0, width=390, height=76),         polygon=[             Point(x=4, y=1), Point(x=4, y=75), Point(x=394, y=76),             Point(x=394, y=0)         ]     ) ] """  import requests as req from io import BytesIO import base64   def test_image_url():     all_no = 0     right_no = 0      # 329/393   0.83715     qr_file = "image_urls.txt"      # 150 0标签, 其他所有数据     no_qr_file = "not_qr_image_urls.txt"      with open(no_qr_file) as f:         for line in f:             key = line.strip()              url = "https://si.geilicdn.com/{}".format(key)             resp = req.get(url)              image1 = Image.open(BytesIO(resp.content))              results = decode(image1)             all_no += 1             if len(results) > 0:                 right_no += 1              info = "{}\t size: {} ".format(key, len(results))             for res in results:                 info += "{}({}), {}\t".format(res.data, res.type, res.rect)             # print("size: {}".format(len(a)))             # print(a[0].type, a[0].data, a[0].rect)             print(info)      print("{}/{}".format(right_no, all_no))   def test_image_file():     all_no = 0     right_no = 0      key2label = {}     with open("./label.result") as f:         for line in f:             image_key, label = line.strip().split(" ")             key2label[image_key] = int(label)      fout = open("pyzbar_qr_result.txt", "w")     with open("./data.base64") as f:         for line in f:             try:                 image_key, itemid, b64str = line.strip().split("\t")                  image_file = base64.b64decode(b64str)                 img_array = np.asarray(bytearray(image_file), dtype=np.uint8)                 image1 = cv2.imdecode(img_array, cv2.IMREAD_COLOR)                  # image1 = Image.open(BytesIO(image_file))                  results = decode(image1)                 all_no += 1                 """                 if key2label[image_key] == "13":                     if len(results) > 0:                         right_no += 1                     else:                         print("============ {} {}".format(image_key, results))                 else:                     if len(results) == 0:                         right_no += 1                     else:                         print("============ {} {}".format(image_key, results))                 """                  info = "{}\t{}\t{}\t".format(image_key, key2label[image_key], len(results))                 for res in results:                     # TODO:  判断 one 的长度大于0,  纯数字也有问题                     info += "{},".format(res.data.decode())                 # print("size: {}".format(len(a)))                 # print(a[0].type, a[0].data, a[0].rect)                 info += "\n"                 fout.write(info)              except Exception as e:                 print("{} {}".format(line[:100], e))      fout.close()      print("{}/{}".format(right_no, all_no))   # test_image_file()   def formats():     f1 = "./pyzbar_qr_result.txt"     f2 = "./pyzbar_qr_result.txt_2"      f2 = open(f2, "w")     with open(f1) as f:         for line in f:             # bj-vshop-422200229-1539101143736-1554816003_984_984.jpg	0	1	b'https://u.wechat.com/ED9hyuR9PJVnPFZIxwSdO9o',             datas = line.strip().split("\t")              if len(datas) == 3:                 f2.write(line)              elif len(datas) == 4:                 image_key, label, sizes, data = datas                  data = data.split(",")[:-1]                  info = ""                 for one in data:                     # TODO:  判断 one 的长度大于0,  纯数字也有问题                     info += "{},".format(eval(one).decode())                  f2.write("{}\t{}\t{}\t{}\n".format(image_key, label, sizes, info))              else:                 print("error {}".format(line.strip()))      f2.close()   def save_diff_images():     mp = {}     with open("./see_diff.txt") as f:         for line in f:             if "all:" in line:                 continue              image_key, label, pyzbar, quirc = line.strip().split("\t")             mp[image_key.strip()] = "{}_pyzbar{}_quirc{}".format(label, pyzbar, quirc)      with open("./data.base64") as f:         for line in f:             try:                 image_key, itemid, b64str = line.strip().split("\t")                  if image_key in mp:                     image_file = base64.b64decode(b64str)                     img_array = np.asarray(bytearray(image_file), dtype=np.uint8)                     image1 = cv2.imdecode(img_array, cv2.IMREAD_COLOR)                      cv2.imwrite("./diff_images/{}_{}".format(mp[image_key], image_key), image1)              except Exception as e:                 print("{} {}".format(line[:100], e))   save_diff_images()  
文章来源: https://blog.csdn.net/wyBluewind/article/details/90340456
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!