0

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 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.