LOTS of errors in that. Mostly due to not computing x1,x2,y1,y2 correctly using the rect variable, which is [x, y, width, height], NOT [x1,x2,y1,y2]. Then you didn't use the third index, needed because they are color images not gray scale images. Finally, you reversed x and y in the indexing. Remember arrays index as array(y, x), NOT array(x,y) because the row/y/vertical value is always the first index, not the colulmn/x/horizontal value.
Fixed code is below:
image1=imread('office_1.jpg');
subplot(2, 1, 1);
imshow(image1);
title('Image1', 'FontSize', 20);
image2=imread('office_5.jpg');
subplot(2, 1, 2);
imshow(image2);
title('Image2', 'FontSize', 20);
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
drawnow;
uiwait(helpdlg('Draw out a rectangle over the bottom Image2.'));
rect = getrect;
x1 =rect(1)
x2 = x1 + rect(3)
y1 =rect(2)
y2 = y1 + rect(4)
Z = image1;
Z(y1:y2, x1:x2, :) = image2(y1:y2, x1:x2, :);
imshow(Z)
title('Z', 'FontSize', 20);
Best Answer