dumb_coder
dumb_coder

Reputation: 325

convert 8 bit binary vector to 1 grayscale pixel

I am having binary vector of size 8 ie 8 bit vector of 1 and 0. How can I convert 8 bit vector to 1 bit grayscale pixel in python?

Upvotes: 1

Views: 1167

Answers (1)

Lanting
Lanting

Reputation: 3068

v = numpy.array([1,0,1,0,1,0,1,0])
g = numpy.sum(2**numpy.arange(8)*v)

For each bit we determine its weight by taking 2^0, 2^1 etc. we then take the product of the weight vector with our bit vector, and sum the values.

This assumes the first bit to be the least significant one, by reversing the range it could be the other way around:

g = numpy.sum(2**numpy.arange(7,-1,-1)*v)

both of these give you a greyscale value in the range 0-255. If you'd like to make this 1 bit, you could threshold it:

g = 1 if (numpy.sum(2**numpy.arange(7,-1,-1)*v) > 127) else 0

Upvotes: 3

Related Questions