Python实现替换图片中嵌入的二维码为自己的二维码

wylc123 1年前 ⋅ 3856 阅读
#!/usr/bin/env python
# _*_coding:utf-8_*_
__author__ = 'Jun'
__time__ = '2019/4/25 10:48'

#识别图片中的二维码,并对二维码进行替换,经过多次验证,识别率极高,替换效果很好,特分享出来,供需要的兄弟参考

import pyzbar.pyzbar as pyzbar
import numpy as np
import cv2
import qrcode
from PIL import Image
import urllib.request

# 生成新的二维码图片并覆盖原图
def detect(im, save_path=None):
    # 解析图片中的二维码内容
    results = pyzbar.decode(im)
    points = []
    # 获取所有解析对象
    for code in results:
        points = code.polygon
    # 如果这些点不形成四边形,则找到一个
    if len(points) > 4:
        hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))
        hull = list(map(tuple, np.squeeze(hull)))
    else:
        hull = points
    # 将cv2对象转换为Image对象
    img = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
    # 若二维码解析成功,则生成新的二维码并覆盖
    if hull:
        # 获取二维码解析数据
        data = results[0].data.decode("utf-8")
        if data:
            width = results[0].rect.width + 2
            height = results[0].rect.height + 2
            left = results[0].rect.left - 1
            top = results[0].rect.top - 1
            # 生成带中心图标的二维码  data为原来的二维码数据,可以替换为自己的数据
            qr_code_img = make_qr_code_with_icon(data, 'F:/image/log.jpg')
            # 设置二维码的尺寸
            qr_code_img = qr_code_img.resize((width, height), Image.ANTIALIAS)
            # 将原图上的二维码替换为新的二维码
            img.paste(qr_code_img, (left,top))
    # 保存新生成的图片
    if save_path:
        img.save(save_path)
    # 显示原图和新生成的图片
    img.show()
    cv2.imshow('imshow', im)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return save_path

# 生成新的带中心logo的二维码图片
def make_qr_code_with_icon(content, icon_path):
    # 生成一张二维码图片
    qr_code_maker = qrcode.QRCode(version=5,
                                  error_correction=qrcode.constants.ERROR_CORRECT_L,
                                  box_size=10,
                                  border=0,
                                  )
    qr_code_maker.add_data(data=content)
    qr_code_maker.make(fit=True)
    qr_code_img = qr_code_maker.make_image(fill_color="black", back_color="white").convert('RGBA')
    # 加载中心图标,设置大小
    icon_img = Image.open(icon_path)
    code_width, code_height = qr_code_img.size
    icon_img = icon_img.resize((code_width // 4, code_height // 4), Image.ANTIALIAS)
    # 将图标放置于原始图片上
    qr_code_img.paste(icon_img, (code_width * 3 // 8, code_width * 3 // 8))
    return qr_code_img;

# 根据图片路径获取cv2对象
def get_cv2_image(img_path):
    image = None
    if img_path.startswith('http:') or img_path.startswith('https:'):
        # 从网络路径加载图片资源
        resp = urllib.request.urlopen(img_path)
        image = np.asarray(bytearray(resp.read()), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    else:
        # 从本地获取图片资源
        image = cv2.imread(img_path)
    return image

if __name__ == '__main__':
    # img_path = 'https://bpb-test.oss-cn-beijing.aliyuncs.com/test/1.jpg?OSSAccessKeyId=LTAIBGsGFQH2Kxns&Expires=1555700356&Signature=%2FgLKrl4Fyjko%2FD97OmJGHlYea3s%3D'
    img_path = 'F:/image/zfb1.jpg'
    image = get_cv2_image(img_path)
    detect(image)
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: