How to remove seven low bits of a grayscale image using OpenCV
Question:
I wrote a script to remove the seven least significant bits and only keep the MBS for each pixel of a gray-scale 8-bit image. To do this, I mask each pixel with 0b10000000
, but am not getting the expected output.
import cv2
import numpy as np
imageSource = 'input.jpg'
original_img = cv2.imread(imageSource,cv2.COLOR_BGR2GRAY)
cv2.imshow( "original", original_img )
result = original_img & 0b10000000
cv2.imshow( "out", result )
cv2.imwrite('out.jpg',result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Answers:
import cv2
import numpy as np
imageSource = 'input.png'
original_img = cv2.imread(imageSource, cv2.CV_LOAD_IMAGE_GRAYSCALE)
cv2.imshow("original", original_img)
result = original_img & 0b10000000
_, result = cv2.threshold(result, 1, 255, cv2.THRESH_BINARY)
cv2.imshow("out", result)
cv2.imwrite('out.jpg', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
What you wanted is binary image(0, 255), so use the threshold function.
So you basically want all values that are:
- greater than 127
(128 = 0b1000000 to 255 = 0b11111111)
to be 255,
- lower or equal 127
(0 = 0b00000000 to 127 = 0b01111111)
to be 0.
You can avoid the binary AND &
, and simply use the threshold
function:
_, result = cv2.threshold(result, 127, 255, cv2.THRESH_BINARY)
I wrote a script to remove the seven least significant bits and only keep the MBS for each pixel of a gray-scale 8-bit image. To do this, I mask each pixel with 0b10000000
, but am not getting the expected output.
import cv2
import numpy as np
imageSource = 'input.jpg'
original_img = cv2.imread(imageSource,cv2.COLOR_BGR2GRAY)
cv2.imshow( "original", original_img )
result = original_img & 0b10000000
cv2.imshow( "out", result )
cv2.imwrite('out.jpg',result)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
imageSource = 'input.png'
original_img = cv2.imread(imageSource, cv2.CV_LOAD_IMAGE_GRAYSCALE)
cv2.imshow("original", original_img)
result = original_img & 0b10000000
_, result = cv2.threshold(result, 1, 255, cv2.THRESH_BINARY)
cv2.imshow("out", result)
cv2.imwrite('out.jpg', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
What you wanted is binary image(0, 255), so use the threshold function.
So you basically want all values that are:
- greater than 127
(128 = 0b1000000 to 255 = 0b11111111)
to be 255, - lower or equal 127
(0 = 0b00000000 to 127 = 0b01111111)
to be 0.
You can avoid the binary AND &
, and simply use the threshold
function:
_, result = cv2.threshold(result, 127, 255, cv2.THRESH_BINARY)