在Python中处理图像时元组索引超出范围

2024-09-24 00:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个class头:

class Header:
    MAX_FORMAT_LENGTH=8
    magicnum = "hide" #str
    size = 0
    fformat = "txt" 

有一个功能,可以对图像中的像素进行编码:

^{pr2}$

在命令行中输入正确的arg之后,在构建时,我有一个错误,它说:

a = pixel[3]&3

IndexError: tuple index out of range

我试着输入不同种类的图像,比如:png,jpg,jpeg等等。 因为我想检查A 4-channel pixel,因为我可能会弄错图像。但不,我也有同样的错误。在

我想展示我的编码过程是怎样的,除了encode_in_pixel(),我有一个函数,它调用encode_in_pixel

def encode(image, data, filename, encryption=False, password=""):
    im = Image.open(image)
    px = im.load()

    #Create a header
    header = Header()
    header.size = len(data)
    header.fformat = "" if (len(filename.split(os.extsep))<2)\
                     else filename.split(os.extsep)[1]

    #Add the header to the file data
    headerdata = struct.pack("4s"+\
                             "I"+\
                             str(Header.MAX_FORMAT_LENGTH)+"s",\
                             header.magicnum, header.size, header.fformat)
    filebytes = headerdata + data

    #Optional encryption step
    if encrypt:
        if password:
            filebytes = encrypt(filebytes, password,\
                                padding=im.width*im.height - len(filebytes))
        else:
            print "Password is empty, encryption skipped"

    #Ensure the image is large enough to hide the data
    if len(filebytes) > im.width*im.height:
        print "Image too small to encode the file. \
You can store 1 byte per pixel."
        exit()

    for i in range(len(filebytes)):
        coords = (i%im.width, i/im.width)

        byte = ord(filebytes[i])

        px[coords[0], coords[1]] = encode_in_pixel(byte, px[coords[0], coords[1]]) 
#here i'm trying to call function , where I have an error

    im.save("output.png", "PNG")

我可以在给定的参数中出错,但如果是,我应该如何给出它们?在


Tags: thetoindatasizelenifcoords