为什么?numpy.asarray公司返回一个充满布尔值的数组

2024-06-15 00:37:56 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我想根据图像中的像素值,用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",数组中必须充满10https://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'>

但是与第二个例子不同,第一个例子充满了truefalse。 那为什么呢?你知道吗


Tags: 图像imagenumpyconverttypenp数组class
1条回答
网友
1楼 · 发布于 2024-06-15 00:37:56

简而言之:在python中True1False0。这应该可以纠正这种奇怪的行为:

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

相关问题 更多 >