How to replace pixels with for loops

I'm trying to make a composite of pixels from two photos by using for loops. I want to take the subject of my first photo with a green screen background, and replace the green pixels with pixels from a different photo. Assume the photos are the same size.
Here is the code I have written so far, but I am confused on how to set up an if statement for each pixel in the photo and then replacing it with the given pixel of the background.
foregroundfile = 'elephant.jpg'
backgroundfile = 'moon.jpg'
foreground = imread(foregroundfile);
background = imread(backgroundfile);
Rbackground = background(:,:,1);
Gbackground = background(:,:,2);
Bbackground = background(:,:,3);
Rforeground = foreground(:,:,1);
Gforeground = foreground(:,:,2);
Bforeground = foreground(:,:,3);
sizeDims = size(foreground)
m = sizeDims(1)
n = sizeDims(2)
for i = 1:m
for j = 1:n
if Rforeground <(certain value) && Gforeground > (certain value) && Bforeground < (certain value)

Antworten (1)

Rik
Rik am 11 Dez. 2017

0 Stimmen

  1. create a binary mask that is either true for subject pixels, or true for green screen pixels, the choice doesn't matter much.
  2. use this mask for logical indexing (you can use repmat(mask,1,1,3) to extend your 2D mask to 2D+color)
You can compare an entire matrix in one go, no need for a loop
a=rand(10,1);%random vector
b1=a<0.5;
b2=false(size(a));
for n=1:10
b2(n)= a(n)<0.5;
end
if isequal(b1,b2)
disp('yay, it works')
end

Kategorien

Mehr zu Functions finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 11 Dez. 2017

Beantwortet:

Rik
am 11 Dez. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by