【问题标题】:Why numpy.asarray return an array full of boolean为什么 numpy.asarray 返回一个充满布尔值的数组
【发布时间】:2018-11-22 03:22:35
【问题描述】:

如果我想根据图像中的像素值填充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。 那为什么呢?

【问题讨论】:

    标签: python numpy types numpy-dtype


    【解决方案1】:

    简而言之:在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
    

    【讨论】:

      猜你喜欢
      • 2014-03-20
      • 2017-08-27
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      相关资源
      最近更新 更多