Why numpy.asarray return an array full of boolean

江枫思渺然 提交于 2020-01-06 05:24:05

问题


If I want to have an array filled whith 0 or 1 depending of the pixels value in a image, I write this :

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]))

Result :

<class 'numpy.bool_'>

Because of the .convert bilevel mode "1", the array must be full of 1 and 0. https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.convert

When I try something simpler :

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

Result :

<class 'numpy.int32'>

But instead of the second example, the first is full of true and false. So Why ?


回答1:


In a nutshell : In python True is 1 and False is 0. This should correct this weird behavior :

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

Long answer : Maybe imageOpen.convert("1", dither=Image.NONE) prefer bool instead of int32 for a better memory management :

import sys
import numpy

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

Result :

Size of numpy.bool_() : 13
Size of numpy.int32() : 16


来源:https://stackoverflow.com/questions/50822068/why-numpy-asarray-return-an-array-full-of-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!