Numpy & # 8594; PIL int type problem

So, I have the x and y values ​​of the curve that I want to build, like the float values ​​in numpy arrays. Now I want to round them to the nearest int and draw them as pixel values ​​in an empty PIL image. Leaving as I actually fill my vectors x and y, this is what we are 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 

However, this makes no sense to me, since .astype(int) had to turn these puppies into an integer. If I use pix[int(i[0]], int(i[1])] , it works, but thats gross.

Why is my .astype(int) not recognized as int via PIL?

+4
source share
2 answers

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

Try this by converting all numpy.int64 to Python int s:

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

If you're interested in how I understood this, I used the type function for the value from the 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 
+3
source

Not sure what you are doing in the first part of your code, but why don't you replace pix = new_img.load () instead:

 # create blank image new_img = Image.new('L', (500,500)) pix = array(new_img) # create an array with 500 rows and 500 columns 

And then you can follow your source code:

 # 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) 
+2
source

Source: https://habr.com/ru/post/1441406/


All Articles