此问题可能与以图像形式存储和检索numpy数组有关。因此,我正在将二进制值数组保存到图像中(使用scipy.misc.toimage
功能):
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")
请注意,我正在使用模式1
(1位像素,黑白,每字节存储一个像素)保存数据。现在,当我尝试像这样读回它时:
data = scipy.misc.imread("arrayimage.png")
生成的data
数组返回为全零。
问题是:还有其他方法可以从图像检索数据,严格要求应使用1
模式创建图像。谢谢。
答案 0 :(得分:2)
我想你想要这个:
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")
检查使用 ImageMagick
会得到什么identify -verbose arrayimage.png
示例输出
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)