二维码又称二维条码,常见的二维码为QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型。
二维码一共有40个版本(尺寸),Version 1是21 x 21的矩阵,Version 2是 25 x 25的矩阵,Version 3是29的尺寸,每增加一个version,就会增加4的尺寸,公式是:(V-1)*4 + 21(V是版本号) 最高Version 40,(40-1)*4+21 = 177,所以最高是177 x 177 的正方形。
利用python第三方库qrcode可以很容易的创建二维码:
from PIL import Image
import qrcode
def createQR(data, savePath="myQR.png", iconPath = None, ratio = 0.333):
qr = qrcode.QRCode(version=10, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=8, border=4)
qr.add_data(data)
#qr.make(fit=True)
img = qr.make_image()
img = img.convert("RGBA")
if iconPath is not None: #带图标的二维码
W, H = img.size
icon = Image.open(iconPath) # 待粘贴的二维码中心的图片
#ratio = 0.25 #中心图片的比例
icon = icon.resize((int(ratio *W), int(ratio*H)), Image.ANTIALIAS)#缩放,设置抗锯齿
x,y = int((1- ratio)*0.5*W), int((1- ratio)*0.5*H) #粘贴位置(左上角点)
icon = icon.convert("RGBA")
img.paste(icon, (x, y), icon)
img.save(savePath)
print('''saved to "%s" ''' % savePath)
#img.show() # 显示图片
return img
createQR("http://www.baidu.com", savePath="myQR0.png")
createQR("小猴子下山去化斋, 老猴子有交代", savePath="myQR1.png", iconPath = "c.jpg")
指定上述自定义函数中的iconPath参数可以绘制带图标的二维码:
还可以通过合成gif得到动态图标的二维码:
#创建动态图标二维码
def gifSplit2Array(gif_path):
import numpy as np
img = Image.open(gif_path)
for i in range(img.n_frames):
img.seek(i)
frame = Image.new("RGBA", img.size)
frame.paste(img)
#arr = np.array(frame).astype(np.uint8) # image: img (PIL Image):
yield frame
def createQR_gif(data, gifIconPath, savePath="myQR.gif", ratio = 0.333):
import imageio #用于创建gif
import numpy as np
qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=8, border=4)
qr.add_data(data)
#qr.make(fit=True)
QRimg = qr.make_image()
QRimg = QRimg.convert("RGBA")
W, H = QRimg.size
frames = []
for icon0 in gifSplit2Array(gifIconPath):
icon = icon0.resize((int(ratio *W), int(ratio*H)), Image.ANTIALIAS)#缩放,设置抗锯齿
x, y = int((1- ratio)*0.5*W), int((1- ratio)*0.5*H) #粘贴位置(左上角点)
icon = icon.convert("RGBA")
QRimg.paste(icon, (x, y), icon)
frame = np.array(QRimg).astype(np.uint8)
frames.append(frame)
imageio.mimsave(savePath, frames, duration=0.3)
print('''saved to "%s" ''' % savePath)
createQR_gif("小猴子爱跳舞", "monkey.gif", savePath="myQR.gif",ratio = 0.5)
本文分享自 Python可视化编程机器学习OpenCV 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!