noclue123
noclue123

Reputation: 115

Access single image-pixel, matlab

i want to change every single pixel, so it's "255 - pixel". i want to do it in for-loop (!).

my code till now:

for n=1:1:512 %it's a 512x512 image
     picture = 255 - picture;
end

but i don't know how to change single pixel by single pixel in the image.

so what do I need to change "picture" to in my code?

sorry for poor english. also i'm a total newbie.

thanks for help

Upvotes: 0

Views: 85

Answers (2)

Yuval
Yuval

Reputation: 3433

If you insist on using a for-loop, to calculate the complement to a number for each element of a general array:

for n=1:numel(picture)
  picture(n) = 255 - picture(n);
end

Or, if you need a nested loop for a two-dimensional array:

for n=1:size(picture,1)
  for m=1:size(picture,2)
    picture(n,m) = 255 - picture(n,m);
  end
end

However, this is really abuse of Matlab. A big part of why one would want to use Matlab is exactly to avoid for-loops such as these. Instead, you should simply:

picture = 255 - picture

Upvotes: 4

Kape
Kape

Reputation: 195

I would recommend not using any for loop if you want to change the whole picture. Just:

picture = 255 - picture;

Matlab is faster if it does not have to work in loops;

If you need to modify it in for loop and the picture is typical RGB format the picture size is 512x512x3

for a=1:512
    for b=1:512
       for c=1:3
           picture(a,b,c) = 255 - picture(a,b,c); 
       end
    end
end

Upvotes: 2

Related Questions