janoliver - 7 months ago 18
Python Question

# Generate image data from three numpy arrays

I have three numpy arrays,

`X`
,
`Y`
, and
`Z`
.

`X`
and
`Y`
are coordinates of a spatial grid and each grid point
`(X, Y)`
has an intensity
`Z`
. I would like to save a PNG image using this data. Interpolation is not needed, as
`X`
and
`Y`
are guaranteed to cover each grid point between
`min(X)`
and
`max(Y)`
.

I'm guessing the solution lies within numpy's
`meshgrid()`
function, but I can't figure out how to reshape the
`Z`
array to
`NxM`
intensity data.

How can I do that?

To clarify the input data structure, this is what it looks like:

``````   X   |    Y    |    Z
-----------------------------
0.1    | 0.1     | something..
0.1    | 0.2     | something..
0.1    | 0.3     | something..
...
0.2    | 0.1     | something..
0.2    | 0.2     | something..
0.2    | 0.3     | something..
...

0.2    | 0.1     | something..
0.1    | 0.2     | something..
0.3    | 0.3     | something..
...
``````

You said you needed no interpolation is needed since every grid point is covered. So I assume the points are equally spaced.

If your table is already sorted primary by increasing `x` and secondary by `y` you can simply take the `Z` array directly and save it using `PIL`:

``````import numpy as np
# Find out what shape your final array has (if you already know just hardcode these)
x_values = np.unique(X).size
y_values = np.unique(Y).size
img = np.reshape(Z, (x_values, y_values))

# Maybe you need to cast the dtype to fulfill png restrictions
#img = img.astype(np.uint) # alter it if needed

# Print image
from PIL import Image
Image.fromarray(img).save('filename.png')
``````

If your input isn't sorted (it looks like it is but who knows) you have to sort it before you start. Depending on your input this can be easy or really hard.

Source (Stackoverflow)