如何根据 Python 中的字符串添加形状?

How to add shapes based on strings in Python?

我正在尝试制作我自己的 QR 码版本,但是对于可以作为数据输入的内容没有那么复杂。我将代码设置为任何人都可以插入最多 8 个 ASCII 字符,代码会将其转换为每个字符的位值字符串。我遇到的麻烦是在 QR 码需要的部分放置黑色方块,在不属于黑色方块的地方放置白色方块。

这是我正在使用的空白二维码模板:

这就是我的代码现在的样子:

import numpy as np
import cv2
def show(img,wait=0,destroy=True):
    img=np.uint8(img)
    cv2.imshow("image",img)
    cv2.waitKey(wait)
    if destroy:
        cv2.destroyAllWindows()

def data2bits(data):
    bits=""
    for i in range(len(data)):
        binary=str(bin(ord(data[i])))
        binary=binary.replace("0b","0")
        binary=binary.zfill(8)
        bits+=binary

    bits=bits.ljust(64,'0')
    print("\nThese are the bits of the data you put in:\n"+str(bits)+"\n")
    return bits
    
def bits2pixels(bits,qrCode):
    for i in range(150,412):
        for j in range(150,412):
            for k in range(0,len(bits)):
                if (bits[k]=="1"):
                    cv2.rectangle(qrCode,(i,j),(i+38,j+38),(0,0,0),-1)
                elif (bits[k]=="0"):
                    cv2.rectangle(qrCode,(i,j),(i+3,j+3),(255,255,255),-1)
    show(qrCode)


qrCode=cv2.imread("scan.png",0)
data=input("Put in the data you want and you will get the binary output for the first 8 characters.\nIf the data put in is less than 8 characters long, the bits will be filled up\nbut will be removed when the data is recompiled.\nType in your data: ")
data=data[:8]
bits=data2bits(data)
bits2pixels(bits,qrCode)

目前,代码可以接收数据,将其转换为位,并且应该在需要的地方放置方块。例如,如果我有以下位“10010101”,我想将它们转换为以下 black/white 形状序列“BWWBWBWB”。但是如果我运行当前的代码,如果最后一位是1,我为可扫描数据指定的整个部分变成黑色,如果最后一位是0则相反。

我应该对我的代码进行哪些更改,以便有一个 8 x 8 的数据部分?感谢所有帮助。

But if I run the code as it is currently, If the last bit is a 1, the whole section I have designated for scannable data turns black, and the opposite is true if the last bit is 0.

内部循环 - for k in range(0,len(bits)): 迭代所有位,并在最后一次迭代时有效地将最后一位分配给单元格;然后你的其他循环移动到另一个单元格并做同样的事情。

我通过迭代位并在每次迭代中推进像素位置来重构。 bits2pixels 中的外循环递增 1,所以我会保留它。

def bits2pixels(bits,qrCode):
    i,j = 150,150
    step = 1
    for bit in bits:
        if (bit=="1"):
            dim = 38
            color = (0,0,0)
        elif (bit=="0"):
            dim = 3
            color = (1,1,1)
        cv2.rectangle(qrCode,(i,j),(i+dim,j+dim),color,-1)
        i += step
        j += step
    show(qrCode)

我不确定我是否抓住了您的意图 - 形状最终在对角线上。它们都运行在一起,因为形状比台阶大。


也许这更接近。 shape 的 40x40 个位置;形状从左到右从上到下放置。

def bits2pixels(bits,qrCode):
    i,j = 150,150
    step = 40
    for bit in bits:
        if (bit=="1"):
            dim = 38
            color = (0,0,0)
        elif (bit=="0"):
            dim = 3
            color = (1,1,1)
        cv2.rectangle(qrCode,(i,j),(i+dim,j+dim),color,-1)
        i += step
        if i >= 412:
            i = 150
            j += step
            if j >= 412:
                break
        # j += step
    show(qrCode)