numpy - > PIL int类型问题 [英] numpy-->PIL int type issue

查看:175
本文介绍了numpy - > PIL int类型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我得到了一条曲线的x和y值,我希望将其绘制为numpy数组中的浮点值。现在,我想将它们舍入到最近的int,并将它们绘制为空PIL图像中的像素值。
离开我实际上如何填充我的x和y向量,这是我们正在使用的:

So I've got the x and y values of a curve that I want to plot held as float values in numpy arrays. Now, I want to round them to the nearest int, and plot them as pixel values in an empty PIL image. Leaving out how I actually fill my x and y vectors, here is what we're working with:

# 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  

这给了我一条错误消息:

This gives me an error message:

  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])] 它可以工作,但这很糟糕。

However, this makes no sense to me since the .astype(int) should have cast these puppies to an integer. If I use pix[int(i[0]], int(i[1])] it works, but that's gross.

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

Why isn't my .astype(int) being recognized as int by PIL?

推荐答案

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

I think the problem is that your numpy arrays have type numpy.int64 or something similar, which PIL does not understand as an int that it can use to index into the image.

试试这个,转换所有 numpy.int64 s到Python int s:

Try this, which converts all the numpy.int64s to 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))

如果你想知道我是怎么想出来的,我用的是输入来自numpy数组的值的函数:

In case you're wondering how I figured this out, I used the type function on a value from a numpy array:

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

这篇关于numpy - > PIL int类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆