我想找出一张图片与我拥有的一些样本(黑白)有多相似。
我使用的是绝对差值和代码,但由于我刚接触MATLAB,我还不知道如何使用它。这个算法是如何工作的?它能给出图片之间的相似度吗?
I= imread('img1.jpg');
image2= imread('img2.jpg');
% J = uint8(filter2(fspecial('gaussian'), I));
K = imabsdiff(I,image2);
figure, imshow(K,[])
我想找出一张图片与我拥有的一些样本(黑白)有多相似。
我使用的是绝对差值和代码,但由于我刚接触MATLAB,我还不知道如何使用它。这个算法是如何工作的?它能给出图片之间的相似度吗?
I= imread('img1.jpg');
image2= imread('img2.jpg');
% J = uint8(filter2(fspecial('gaussian'), I));
K = imabsdiff(I,image2);
figure, imshow(K,[])
我认为你已经基本回答了自己的问题,这是绝对差值的总和。假设你有相同大小和类型的img1
和img2
.
要找到它们之间的差异,请进行减法操作。
img1-img2
abs
。abs(img1-img2)
sum
函数。请注意,您需要为图像的每个“维度”执行此操作。如果您不确定,请键入size(img1)
并查看是否出现2个或3个数字,这对应于您需要使用多少个sum(...)
。sum(sum(sum(abs(img1-img2))))
^^ 是绝对差的总和。无论哪个图像的总和最小,都可以视为最接近的图像。
如果你有不同大小的图像,需要使用 normxcorr2 函数。该函数将返回一个矩阵,其中显示了模板(小)图像在不同点上适合大图像的程度。找到该矩阵的最大值,即可确定该图像的适合程度。
例如:
correlation = normxcorr2(smallImg, bigImg);
compareMe = max(correlation(:))
sum(abs(img1(:)-img2(:)))
作为更简单的方法,但仍然是个好答案。 - chappjc最佳实践是使用MATLAB
的内置函数imabsdiff
。与其他建议的答案相比,如果您的图像格式为uint8
,它会处理范围边界。考虑以下内容:
img1 = uint8(10);
img2 = uint8(20);
sum(abs(img1(:)-img2(:)))
gives you 0, whereas
imabsdiff(img1(:),img2(:))
正确地给出了10。
在MATLAB中,你应该使用命令im2col
来以向量化的方式进行操作。
只需将每个邻域按列排列(对于每个帧)。
将它们放入3D矩阵中,并在第三维度上进行操作。
我使用了维基百科关于“绝对差值之和”的定义。
演示脚本:
```
% Sum of Absolute Differences Demo
numRows = 10;
numCols = 10;
refBlockRadius = 1;
refBlockLength = (2 * refBlockRadius) + 1;
mImgSrc = randi([0, 255], [numRows, numCols]);
mRefBlock = randi([0, 255], [refBlockLength, refBlockLength]);
mSumAbsDiff = SumAbsoluteDifferences(mImgSrc, mRefBlock);
```
SumAbsoluteDifferences
函数:
```
function [ mSumAbsDiff ] = SumAbsoluteDifferences( mInputImage, mRefBlock )
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
numRows = size(mInputImage, 1);
numCols = size(mInputImage, 2);
blockLength = size(mRefBlock, 1);
blockRadius = (blockLength - 1) / 2;
mInputImagePadded = padarray(mInputImage, [blockRadius, blockRadius], 'replicate', 'both');
mBlockCol = im2col(mInputImagePadded, [blockLength, blockLength], 'sliding');
mSumAbsDiff = sum(abs(bsxfun(@minus, mBlockCol, mRefBlock(:))));
mSumAbsDiff = col2im(mSumAbsDiff, [blockLength, blockLength], [(numRows + blockLength - 1), (numCols + blockLength - 1)]);
end
```
享受...
imabsdiff
文档。 - chappjc