Reputation: 7298
This question is possibly related to storing and retrieving a numpy array in the form of an image. So, I am saving an array of binary values to an image (using scipy.misc.toimage
feature):
import numpy, random, scipy.misc
data = numpy.array([random.randint(0, 1) for i in range(100)]).reshape(100, 1).astype("b")
image = scipy.misc.toimage(data, cmin=0, cmax=1, mode='1')
image.save("arrayimage.png")
Notice that I am saving the data with mode 1
(1-bit pixels, black and white, stored with one pixel per byte). Now, when I try to read it back like:
data = scipy.misc.imread("arrayimage.png")
the resulting data
array comes back as all zeroes.
The question is: is there any other way to retrieve data from the image, with the strict requirement that the image should be created with the mode 1
. Thanks.
Upvotes: 1
Views: 531
Reputation: 207758
I think you want this:
from PIL import Image
import numpy
# Generate boolean data
data=numpy.random.randint(0, 2, size=(100, 1),dtype="bool")
# Convert to PIL image and save as PNG
Image.fromarray(data).convert("1").save("arrayimage.png")
Checking what you get with ImageMagick
identify -verbose arrayimage.png
Sample Output
Image: arrayimage.png
Format: PNG (Portable Network Graphics)
Mime type: image/png
Class: PseudoClass
Geometry: 1x100+0+0
Units: Undefined
Colorspace: Gray
Type: Bilevel <--- Bilevel means boolean
Base type: Undefined
Endianess: Undefined
Depth: 8/1-bit
Channel depth:
Gray: 1-bit
Channel statistics:
Pixels: 100
Gray:
min: 0 (0)
max: 255 (1)
mean: 130.05 (0.51)
standard deviation: 128.117 (0.502418)
kurtosis: -2.01833
skewness: -0.0394094
entropy: 0.999711
Colors: 2
Histogram:
49: ( 0, 0, 0) #000000 gray(0) <--- half the pixels are black
51: (255,255,255) #FFFFFF gray(255) <--- half are white
Colormap entries: 2
Colormap:
0: ( 0, 0, 0,255) #000000FF graya(0,1)
1: (255,255,255,255) #FFFFFFFF graya(255,1)
Upvotes: 2