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)

답변 (1개)

Rik
Rik 2017년 12월 11일

0 개 추천

  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

카테고리

도움말 센터File Exchange에서 Functions에 대해 자세히 알아보기

질문:

2017년 12월 11일

답변:

Rik
2017년 12월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by