Reputation: 503
I have a image data, How can I separate it into x, y and the value?
image data
[[38 0 0 ... 0 0 0]
[46 3 0 ... 0 0 0]
[46 3 0 ... 0 0 0]
...
[74 0 0 ... 0 0 0]
[74 0 0 ... 0 0 0]
[74 0 0 ... 0 0 0]]
and their should it be?
x = 0, y = 0, value = 38
x = 0, y = 1, value = 46
...
How can I separate it in to :
x = []
y = []
value = []
only for
loop method is work?
Thanks for any help
Upvotes: 2
Views: 2384
Reputation: 51395
IIUC, I think you can use np.indices
. Take your example:
>>> img
array([[38, 0, 0, 0, 0, 0],
[46, 3, 0, 0, 0, 0],
[46, 3, 0, 0, 0, 0],
[74, 0, 0, 0, 0, 0],
[74, 0, 0, 0, 0, 0],
[74, 0, 0, 0, 0, 0]])
value = img.flatten()
y,x = np.indices(img.shape).reshape(-1,len(value))
>>> x
array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5])
>>> y
array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,
3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5])
>>> value
array([38, 0, 0, 0, 0, 0, 46, 3, 0, 0, 0, 0, 46, 3, 0, 0, 0,
0, 74, 0, 0, 0, 0, 0, 74, 0, 0, 0, 0, 0, 74, 0, 0, 0,
0, 0])
So where x
is 0 and y
is 0, you get value
38, where x
is 0 and y
is 1, you get value
46, and so on.
Edit: In your comment, you said you want to filter out the zeros. You can do this with np.where
and np.nonzero
:
y,x = np.where(img)
value = img[np.nonzero(img)]
>>> y
array([0, 1, 1, 2, 2, 3, 4, 5])
>>> x
array([0, 0, 1, 0, 1, 0, 0, 0])
>>> value
array([38, 46, 3, 46, 3, 74, 74, 74])
Upvotes: 4
Reputation: 912
if your image is colored, it's often in RGB format(3 channels), if it's grayscale, it will have 1 channel.
So the shape of the array will be (img_height, img_width, number_of_channels)
By understanding the shape, you can properly use the imread
from PIL
or imread
from matplotlib
to load the image, and then turn them to array using myarray = numpy.array(your_loaded_img)
. As it's a numpy array, you can call the cell values by myarray[x,y]
Upvotes: 0