4

因此,我将要绘制的曲线的 x 和 y 值作为浮点值保存在 numpy 数组中。现在,我想将它们四舍五入到最接近的 int,并将它们绘制为空 PIL 图像中的像素值。省略我实际填充 x 和 y 向量的方式,以下是我们正在使用的内容:

# create blank image    
new_img = Image.new('L', (500,500))    
pix = new_img.load()

# round to int and convert to int    
xx = np.rint(x).astype(int)    
yy = np.rint(y).astype(int)

ordered_pairs = set(zip(xx, yy))

for i in ordered_pairs:    
    pix[i[0], i[1]] = 255  

这给了我一条错误消息:

  File "makeCurves.py", line 105, in makeCurve
    pix[i[0], i[1]] = 255        
TypeError: an integer is required

但是,这对我来说毫无意义,因为.astype(int)应该将这些小狗转换为整数。如果我使用pix[int(i[0]], int(i[1])]它可以工作,但这很糟糕。

为什么我.astype(int)没有被 PIL 识别为 int?

4

2 回答 2

3

我认为问题在于您的 numpy 数组具有类型numpy.int64或类似的东西,PIL 不理解int它可以用来索引图像。

试试这个,它将所有numpy.int64s 转换为 Python ints:

# round to int and convert to int    
xx = map(int, np.rint(x).astype(int)) 
yy = map(int, np.rint(y).astype(int))

如果您想知道我是如何得出这个结论的,我type在 numpy 数组中的一个值上使用了该函数:

>>> a = np.array([[1.3, 403.2], [1.0, 0.3]])
>>> b = np.rint(a).astype(int)
>>> b.dtype
 dtype('int64')
>>> type(b[0, 0])
 numpy.int64
>>> type(int(b[0, 0]))
 int
于 2012-10-22T23:27:05.030 回答
2

不确定您在代码的第一部分中要做什么,但是为什么不使用此替换 pix = new_img.load() :

# create blank image    
new_img = Image.new('L', (500,500))

pix = array(new_img) # create an array with 500 rows and 500 columns

然后你可以按照你的原始代码:

# round to int and convert to int    
xx = np.rint(x).astype(int)    
yy = np.rint(y).astype(int)

ordered_pairs = set(zip(xx, yy))

for i in ordered_pairs:    
    pix[i[0], i[1]] = 255 

Out[23]: 
array([[  0,   0,   0, ...,   0,   0,   0],
       [  0, 255,   0, ...,   0,   0,   0],
       [  0,   0,   0, ...,   0,   0,   0],
       ..., 
       [  0,   0,   0, ...,   0,   0,   0],
       [  0,   0,   0, ...,   0,   0,   0],
       [  0,   0,   0, ...,   0,   0,   0]], dtype=uint8)
于 2012-10-22T23:17:43.630 回答