How would I paste a cropped image onto a blank image of different size?

2 views (last 30 days)
I created a blank image with a yellow background that is 200x200 pixel and also cropped 150x150 pixel image from another image. How would I go about pasting the the cropped 150x150 image onto the 200x200 image?
I tried to use pastedimg=combine(blankimg, croppedimg), which did not work and gave me the following error: "Subscripted assignment dimension mismatch".
Thank you in advancee for any help you can provide.

Accepted Answer

Image Analyst
Image Analyst on 30 Mar 2013
Here's the second one of my copy and paste images demo. This one lets you select a box from the source image, and a destination on the destination image and it pastes it onto that location.
% Lets user drag out a box on an image, then define where they want to paste it.
% Then it pastes the drawn region onto the original image.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
format compact;
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'eight.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(grayImage);
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(grayImage);
axis on;
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Let's compute and display the histogram, just for fun.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
grid on;
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
% Ask user to draw a box.
subplot(2, 2, 1);
promptMessage = sprintf('Drag out a box that you want to copy,\nor Cancel to abort processing?');
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, 'Continue', 'Cancel', 'Continue');
if strcmpi(button, 'Cancel')
return;
end
k = waitforbuttonpress;
point1 = get(gca,'CurrentPoint'); % button down detected
finalRect = rbbox; % return figure units
point2 = get(gca,'CurrentPoint'); % button up detected
point1 = point1(1,1:2); % extract x and y
point2 = point2(1,1:2);
p1 = min(point1,point2); % calculate locations
offset = abs(point1-point2); % and dimensions
% Find the coordinates of the box.
xCoords = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)];
yCoords = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)];
x1 = round(xCoords(1));
x2 = round(xCoords(2));
y1 = round(yCoords(5));
y2 = round(yCoords(3));
hold on
axis manual
plot(xCoords, yCoords, 'b-'); % redraw in dataspace units
% Display the cropped image.
croppedImage = grayImage(y1:y2,x1:x2);
subplot(2, 2, 3);
imshow(croppedImage);
axis on;
title('Region that you defined', 'FontSize', fontSize);
% Paste it onto the original image
[rows2 columns2] = size(croppedImage)
promptMessage = sprintf('Click on the upper left point where you want to paste it,\nor Cancel to abort processing?');
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, 'Continue', 'Cancel', 'Continue');
if strcmpi(button, 'Cancel')
return;
end
[x, y] = ginput(1)
% Determine the pasting boundaries.
r1 = int32(y);
c1 = int32(x);
r2 = r1 + rows2 - 1;
r2 = min([r2 rows]);
c2 = c1 + columns2 - 1;
c2 = min([c2, columns]);
plot([c1 c2 c2 c1 c1], [r1 r1 r2 r2 r1], 'r-');
% Paste as much of croppedImage as will fit into the original image.
grayImage(r1:r2, c1:c2) = croppedImage(1:(r2-r1+1), 1:(c2-c1+1));
subplot(2, 2, 4);
imshow(grayImage);
axis on;
title('Region that you defined pasted onto original', 'FontSize', fontSize);
  13 Comments
Image Analyst
Image Analyst on 1 Apr 2013
Edited: Image Analyst on 1 Apr 2013
I didn't scroll over that far enough to see it. Besides I can't copy and paste from an image into the code editor. Edit your post, put a blank line in front of the code, highlight the code and click the {}Code icon so that it will look properly formatted. thanks. I fixed your code by avoiding floating point arrays and sticking to all uint8 arrays:
clc; % Clear the command window.
clearvars;
workspace; % Make sure the workspace panel is showing.
format longg;
format compact;
fontSize = 20;
% Create yellow canvass
rows = 200;
columns = 200;
% Make uint8 image not floating point.
A1 = 255 * ones(200,200,3, 'uint8');
A1(:,:,3) = 0;
subplot(2,2,1);
imshow(A1);
axis on;
title('A1 Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Read in original image.
A2=imread('peppers.png');
subplot(2,2,2);
imshow(A2);
axis on;
title('Original Color Image', 'FontSize', fontSize);
% Crop out a portion of it.
A3=imcrop(A2,[0 0 150 150]);
subplot(2,2,3);
imshow(A3);
axis on;
title('A3 Image', 'FontSize', fontSize);
% Paste cropped image onto canvass image.
A4(1:1+150-1,1:1+150-1,:)=A3;
% Display result.
subplot(2,2,4);
imshow(A4);
axis on;
title('A4 Image', 'FontSize', fontSize);
integra-t
integra-t on 2 Apr 2013
Edited: integra-t on 2 Apr 2013
It was just a matter of making sure all of the images were of uint8 format. I simplified your commands above since I have to show each step of my work to my professor. Just wanted to point one thing out that you seem to have missed in your code is A4=A1; which caused A3 Image to look exactly like A4 Image missing the yellow background.
Thank you again for all your help!
A1=255*ones(200,200,3, 'uint8');
A1(:,:,3)=0;
imshow(A1);
A2=imread('peppers.png');
figure, imshow(A2);
A3=imcrop(A2,[0 0 150 150]);
figure, imshow(A3);
A4=A1;
A4(1:1+150-1,1:1+150-1,:)=A3;
figure, imshow(A4);

Sign in to comment.

More Answers (3)

Walter Roberson
Walter Roberson on 30 Mar 2013
Edited: Walter Roberson on 30 Mar 2013
pastedimg = blankimg;
pastedimg( startrow:startrow+150-1, startcol:startcol+150-1) = croppedimg;
  9 Comments
Walter Roberson
Walter Roberson on 31 Mar 2013
No, you have
A4=A3;
in your command history, but A3 is your cropped image. You need to set A4 to your blank image, A1.
integra-t
integra-t on 31 Mar 2013
Edited: integra-t on 3 Apr 2013
Thought you would not answer until tomorrow since its late. I am up late cause I have to work until 7AM. =D
Sorry, about the mix up. I associated the correct images with the proper corresponding name. Now I end up with a white box inside of the blank yellow image. http://db.tt/7JD332yK

Sign in to comment.


Image Analyst
Image Analyst on 30 Mar 2013
Here's one of my old demos. You should just be able to copy and past and run. It uses standard demo images.
clear
clc;
close all;
workspace; % Make sure the workspace panel is showing.
format longg;
format compact;
fontSize = 20;
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'Moon.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
bigGrayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(bigGrayImage);
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(bigGrayImage, []);
title('Original BIG Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'cameraman.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
smallGrayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[smallRows smallColumns numberOfColorBands] = size(smallGrayImage);
% Display the original gray scale image.
subplot(2, 2, 2);
imshow(smallGrayImage, []);
title('Original SMALL Grayscale Image', 'FontSize', fontSize);
% Note: smallGrayImage could just have well been a sub-portion of
% another image that you extracted out with imcrop() or indexing.
% Paste small image into big one.
% Put upper left at xColumn = 50, and yRow = 100.
xColumn = 50;
yRow = 100;
row1 = yRow;
row2 = row1 + smallRows - 1;
col1 = xColumn;
col2 = col1 + smallColumns - 1;
% Not shown: making sure they don't exceed
% image boundaries and making adjustments if they do.
pastedImage = bigGrayImage; % Initialize.
pastedImage(row1:row2, col1:col2) = smallGrayImage;
% Display the pasted gray scale image.
subplot(2, 2, 3);
imshow(pastedImage, []);
title('Pasted Image', 'FontSize', fontSize);
  3 Comments
Image Analyst
Image Analyst on 13 Jun 2021
@Aminah Zhulaika, Just initialize pasted image with your "other picture" instead of bigGrayImage:
pastedImage = otherImage; % Initialize.
pastedImage(row1:row2, col1:col2) = smallGrayImage;
or to do it in place, overwriting your original otherImage:
otherImage(row1:row2, col1:col2) = smallGrayImage;
Aminah Zhulaika
Aminah Zhulaika on 14 Jun 2021
thank you. but this code cant select the region that I want to crop. How about the other code that you give before. This one. How to use this code which can paste the cropped image on other picture instead of paste it on the original picture?
% Lets user drag out a box on an image, then define where they want to paste it.
% Then it pastes the drawn region onto the original image.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
format compact;
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'eight.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(grayImage);
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(grayImage);
axis on;
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Let's compute and display the histogram, just for fun.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
grid on;
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
% Ask user to draw a box.
subplot(2, 2, 1);
promptMessage = sprintf('Drag out a box that you want to copy,\nor Cancel to abort processing?');
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, 'Continue', 'Cancel', 'Continue');
if strcmpi(button, 'Cancel')
return;
end
k = waitforbuttonpress;
point1 = get(gca,'CurrentPoint'); % button down detected
finalRect = rbbox; % return figure units
point2 = get(gca,'CurrentPoint'); % button up detected
point1 = point1(1,1:2); % extract x and y
point2 = point2(1,1:2);
p1 = min(point1,point2); % calculate locations
offset = abs(point1-point2); % and dimensions
% Find the coordinates of the box.
xCoords = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)];
yCoords = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)];
x1 = round(xCoords(1));
x2 = round(xCoords(2));
y1 = round(yCoords(5));
y2 = round(yCoords(3));
hold on
axis manual
plot(xCoords, yCoords, 'b-'); % redraw in dataspace units
% Display the cropped image.
croppedImage = grayImage(y1:y2,x1:x2);
subplot(2, 2, 3);
imshow(croppedImage);
axis on;
title('Region that you defined', 'FontSize', fontSize);
% Paste it onto the original image
[rows2 columns2] = size(croppedImage)
promptMessage = sprintf('Click on the upper left point where you want to paste it,\nor Cancel to abort processing?');
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, 'Continue', 'Cancel', 'Continue');
if strcmpi(button, 'Cancel')
return;
end
[x, y] = ginput(1)
% Determine the pasting boundaries.
r1 = int32(y);
c1 = int32(x);
r2 = r1 + rows2 - 1;
r2 = min([r2 rows]);
c2 = c1 + columns2 - 1;
c2 = min([c2, columns]);
plot([c1 c2 c2 c1 c1], [r1 r1 r2 r2 r1], 'r-');
% Paste as much of croppedImage as will fit into the original image.
grayImage(r1:r2, c1:c2) = croppedImage(1:(r2-r1+1), 1:(c2-c1+1));
subplot(2, 2, 4);
imshow(grayImage);
axis on;
title('Region that you defined pasted onto original', 'FontSize', fontSize);

Sign in to comment.


Mohseena Ansar
Mohseena Ansar on 17 Feb 2017
can you give matlab code for pasting different portions of an image into a plane image...?

Community Treasure Hunt

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

Start Hunting!