1

Im using scipy to read a image and extract the RGB array like this

img_b = misc.imread('google.png')
img_b_blue = img_b[:, :, 0]
img_b_blue = img_b_blue.ravel()

Now I need to convert the img_b_blue array to binary and get the most significant bit.

I can convert using map:

img_b_blue_bin = map(bin, img_b_blue)

But it comes as string in the format '0b11110001'. Theres a way to using map and convert to binary without the 'b'? And how can I get the most significant bit?

  • What do you mean with *binary*? Booleans I suppose since the most significant bit is either 0 or 1... – Willem Van Onsem Apr 08 '17 at 20:32
  • Integers are already stored as binary. There's no need to do anything to convert an integer to binary : `0b11110001` is valid Python for `241`, and you can apply bitwise arithmetic directly to the integer. – Eric Duminil Apr 08 '17 at 20:45

1 Answers1

2

You can get the most significant bit by right-shifting 7 bits. The result is an integer array.

img_b_blue_bin = img_b_blue >> 7

Alternatively, probably clearer in your use case, is compare with 128. Higher = white, lower = black. The result is a boolean array.

img_b_blue_bin = img_b_blue >= 128

Similarly, the (n+1)-th least significant bit can be found using (x >> n) & 1, e.g. the 2nd most significant bit:

img_b_blue_2nd_msb = (img_b_blue >> 6) & 1

the least significant bit:

img_b_blue_lsb = img_b_blue & 1

See How am I getting a single bit from an int? for how this works for a single integers.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • Well done. I wanted to post the `>> 7` trick, but you're right that `128` is much clearer. – Eric Duminil Apr 08 '17 at 20:42
  • thank you very much, right-shift 7 bits resolved the problem to get the most significant bit. What about to get the other bits? How can I get the middle and the last bit? – Gustavo Nunes Apr 08 '17 at 20:49