rowana
rowana

Reputation: 748

Copy an image to a bigger image

I want to copy a sub image to a bigger image. Say I have image1 and image2 where image2 has size 600x300 and image1 has size 200x100. I want to copy image1 on to image2, while the rest of image2 remains. I have tried something like this -

`back_img = zeros(round(boundary_y),round(boundary_x),3);
back_img = back_img(:,:,:);

[src_y, src_x,~] = size(img1);
back_img(1:src_y, 1:src_x,1:3) = img1(1:src_y, 1:src_x,1:3);
figure; imshow(back_img);`

I have a black background on top of which I want to paste my image. I'm getting a white box where my image has to be there as my result. What am I missing?

Thanks!

Upvotes: 0

Views: 110

Answers (3)

Rotem
Rotem

Reputation: 32104

Main problem: back_img is of class double and img1 is of class uint8.
Show image of class double displays all pixels above 1 as white pixels.
In uint8 class, pixel range is [0, 255], when 255 is white.

Following code: back_img(1:src_y, 1:src_x,1:3) = img1(1:src_y, 1:src_x,1:3);, place the uint8 matrix in matrix of class (type) double.
In this case, Matlab rule is casting uint8 elements to double.
Using imshow(back_img) when back_img is double, applies pixels range [0, 1] (0 is black, and 1 is white).
Pixels above 1 are also white.
Almost all pixels of original uint8 image are 1 or above, so displyead as white pixels after converting to double.

Solution: Create the zero matrix in the same class as img1 (class uint8 in your case).

Check the following code sample:

%Prepeare 200x200 image for the example:
img1 = imresize(imread('peppers.png'), [200, 200]);

boundary_x = 600;
boundary_y = 600;

%back_img = zeros(round(boundary_y),round(boundary_x),3);
%back_img = back_img(:,:,:); %Do nothing...

%Create 600x600x3 zeros matrix in smae class of img1 (in case img1 is
%uint8, class of back_img is uint8 instead of double.
back_img = zeros(round(boundary_y),round(boundary_x),3, class(img1));

[src_y, src_x, ~] = size(img1);
back_img(1:src_y, 1:src_x,1:3) = img1(1:src_y, 1:src_x,1:3);
figure; imshow(back_img);

Result:
enter image description here

Result of original code:
enter image description here

Upvotes: 2

rowana
rowana

Reputation: 748

The problem with the above code is the zeros in the background image were doubles, converting them into integers (uint8) will fix it.

Upvotes: 0

Ahmet Cecen
Ahmet Cecen

Reputation: 142

Many confusing things here, but I think the core problem is

back_img(1:src_y, 1:src_x,1:3) = img1(1:src_y, 1:src_x,1:3);

Do instead

back_img(1:src_y, 1:src_x,1:3) = img1;

An easier way to achieve black padding is:

padarray(A,padsize,padval,direction)

Upvotes: -1

Related Questions