Using if else statements to change values of pixel in an image

조회 수: 5 (최근 30일)
PenguinForce
PenguinForce 2016년 10월 11일
편집: Adam 2016년 10월 11일
So I am trying to create a function that takes in an image and for every rgb value less than 128, it will change its value to zero, otherwise, it will change its value to 255. However whenever I try using my code, I just get a white, blank image. I am a self taught learner
function newimage = extremecontrast(inimg)
[r,c,l]= size(inimg);
for i = 1:r
for j= 1:c
for k = 1:l
if inimg<128
inimg = 0;
else
inimg = 255;
end
end
end
end
newimage = inimg[i,j,k];
end

채택된 답변

Adam
Adam 2016년 10월 11일
편집: Adam 2016년 10월 11일
I very much doubt you need three nested for loops for this, but
if inimg<128
is not going to do what you want if inimg is an RGB image. I assume you want
if inimg(i,j,k) < 128
and the same for everywhere else you overwrite the whole of your input variable.
Something like
newImage = 255 * round( inimg / 255 );
ought to do the job though instead I think.
  댓글 수: 3
PenguinForce
PenguinForce 2016년 10월 11일
That worked, very interesting way to significantly decrease three fourths of the code. Thank you
Adam
Adam 2016년 10월 11일
편집: Adam 2016년 10월 11일
Yes, that is the power of vectorisation within Matlab (well, other languages too, but I am only really familiar with it in Matlab).
Plus using tricks like knowing that scaling the data down to between 0 and 1 will allow the round function to round the top half of the data range to 1 and the bottom half to 0 to effectively binarise it about the centre point.
It takes a while to get used to using all these kinds of things and I am still very much learning, but it is fun to try to work out neat ways to code these things even if it isn't faster than the longer way (in this case I imagine it should be a lot faster though).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by