Reputation: 185
I am finding a point within a numpy array and then want to save this array as an image with a box around the located point.
Below is a simplified code representation showing the issue
from PIL import Image, ImageDraw
import numpy as np
np_img = np.zeros((259,339,3))
pt = (29,118)
np_img[pt] = [255,0,0]
print(np_img[pt])
final_img = Image.fromarray(np_img, 'RGB')
#final_draw = ImageDraw.Draw(final_img)
#final_draw.rectangle([(pt[1]-3, pt[0]+3), (pt[1]+3, pt[0]-3)], outline="blue")
new_np_img = np.asarray(final_img)
print(new_np_img[pt])
new_pt = np.where(new_np_img > 0)
print(new_pt)
final_img.show()
I would expect that if I read the generated PIL image back into a numpy array that the point that I set as [255,0,0] would still be that value but it is not. What is PIL doing to my data so that I can understand how I need to condition my numpy array so that it displays the correct position of my point in the PIL image?
Upvotes: 0
Views: 425
Reputation: 1850
The reason for undesired output is because you didn't explicitly defined the datatype of the numpy array as uint8
. In your code, the first array (np_img) was stored as float64
datatype. And the array obtained from PIL
(final_img) was of the datatype uint8
. Which caused inconsistent results.
from PIL import Image
import numpy as np
np_img = np.zeros((259,339,3), np.uint8)
pt = (29,118)
np_img[pt] = [255,0,0]
print(np_img[pt])
final_img = Image.fromarray(np_img, 'RGB')
new_np_img = np.asarray(final_img)
print(new_np_img[pt])
final_img.show()
Output:-
[255 0 0]
[255 0 0]
Output Image:-
Upvotes: 2