Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 20 章 图形开发

目录

20.1. 二维码
20.1.1. qrcode
20.1.2. MyQR
20.1.3. 从图片识别二维码
20.1.4. 从摄像头识别二维码
20.2. graphviz
20.2.1. 安装 graphviz 环境
20.2.2. 例子
20.3. Pyro - Pyro is short for PYthon Remote Objects
20.4. Python Imaging Library
20.5. OpenCV
20.5.1. 安装 OpenCV
20.5.2. 显示图片
20.5.3. 将BGR图像转为RGB
20.5.4. uint8 格式
20.5.5. 应用Canny边缘检测
20.5.6. 摄像头捕捉图像
20.5.7. imread()
20.5.8. 通道拆分/合并
20.5.9. HSV 色彩识别
20.5.10. 色阶调整
20.5.11. 亮度调节
20.6. PIL(Python Imaging Library)Python 图像处理库
20.6.1. 安装
20.6.2. 缩放图像与尺寸修改
20.6.3. 叠加图像
20.6.4. 图像旋转
20.6.5. 获取图片信息
20.6.6. 创建空图像
20.6.7. 裁剪
20.6.8. 彩色转灰度
20.6.9. RGB 通道操作
20.6.10. 像素操作
20.6.11. 图像上加文字
20.6.12. 明暗调整
20.6.13. PIL 与 Numpy 相互转换
20.6.14. 比较两张图片
20.7. SVG 图形库
20.7.1. SVG 标签
20.7.2. drawsvg
20.7.3. CairoSVG - SVG 转换为 PNG/PDF/PS

20.1. 二维码

20.1.1. qrcode

安装

pip install qrcode

		
neo@MacBook-Pro-Neo ~ % pip install qrcode
Collecting qrcode
  Downloading qrcode-6.1-py2.py3-none-any.whl (31 kB)
Requirement already satisfied: six in /usr/local/lib/python3.9/site-packages (from qrcode) (1.15.0)
Installing collected packages: qrcode
Successfully installed qrcode-6.1		
		
		

常规二维码

		
import qrcode

img = qrcode.make('《Netkiller Python 手札》')
img.save("text.png")

img = qrcode.make('http://www.netkiller.cn')
img.save("url.png")		
		
		

20.1.1.1. 设置颜色

颜色设置背景为白色,前景为绿色

		
import qrcode as qrcode
qr = qrcode.QRCode(version=1, box_size=10, border=2)
# 向二维码添加数据
qr.add_data("http://www.netkiller.cn")
qr.make(fit=True)

# 更改QR的背景为白色和绘画颜色为绿色
img = qr.make_image(fill_color="green", back_color="white")
img.save('green.png')
img.show()  # 显示二维码		
		
			

QRCode 参数



version: 范围为1到40整数(最小值是1,表示12×12的矩阵),如果想让程序自动生成,将值设置为 None 并使用 fit=True 参数即可。
error_correction: 二维码的纠错范围,可以选择4个常量:
1. ERROR_CORRECT_L  7%以下的错误会被纠正
2. ERROR_CORRECT_M  (default) 15%以下的错误会被纠正
3. ERROR_CORRECT_Q  25 %以下的错误会被纠正
4. ERROR_CORRECT_H. 30%以下的错误会被纠正
boxsize: 每个点(方块)中的像素个数
border: 二维码图像外围边框宽度,默认为4

20.1.1.2. qr - script to create QR codes at the command line

			
NAME
       qr - script to create QR codes at the command line

SYNOPSIS
       qr  [--help]  [--factory=FACTORY]  [--optimize=OPTIMIZE] [--error-correction=LEVEL]
       [data]

DESCRIPTION
       This script uses the python qrcode module. It can take data from stdin or from  the
       commandline  and  generate a QR code.  Normally it will output the QR code as ascii
       art to the terminal. If the output is piped to a file, it  will  output  the  image
       (default type of PNG).

OPTIONS
        -h, --help
           Show a help message.


        --factory=FACTORY
           Full  python  path to the image factory class to create the image with. You can
           use the  following  shortcuts  to  the  built-in  image  factory  classes:  pil
           (default), pymaging, svg, svg-fragment, svg-path.


        --optimize=OPTIMIZE
           Optimize  the  data by looking for chunks of at least this many characters that
           could use a more efficient encoding method. Use 0 to turn off  chunk  optimiza-
           tion.


        --error-correction=LEVEL
           The  error  correction  level  to  use. Choices are L (7%), M (15%, default), Q
           (25%), and H (30%).


        data
           The data from which the QR code will be generated.


SEE ALSO
       https://github.com/lincolnloop/python-qrcode/			
			
			

使用方法

			
neo@MacBook-Pro-Neo ~ % qr "Some text" > test.png			
			
			

20.1.2. MyQR

安装依赖包

		
pip install myqr		
		
		
		
from MyQR import myqr
# myqr.run 参数:
# words:文本/链接,或者你想说的话(不支持中文,很不友好)
# picture:背景图
# colorsize:True 表示生成彩图
# save_name:生成的二维码文件名
myqr.run(words="http://www.netkiller.com",
         picture="db.png", colorized=True,
         save_name="netkiller.png")		
		
		

20.1.3. 从图片识别二维码

安装依赖包

		
pip install pyzbar		
		
		

pyzbar 是调用 zbar 共享库,所以还需要安装 zbar

		
brew install zbar		
		
		
		
import numpy as np
from PIL import Image
import pyzbar.pyzbar as pyzbar

# 读取文件,转成数组
im = np.array(Image.open("netkiller.png"))
print(pyzbar.decode(im))
# 返回的信息
print('-' * 50)
# 读取内容
print(pyzbar.decode(im)[0].data.decode("utf-8"))		
		
		

输出信息

		
[Decoded(data=b'http://www.netkiller.com', type='QRCODE', rect=Rect(left=36, top=36, width=297, height=297), polygon=[Point(x=36, y=36), Point(x=36, y=332), Point(x=333, y=333), Point(x=332, y=36)])]
--------------------------------------------------
http://www.netkiller.com		
		
		

20.1.4. 从摄像头识别二维码

		
import cv2
import pyzbar.pyzbar as pyzbar


def decodeQrcode(image):
    barcodes = pyzbar.decode(image)
    for barcode in barcodes:
        # 提取二维码数据
        barcodeData = barcode.data.decode("utf-8")
        barcodeType = barcode.type
        # 打印调试信息
        print("[INFO] Found {}: {}".format(barcodeType, barcodeData))

        # 取出二维码在图像中的位置
        (x, y, w, h) = barcode.rect
        cv2.rectangle(image, (x, y), (x + w, y + h),
                      (255, 255, 255), cv2.BORDER_DEFAULT)

        # 框出图像中的二维码
        text = "{} ({})".format(barcodeData, barcodeType)
        cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
                    .5, (225, 225, 225), 2)
    return image


if __name__ == '__main__':
    # 默认摄像头是0,如果读取不到,改为1试试
    camera = cv2.VideoCapture(1)
    while True:
        # 从摄像头读取当前帧
        ret, frame = camera.read()
        # 转为灰度图像,转递给解码函数
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        im = decodeQrcode(gray)
        cv2.waitKey(5)
        cv2.imshow("camera", im)
        # 设置退出按键,按下q跳出本次循环
        if cv2.waitKey(5) & 0xFF == ord('q'):
            break
    camera.release()
    cv2.destroyAllWindows()