How to change the gray level of a 8-bit gray level image to 7, 6, 5-bit gray level image using for loops?

59 views (last 30 days)
Hello all,
Below is my code. So if I perform the operations outside of the nested for loop (meaning as a simple script where I input each value individually) I get the correct values for the pixels in the outImage. However, when I try to compute it within the nested for loop, the program doesn't stop executing, and when I click pause, it doesn't throw an error, rather it opens a new script with some chunk of code.
Does anybody have any idea of what do? I thought this would work.
Best,
close all;
clear;
clc;
% read the input image as input image
inImage = imread('rose_copy.jpg');
% get the shape of the image
[row,col] = size(inImage);
outImage = zeros(row,col);
n = 6; % the number of bits for the grayscale. Say I want it from 8-bit to 6-bit in this case
for y = 1:1:row
for x = 1:1:col
pixel = uint8(inImage(y,x));
mask = uint8(256 - power(2,(8 - n)));
pixel2 = uint8(bitand(pixel,mask));
fin = bitsra(pixel2,8 - n);
outImage(y,x) = uint8(fin);
end
end
outImage = uint8(outImage);
imwrite(outImage,'Grayscale.jpg','jpg');

Answers (1)

Image Analyst
Image Analyst on 26 Jan 2021
To seqentially reduce the number of "used" bits in an 8 bit image you'd do
for k = 1 : 7
grayImage = grayImage / 2;
end
  8 Comments
Walter Roberson
Walter Roberson on 28 Jan 2021
binary is not a bad way to approach it. You would probably get more accurate answers than successive division by 2, because in MATLAB divivision of uint8 rounds
x = uint8(1:10);
N = 2;
dec2bin(x)
ans = 10x4 char array
'0001' '0010' '0011' '0100' '0101' '0110' '0111' '1000' '1001' '1010'
uint8(x)/2^N*2^N
ans = 1×10
0 4 4 4 4 8 8 8 8 12
uint8(round(double(x)/2^N)*2^N)
ans = 1×10
0 4 4 4 4 8 8 8 8 12
bitand(x, 255-2^N+1)
ans = 1×10
0 0 0 4 4 4 4 8 8 8
uint8(floor(double(x)/2^N)*2^N)
ans = 1×10
0 0 0 4 4 4 4 8 8 8
Jorge Vera Garcia
Jorge Vera Garcia on 28 Jan 2021
Thanks for the response. I actually implemented an alternative way that works perfectly.
Have a good rest of your day!

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!