How to remove least significant bits in a pixel.
Afficher commentaires plus anciens
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.
Réponses (2)
Prasanna
le 6 Juin 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:
- bitand: https://www.mathworks.com/help/matlab/ref/bitand.html
- imshowpair: https://www.mathworks.com/help/images/ref/imshowpair.html
Hope this helps!
2 commentaires
Image Analyst
le 8 Juin 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
le 8 Juin 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
le 8 Juin 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');
Catégories
En savoir plus sur Watermarking dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!