- bitand: https://www.mathworks.com/help/matlab/ref/bitand.html
- imshowpair: https://www.mathworks.com/help/images/ref/imshowpair.html
How to remove least significant bits in a pixel.
22 views (last 30 days)
Show older comments
i read a image
img=imread('lena.jpg');
now i need to remove 3 least significant bits form every pixel of the image, how can i do that?
can anyone please provide a solution.
0 Comments
Answers (2)
Prasanna
on 6 Jun 2025
Hi Niranjan,
It is my understanding you want to remove the 3 least significant bits (LSBs) from every pixel in the image. Each pixel in an 8-bit image has values from 0–255. In binary, this is 8 bits. To remove the 3 LSBs, you essentially set them to 0, keeping only the 5 most significant bits (MSBs). This can be done using bitmasking by keeping a binary mask of 248 and using “bitand(pixelValue, 248)” removes the 3 LSBs.
img = imread('lena.jpg');
% Initialize output image
img_clean = zeros(size(img), 'uint8');
for channel = 1:3
img_clean(:,:,channel) = bitand(img(:,:,channel), 248);
end
imshowpair(img, img_clean, 'montage');
In the above code “bitand(img, 248)” applies a mask to zero out bits 0–2 of each pixel value. For more information, refer to the following documentations:
Hope this helps!
2 Comments
Image Analyst
on 8 Jun 2025
A more general version that is more robust and will work with other than uint8 images and color images is
% Initialize output image
img_clean = zeros(size(img), class(img));
for channel = 1 : size(img, 3) % Works for color as well as gray scale.
img_clean(:, :, channel) = bitand(img(:, :, channel), 248);
end
Walter Roberson
on 8 Jun 2025
That code will not work with float images.
(Mind you, with floating point images, it is a bit questionable as to what "the last three bits" means.
if isa(img, 'integer')
mask = intmax(class(img)) - 7;
img_clean = bitand(img, mask);
elseif isa(img, 'logical')
img_clean = false(size(img));
elseif isa(img, 'single')
img_clean = round(img .* 2^29)./2^29;
elseif isfloat(img)
N = 2+log2(eps(ones(1,class(img))));
img_clean = floor(img .* 2.^(-N)) .* 2.^N;
else
error('unhandled image type: %s', class(img));
end
Image Analyst
on 8 Jun 2025
inputImage = imread('lena.jpg');
% Set last 3 bits to 000.
% Works for both color and gray scale images.
outputImage = bitand(inputImage, 248);
imshowpair(inputImage, outputImage, 'montage');
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!