我想在Matlab中实现绝对差值之和,以在该帧的任一侧(即过去和未来帧)之间建立一个视频帧和5帧之间的相似性度量。我只需要每帧中共同定位像素的SAD值,而不是完整的搜索例程,例如完全搜索。
显然我可以将它作为嵌套循环实现,例如:
bs = 2; % block size
for (z_i = -bs:1:bs)
for (z_j = -bs:1:bs)
I1(1+bs:end-bs,1+bs:end-bs) = F1(1+bs+z_i:end-bs+z_i, 1+bs+z_j:end-bs+z_j);
I2(1+bs:end-bs,1+bs:end-bs) = F2(1+bs+z_i:end-bs+z_i, 1+bs+z_j:end-bs+z_j);
sad(:,:) = sad(:,:) + abs( I1(:,:) - I2(:,:));
end
end
但是我想知道有没有比这更有效的方法呢?至少我想我应该将上面的代码片段定义为函数吗?
任何建议都会感激不尽!
答案 0 :(得分:2)
你应该在MATLAB中使用命令im2col
,你可以用矢量化方式这样做
只需在列中排列每个邻域(对于每个帧)
将它们放入3D Matrix并在第3维上应用您的操作。
我使用了维基百科对" Sum of Absolute Differences"的定义。
演示脚本:
```
% 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
```
...享受