Pawan
Pawan

Reputation: 443

Copying a color image in MATLAB

I want to copy a particular area of image1 to image2. For that I am using the following code.

for i=1:m
    for j=1:n
        if(OD(i,j)==0)
            result(i,j,1)=Original(i,j,1);
            result(i,j,2)=Original(i,j,2);
            result(i,j,3)=Original(i,j,3);
        end
    end
end

This is fine and pretty good.enter image description here Just to reduce the execution time, I tried the following

for i=1:m
    for j=1:n
        if(OD(i,j)==0)
            result(i,j)=Original(i,j);
        end
    end
end

This is giving some unnecessary color on the result image. You can see pink color in this image. enter image description here Also when I try

result(OD==0)=Original;

I am getting the following error.

In an assignment  A(:) = B, the number of elements in A and B must be the same.

But both the result and Original images are of same sizes. I don't understand why this is occurring. Can some one tell me what is the difference between them and why the outputs are like that.

Upvotes: 0

Views: 323

Answers (3)

kkuilla
kkuilla

Reputation: 2256

The reason is because you haven't set all colours (dimensions) to zero.

Why not vectorise it

 [R,C] = find(OD==0); % // Get the coordinates where OD is zero
 result(R,C,:)=Original(R,C,:); % // copy the data over at those coordinates

Timings between the the approach above and the original is below. The timings might look slow but bear in mind that it is not on the fastest computer and should be seen as a relative measure.

+----------+------------+
| Original | Vectorised |
+----------+------------+
| 3.663 s  | 0.246 (s)  |
+----------+------------+

Upvotes: 0

Mr.Cra
Mr.Cra

Reputation: 1

I think one image in Matlab have 3 spaces: R, G, B with (,,1) (,,2) (,,3). Problem of you: result(i,j)=Original(i,j);

Upvotes: 0

Steffen
Steffen

Reputation: 2431

try

result(OD==0)=Original(OD==0);

otherwise you try to copy the whole Original image into a (sub) area of the result image.

Upvotes: 1

Related Questions