Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create image from numpy float32 array?

I have a numpy.ndarray array which contains values of float32. The images should be dimensions 226×226. I tried to use PIL.Image to create the image but I got an error. I read that PIL.Image.fromarray require an object and mode, and for float I need to call fromarray with 'F' as I tried.

This is what I tried to do:

from PIL import Image
img = Image.fromarray(slice56, mode='F')
#type(slice56) = <type 'numpy.ndarray'>
#slice56 = array([ 0.,  0.,  0., ...,  0.,  0.,  0.], dtype=float32)

and I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1860, in fromarray
    return frombuffer(mode, size, obj, "raw", mode, 0, 1)
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1805, in frombuffer
    return apply(fromstring, (mode, size, data, decoder_name, args))
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1743, in fromstring
    im = new(mode, size)
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1710, in new
    return Image()._new(core.fill(mode, size, color))
TypeError: argument 2 must be sequence of length 2, not 1

Can anyone suggest an idea how to do it? Or how to solve this error?

like image 799
Idan.c Avatar asked Aug 10 '16 08:08

Idan.c


People also ask

How do I save a float32 image?

First, you need to check values of the output data. If it is float, but belongs to 0.. 255, you just cast from float32 to uint8 and save it!


Video Answer


2 Answers

I would agree with DavidG's answer being a quick solution to plot an image from a numpy array. However, if you have a very good reason for sticking with PIL.Image, the closest approach to what you've already done would be something like this:

from PIL import Image
import numpy as np

slice56 = np.random.random((226, 226))

# convert values to 0 - 255 int8 format
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.show()

It will then produce something like below given random numbers:

PIL Image

like image 115
jtitusj Avatar answered Oct 04 '22 20:10

jtitusj


scipy.misc is my favorite way of doing it. It's cleaner and it is done in just one line. Look how nice it is:

import scipy.misc
img = scipy.misc.toimage(slice56, mode='L')

Please check here for the official docs.

like image 24
NKSHELL Avatar answered Oct 04 '22 20:10

NKSHELL