繁体   English   中英

如何在 python 中创建随机二维码

[英]How can I create random QR code in python

我需要编写一个程序,生成随机的黑白方块,看起来像二维码,但我只能使用 tkinter 和随机的。 我正在尝试这样的事情:

def qr():
x = random.randint(1, 21)
canvas.create_rectangle(x * 10, x * 10, x + 10, x + 10, fill = 'black')

但我真的不知道怎么写。 我知道,这对某人来说很容易,但我只是编程的初学者。 它应该是这样的: 二维码

所以谢谢你的每一个回答,祝你有美好的一天。

您可以使用 matplotlib 打印任何矩阵,包括随机矩阵。

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)  # make it reproducible

# random 0s and 1s with equal probability
rnd_matrix = np.random.randint(low=0, high=2, size=(10, 10))

# format the image
fig, ax = plt.subplots()
ax.spines['top'].set_visible(False)  # hide the frame
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
plt.xticks([])  # hide tics and their labels
plt.yticks([])
ax.set_aspect(1)  # make the shape square

# create the image
plt.imshow(rnd_matrix, cmap='Greys')

这会产生一个像

随机 10x10 矩阵作为 bw 图像

这个想法来自另一个 SO answer

使用 Numpy 和 PIL 非常简单:

from PIL import Image
import numpy as np

# Create 21x21 grid of pixels, each being 0 or 255
pixels = np.random.randint(0,2, (21,21), np.uint8) * 255

# Make Numpy array of pixels into PIL Image and save
Image.fromarray(pixels).save('result.png')

在此处输入图像描述

或者,如果您想要更大,请将最后一行更改为:

Image.fromarray(pixels).resize((100,100), resample=Image.NEAREST).save('result.png')

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM