youknowwho
youknowwho

Reputation: 33

Make 8 images using each bit of each pixel of an image

so I have a 512x512 grayscale image and I want to use each bit of the pixels of the image to make 8 different black and white images, each one with the respective bits. To achieve this I'm using the opencv library. The grayscale image x_img_g is represented by a matrix:

[[162 162 162 ... 170 155 128]
[162 162 162 ... 170 155 128]
[162 162 162 ... 170 155 128]
...
[ 43  43  50 ... 104 100  98]
[ 44  44  55 ... 104 105 108]
[ 44  44  55 ... 104 105 108]]

You can see the image here

I think I managed to make the image with the most significant bit which I made like this:

def makeImages():
    y = x_img_g>128
    cv2.imshow('BW',np.uint8(y*255))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Which makes this image

But I'm having trouble making the other images so I would really aprecciate any help.

Oh and if anyone can explain this also, I would like aswell to make an image with only the 4 most significant bits of the x_img_g

Upvotes: 2

Views: 179

Answers (1)

Divakar
Divakar

Reputation: 221564

Extend to 3D with a new axis at the end and use np.unpackbits along the same -

np.unpackbits(a[...,None], axis=-1) # a is input array

Sample run -

In [145]: np.random.seed(0)

In [146]: a = np.random.randint(0,256,(2,3),dtype=np.uint8)

In [147]: a
Out[147]: 
array([[172,  10, 127],
       [140,  47, 170]], dtype=uint8)

In [149]: out = np.unpackbits(a[...,None], axis=-1)

In [150]: out
Out[150]: 
array([[[1, 0, 1, 0, 1, 1, 0, 0],
        [0, 0, 0, 0, 1, 0, 1, 0],
        [0, 1, 1, 1, 1, 1, 1, 1]],

       [[1, 0, 0, 0, 1, 1, 0, 0],
        [0, 0, 1, 0, 1, 1, 1, 1],
        [1, 0, 1, 0, 1, 0, 1, 0]]], dtype=uint8)

Hence, out[...,0] would be the binary image with the least significant bit and so on until out[...,7] as the one with the most significant bit.

Alternatively, putting it in another way, we could extend with a new axis along the first axis -

out = np.unpackbits(a[None], axis=0)

Hence, out[0] would be the binary image with the least significant bit and so on until out[7] as the one with the most significant bit.

Upvotes: 1

Related Questions