-1

如果我想让一个数组填充01取决于图像中的像素值,我写这个:

image = "example.jpg"
imageOpen = Image.open(image)
bwImage = imageOpen.convert("1", dither=Image.NONE)
bw_np = numpy.asarray(bwImage)
print(type(bw_np[0, 0]))

结果 :

<class 'numpy.bool_'>

由于.convert双层模式"1",数组必须充满1and 0https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.convert

当我尝试更简单的事情时:

bw_np = numpy.asarray([0, 1])
print(type(bw_np[0]))

结果 :

<class 'numpy.int32'>

但不是第二个例子,第一个例子充满了trueand false。所以为什么 ?

4

1 回答 1

1

简而言之:在 pythonTrue中 is1Falseis 0。这应该纠正这种奇怪的行为:

bw_np = numpy.asarray(bwImage, dtype=int)

长答案:也许imageOpen.convert("1", dither=Image.NONE)更喜欢 bool 而不是 int32 以获得更好的内存管理:

import sys
import numpy

print("Size of numpy.bool_() :", sys.getsizeof(numpy.bool_()))
print("Size of numpy.int32() :", sys.getsizeof(numpy.int32()))

结果 :

Size of numpy.bool_() : 13
Size of numpy.int32() : 16
于 2018-06-12T16:50:41.803 回答