数据类型错误

1 投票
1 回答
1025 浏览
提问于 2025-04-17 20:15

当我运行这段代码时,我得到了这个输出:

TypeError: an integer is required

我不知道为什么会这样,因为我把这两个数据类型分别设置成了uint8和uint64。显然,我对数据类型的理解还不够。

from PIL import Image

from numpy import random

N = 100

##open an image
im=Image.open('/Users/grahamwarner/Desktop/Experiment/gwarner/labeled_photos/masks/003030.png')

##create a random image
rand_matrix = random.randint(0, 255, (500, 500, 3)).astype('uint8')

rand_image = Image.fromarray(rand_matrix)

##select N random pixels
rand_pix = random.randint(0,499, (N,2)).astype('uint64')

##replace the random values at these pixels with the original values
for ii in range(N):

  rand_image.putpixel(tuple(rand_pix[ii,:]), im.getpixel(tuple(rand_pix[ii,:])))

1 个回答

1

PIL中的getpixel方法对输入要求很严格,特别是它需要一个整数的元组(这和Numpy的uint64类型是不一样的)。下面的代码对我来说是有效的:

for ii in range(N):
    coordinate = tuple(map(int, rand_pix[ii,:]))
    rand_image.putpixel(coordinate, im.getpixel(coordinate))

撰写回答