python二维码生成与扫码

(1)
import qrcode
img = qrcode.make("hello world!")
img.get_image().show()
img.save('hello.png')

(2)
import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('Some data')
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")
img.save('qrcode.png')

version参数为一个取值范围1-40的整数(或字符串),用于控制二维码的尺寸。最小的尺寸1是一个21格*21格的矩阵。该值设置为None(默认),并且调用make函数时fit参数为True(默认)时,模块会自己决定生成二维码的尺寸。

error_correction参数用于控制二维码的错误纠正程度。可以取以下四个保存在模块中的常量:

ERROR_CORRECT_L:大约7%或者更少的错误会被更正。
ERROR_CORRECT_M:默认值,大约15%或者更少的错误会被更正。
ERROR_CORRECT_Q:大约25%或者更少的错误会被更正。
ERROR_CORRECT_H:大约30%或者更少的错误会被更正。

box_size参数控制二维码中每个格子的像素数,默认为10。

border参数控制边框(二维码四周留白)包含的格子数(默认为4,是标准规定的最小值)。

image_factory参数是一个继承于qrcode.image.base.BaseImage的类,用于控制make_image函数返回的图像实例。image_factory参数可以选择的类保存在模块根目录的image文件夹下。image文件夹里面有五个.py文件,其中一个为__init__.py,一个为base.py。还有pil.py提供了默认的qrcode.image.pil.PilImage类。pure.py提供了qrcode.image.pure.PymagingImage类。svg.py提供了SvgFragmentImage、SvgImage和SvgPathImage三个类。

(3)
from PIL import Image
import qrcode


# 初步生成二维码图像
qr = qrcode.QRCode(version=5,error_correction=qrcode.constants.ERROR_CORRECT_H,box_size=8,border=4)
qr.add_data("http://www.cnblogs.com/sfnz/")
qr.make(fit=True)

# 获得Image实例并把颜色模式转换为RGBA
img = qr.make_image()
img = img.convert("RGBA")

# 打开logo文件
icon = Image.open("D:/favicon.jpg")

# 计算logo的尺寸
img_w,img_h = img.size
factor = 4
size_w = int(img_w / factor)
size_h = int(img_h / factor)

# 比较并重新设置logo文件的尺寸
icon_w,icon_h = icon.size

if icon_w >size_w:
    icon_w = size_w
if icon_h > size_h:
    icon_h = size_h
icon = icon.resize((icon_w,icon_h),Image.ANTIALIAS)

# 计算logo的位置,并复制到二维码图像中
w = int((img_w - icon_w)/2)
h = int((img_h - icon_h)/2)
icon = icon.convert("RGBA")
img.paste(icon,(w,h),icon)


# 保存二维码
img.save('D:/createlogo.jpg')

(4)

python-qrcode是个用来生成二维码图片的第三方模块,依赖于 PIL 模块和 qrcode 库。
简单用法
import qrcode 
img = qrcode.make('hello, qrcode')
img.save('test.png')

(5)
import qrcode 
qr = qrcode.QRCode(     
    version=1,     
    error_correction=qrcode.constants.ERROR_CORRECT_L,     
    box_size=10,     
    border=4, 

qr.add_data('hello, qrcode') 
qr.make(fit=True)  
img = qr.make_image()
img.save('123.png')


参数含义:
version:值为1~40的整数,控制二维码的大小(最小值是1,是个12×12的矩阵)。 如果想让程序自动确定,将值设置为 None 并使用 fit 参数即可。
error_correction:控制二维码的错误纠正功能。可取值下列4个常量。
  ERROR_CORRECT_L:大约7%或更少的错误能被纠正。
  ERROR_CORRECT_M(默认):大约15%或更少的错误能被纠正。
  ROR_CORRECT_H:大约30%或更少的错误能被纠正。
box_size:控制二维码中每个小格子包含的像素数。
border:控制边框(二维码与图片边界的距离)包含的格子数(默认为4,是相关标准规定的最小值)

(6)

import qrcode
 
# 复杂的生成二维码
def make_code(text):
    #  version是二维码的尺寸,数字大小决定二维码的密度       error_correction:是指误差
    # box_size:参数用来控制二维码的每个单元(box)格有多少像素点
    # border: 参数用控制每条边有多少个单元格(默认值是4,这是规格的最小值
    qr = qrcode.QRCode(version=5,
                       error_correction=qrcode.constants.ERROR_CORRECT_L,
                       box_size=8,
                       border=4,
                       )
    # 添加数据
    qr.add_data(text)
    # 生成二维码
    qr.make(fit=True)
    img = qr.make_image()
    img.show()
 
# 简单的生成二维码
def make_code_easy(text):
    image = qrcode.make(text)
    image.save(r"C:\Users\COMPUTER\Desktop\s.png")
    image.show()
    print("image already save: \COMPUTER\Desktop\s.png")
 
if __name__ == '__main__':
    text = input("请输入你想说的话:")
make_code(text)

(7)
import Image


# 打开一个jpg图像文件,注意路径要改成你自己的:
im = Image.open('/Users/michael/test.jpg')

# 获得图像尺寸:
w, h = im.size
# 缩放到50%:
im.thumbnail((w//2, h//2))
# 把缩放后的图像用jpeg格式保存:

im.save('/Users/michael/thumbnail.jpg', 'jpeg')

(8)
模糊效果也只需几行代码:

import Image, ImageFilter

im = Image.open('/Users/michael/test.jpg')
im2 = im.filter(ImageFilter.BLUR)
im2.save('/Users/michael/blur.jpg', 'jpeg')


(9)
生成字母验证码图片:

import Image, ImageDraw, ImageFont, ImageFilter
import random

# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))


# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))


# 240 x 60:
width = 60 * 4
height = 60

image = Image.new('RGB', (width, height), (255, 255, 255))

# 创建Font对象:
font = ImageFont.truetype('Arial.ttf', 36)

# 创建Draw对象:
draw = ImageDraw.Draw(image)

# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())

# 输出文字:
for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())

# 模糊:
image = image.filter(ImageFilter.BLUR)

image.save('code.jpg', 'jpeg');  

(10)
import os
import logging
from PIL import Image
import zxing    #导入解析包
import random


logger = logging.getLogger(__name__)    #记录数据


if not logger.handlers:
    logging.basicConfig(level = logging.INFO)


DEBUG = (logging.getLevelName(logger.getEffectiveLevel()) == 'DEBUG')   #记录调式过程


# 在当前目录生成临时文件,规避java的路径问题
def ocr_qrcode_zxing(filename):
    img = Image.open(filename)
    ran = int(random.random() * 100000)     #设置随机数据的大小
    img.save('%s%s.jpg' % (os.path.basename(filename).split('.')[0], ran))
    zx = zxing.BarCodeReader()      #调用zxing二维码读取包
    data = ''
    zxdata = zx.decode('%s%s.jpg' % (os.path.basename(filename).split('.')[0], ran))    #图片解码


# 删除临时文件
    os.remove('%s%s.jpg' % (os.path.basename(filename).split('.')[0], ran))
    
    if zxdata:
        logger.debug(u'zxing识别二维码:%s,内容: %s' % (filename, zxdata))
        data = zxdata
    else:
        logger.error(u'识别zxing二维码出错:%s' % (filename))
        img.save('%s-zxing.jpg' % filename)
    return data     #返回记录的内容


if __name__ == '__main__':
    filename = r'G:\TestDemo\venv\二维码解析与生成\1536492016.png'
    # zxing二维码识别
    ltext = ocr_qrcode_zxing(filename)  #将图片文件里的信息转码放到ltext里面
    logger.info(u'[%s]Zxing二维码识别:[%s]!!!' % (filename, ltext))  #记录文本信息
    
print(ltext)    #打印出二维码名字

(11)
解析二维码用到zbar模块,改模块在windowns下面是exe文件直接安装,比较简单,在linux下依赖的包比较多,安装过程就不在介绍,使用方法如下:


def get_QR():
    scanner = zbar.ImageScanner()
    scanner.parse_config("enable")
    pil = Image.open("char.png").convert('L')
    width, height = pil.size
    raw = pil.tostring()
    image = zbar.Image(width, height, 'Y800', raw)
    scanner.scan(image)
    data = ''
    for symbol in image:
        data+=symbol.data
    del(image)
    return data
(12)
import numpy as np
import cv2
 
def detect(image):
# convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 
# compute the Scharr gradient magnitude representation of the images
# in both the x and y direction
gradX = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 1, dy = 0, ksize = -1)
gradY = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 0, dy = 1, ksize = -1)
 
# subtract the y-gradient from the x-gradient
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
 
# blur and threshold the image
blurred = cv2.blur(gradient, (9, 9))
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
 
# construct a closing kernel and apply it to the thresholded image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
 
# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
 
# find the contours in the thresholded image
(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
 
# if no contours were found, return None
if len(cnts) == 0:
return None
 
# otherwise, sort the contours by area and compute the rotated
# bounding box of the largest contour
c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
rect = cv2.minAreaRect(c)
box = np.int0(cv2.cv.BoxPoints(rect))
 
# return the bounding box of the barcode
return box

(13)
# import the necessary packages
import simple_barcode_detection
import cv2
import numpy as np
import zbar
from PIL import Image


#接下去是创建一个扫描器,他可以解析二维码的内容


# create a reader
scanner = zbar.ImageScanner()

# configure the reader
scanner.parse_config('enable')

#设置屏幕显示字体

font=cv2.FONT_HERSHEY_SIMPLEX

#启用摄像头

camera=cv2.VideoCapture(0)


#接下去是一个大的while循环


while True:


#得到当前的帧
# grab the current frame
(grabbed, frame) = camera.read()


#检测视频是否到底了,如果检测视频文件里面的二维码或条形码用这个,如果开启摄像头就无所谓了
# check to see if we have reached the end of the
# video
if not grabbed:
break


调用刚才我们建的那个函数来查找二维码返回二维码的位置
# detect the barcode in the image
box = simple_barcode_detection.detect(frame)
if box != None:


#这下面的3步得到扫描区域,扫描区域要比检测出来的位置要大
min=np.min(box,axis=0)
max=np.max(box,axis=0)

roi=frame[min[1]-10:max[1]+10,min[0]-10:max[0]+10]

#把区域里的二维码传换成RGB,并把它转换成pil里面的图像,因为zbar得调用pil里面的图像,而不能用opencv的图像
roi=cv2.cvtColor(roi,cv2.COLOR_BGR2RGB)
pil= Image.fromarray(frame).convert('L')
width, height = pil.size
raw = pil.tostring()


#把图像装换成数据
zarimage = zbar.Image(width, height, 'Y800', raw)

#扫描器进行扫描
scanner.scan(zarimage)

#得到结果
for symbol in zarimage:
   # 对结果进行一些有用的处理
print 'decoded', symbol.type, 'symbol', '"%s"' %symbol.data
cv2.drawContours(frame, [box], -1, (0, 255, 0), 2)

#把解析的内容放到视频上
cv2.putText(frame,symbol.data,(20,100),font,1,(0,255,0),4)

# show the frame and record if the user presses a key
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF

# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break

# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllWindows()

 

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值