I want to subtract two images and show the results in another figure. For instance, if the subtraction matrix has 0 value indicate the elements with black, if it has negative value show them with red and if it has positive value show with blue. How can I do that?

 採用された回答

Walter Roberson
Walter Roberson 2021 年 2 月 17 日

0 投票

%sample data
firstImage = imread('cameraman.tif');
secondImage = imresize( rgb2gray( imread('flamingos.jpg') ), size(firstImage));
%assuming grayscale images
imgdiff = double(firstImage) - double(secondImage);
n0p = sign(imgdiff); %-1 for negative, 0 for equal, 1 for positive
%add 2 to n0p to get a 1-based index
cmap = [1 0 0; 0 0 0; 0 0 1]; %red, black, blue
diffImg = reshape(cmap(n0p+2,:), size(imgdiff,1), size(imgdiff,2), 3);
%show it off
subplot(3,1,1)
imshow(firstImage);
title('cameraman')
subplot(3,1,2)
imshow(secondImage);
title('flamingos')
subplot(3,1,3)
imshow(diffImg);
title('color difference image')

4 件のコメント

ali eskandari
ali eskandari 2021 年 2 月 24 日
Thank you so much for your guidance... Could you please explain this part of the code?
cmap(n0p+2,:)
Walter Roberson
Walter Roberson 2021 年 2 月 24 日
Notice the
n0p = sign(imgdiff); %-1 for negative, 0 for equal, 1 for positive
As indicated in the comment, sign() is -1 when the value is negative, 0 when the value is 0, +1 when the value is positive -- which correspond to the three categories you asked for, as you asked for different colors for negative (red), equal (black) or positive (blue)
So you have an array of values that are all -1, 0, or +1, and you need to turn that into a colormap index. colormap indices start at +1, so the easiest way is to add 2 to the [-1, 0, +1] getting [+1, +2, +3] indices into the color map, which you then use to extract rows from the color map.
ali eskandari
ali eskandari 2021 年 2 月 24 日
Briliant!!!
Thanks a lot...
Is it possible to show the categories in the legend??
Walter Roberson
Walter Roberson 2021 年 2 月 24 日
%sample data
firstImage = imread('cameraman.tif');
secondImage = imresize( rgb2gray( imread('flamingos.jpg') ), size(firstImage));
%assuming grayscale images
imgdiff = double(firstImage) - double(secondImage);
n0p = sign(imgdiff); %-1 for negative, 0 for equal, 1 for positive
%add 2 to n0p to get a 1-based index
cmap = [1 0 0; 0 0 0; 0 0 1]; %red, black, blue
diffImg = reshape(cmap(n0p+2,:), size(imgdiff,1), size(imgdiff,2), 3);
%show it off
subplot(3,1,1)
imshow(firstImage);
title('cameraman')
subplot(3,1,2)
imshow(secondImage);
title('flamingos')
subplot(3,1,3)
imshow(diffImg);
title('color difference image')
hold on
names = {'negative', 'equal', 'positive'};
for K = 1 : 3
L(K) = plot(nan,nan,'s', 'markeredgecolor', cmap(K,:), 'markerfacecolor', cmap(K,:));
end
hold off
legend(L, names, 'location', 'eastoutside')

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by