簡體   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