Home > Back-end >  how to check if pixel value is increased from 255 in matlab while increasing the brightness of the i
how to check if pixel value is increased from 255 in matlab while increasing the brightness of the i

Time:01-05

i am writing the code of matlab in which i just read the image and then i add 50 on each pixel of the image it works fine and along with it i want to check the pixel value with if statment if pixel value exceed to 255 then this pixel value set to 255. but the if statment not working here is my code

m1 = imread('owl.pgm');
m2  = imread('mecca06.pgm');
for i=1: size(m1,1)
    for j=1: size(m1,2)
        m1(i,j) = m1(i,j) 270;
       if m1(i,j)>=255
            m1(i,j)= 255;
       
            
        end

    end
end
figure
imshow(m1)

CodePudding user response:

You don't need to loop over all pixels, you can use the image as a matrix and simply do something like:

m1 = imread('owl.pgm');
m1 = min(255,m1 50);

Edit: Depending on what datatype im1 has you may need to convert it first to something that can handle the operation you want to do, e.g. an 8-Bit integer allows only numbers upto 255. In that case you may have to convert to a 16-Bit Integer or just a floating point number. You can convert back afterwards:

m1 = imread('owl.pgm');
m1 = double(m1);
m1 = min(255,m1 50);
m1 = uint8(m1);

CodePudding user response:

In MATLAB, integer addition is saturated. That means that, if m1 is uint8 (as it usually is returned from imread), then m1 50 will never be more than 255, if the sum would surpass that value, it would be set to 255 instead.

So, MATLAB automatically does what you wanted to accomplish, you don't need anything special for that.

The code in your post can be replaced by:

m1 = imread('owl.pgm');
m2 = imread('mecca06.pgm');

m1 = m1   270;

figure
imshow(m1)
  • Related