Bharath Ram
Bharath Ram

Reputation: 310

Save Numpy array as a 3 channel image while preserving resolution

Essentially my task involves converting a 2-Dimensional temperature field (a 2D matrix) to an image (such that resolution is preserved), then do some image processing on the image and then convert it back to temperature field. For example, if my Temperature field was a grid containing 25x25 cells, my image should be having a resolution of 25x25 pixels.

Also, since my temperature field will have float values, I want the floating values to be preserved in the image and be able to extract the same afterwards.

I tried the following: I have a numpy array that represents some physical field (like Temperature) and I want to convert this to an image for further processing. But while creating the image, matplotlib 's cmap seems to be the only option in python that preserves the resolution.

But when I save the numpy array into colormap, the resulting image seems to be a 4-channel image while I want a 3 channel image.

Is there a way out for my problem?

The code is used was:

import matplotlib as plt
cmap = plt.cm.jet
norm = plt.Normalize(vmin=temp.min(), vmax=temp.max())

# Map the normalized data to colors.  
image = cmap(norm(temp))

# Save the image
plt.imsave('temperature2image.png', image)

# Display the image
plt.pcolor(image)

##### PROCESS THE IMAGE #################

temp_after_processing = plt.imread('processed_image.png')

EDIT: Also, can someone else tell me if there is a way to convert the 3 channel or 4 channel image back to a 2dimensional matrix containing temperature values?

Upvotes: 2

Views: 1923

Answers (1)

gboffi
gboffi

Reputation: 25023

As people told in comments, it's likely the best to to operate on a gray scale image, because the temperature field is exactly that...

The typical format for gray scale images is a floating point array with values comprised between 0 and 1, so you want to input your temperatures,

t0 = np.loadtxt(...) # → t.shape is 25x25

and you want to normalize them (saving the values used in normalization)

m_in = t0.min()
m_ax = t0.max()
t1 = (t0-m_in)/(m_ax-m_in) # → 0 ≤ t1 ≤ 1

process your image

t1 = imageproc(t1)

and convert back from a gray scale image to a temperature field reversing the linear transformation we have applied.

t1 = t1*(m_ax-m_in)+m_in

Of course you can apply a non-linear transform to convert from temperatures to gray levels as long as you can revert the forward transformation.

Upvotes: 1

Related Questions