Reputation: 8376
I'm trying to perform simple arithmetic operations like sum, difference, division, and, etc to images.
An example of what I'm doing is:
function I = difference_matlab(source1, source2)
image1 = rgb2gray(imread(source1));
image2 = rgb2gray(imread(source2));
I = mat2gray(image1 - image2);
subplot(2,2,1)
imshow(image1)
subplot(2,2,2)
imshow(image2)
subplot(2,2,3:4)
imshow(I);
end
However this will fail when images are not same size, how can I overlap images so operations are performed in common area? That's something like take smaller image and mount it over bigger, cropping operations region. However I can't figure out how to do it with out looping each image matrix.
Upvotes: 0
Views: 90
Reputation: 357
To crop both images to the size of the smaller one (or also to the smallest size in X, Y and Z direction):
function I = difference_matlab(source1, source2)
image1 = rgb2gray(imread(source1));
image2 = rgb2gray(imread(source2));
minsize=min([size(image1); size(image2)], [], 1);
image1=image1(1:minsize(1), 1:minsize(2), 1:minsize(3));
image2=image2(1:minsize(1), 1:minsize(2), 1:minsize(3));
I = mat2gray(image1 - image2);
subplot(2,2,1)
imshow(image1)
subplot(2,2,2)
imshow(image2)
subplot(2,2,3:4)
imshow(I);
end
To pad the smaller one with zeros:
function I = difference_matlab(source1, source2)
image1 = rgb2gray(imread(source1));
image2 = rgb2gray(imread(source2));
maxsize=max([size(image1); size(image2)], [], 1);
image1_padded=zeros(maxsize);
image2_padded=zeros(maxsize);
image1_padded(1:size(image1, 1), 1:size(image1, 2), 1:size(image1, 3))=image1;
image2_padded(1:size(image2, 1), 1:size(image2, 2), 1:size(image2, 3))=image2;
I = mat2gray(image1_padded - image2_padded);
subplot(2,2,1)
imshow(image1)
subplot(2,2,2)
imshow(image2)
subplot(2,2,3:4)
imshow(I);
end
No idea if there is a more elegant solution for the zero padding, but I think it should do the trick!
pick what you like more :-)
Upvotes: 2