Lucas-Kanade光流算法、基于Kalman滤波的光流算法,基于Horn-Schunck光流算法精确度比较matlab代码
时间: 2023-12-01 19:07:15 浏览: 122
基于光流法的光流检测matlab算法,代码很详细.7z
5星 · 资源好评率100%
下面是基于Lucas-Kanade光流算法、基于Kalman滤波的光流算法和基于Horn-Schunck光流算法的精确度比较的Matlab代码。
```matlab
% 读入两幅图像
I1 = imread('frame1.jpg');
I2 = imread('frame2.jpg');
% 转为灰度图像
I1 = rgb2gray(I1);
I2 = rgb2gray(I2);
% Lucas-Kanade光流算法
points1 = detectMinEigenFeatures(I1);
[features1, points1] = extractFeatures(I1, points1);
points2 = detectMinEigenFeatures(I2);
[features2, points2] = extractFeatures(I2, points2);
indexPairs = matchFeatures(features1, features2);
matchedPoints1 = points1(indexPairs(:, 1), :);
matchedPoints2 = points2(indexPairs(:, 2), :);
[tform, inlierPoints1, inlierPoints2] = estimateGeometricTransform(matchedPoints1, matchedPoints2, 'affine');
outputView = imref2d(size(I1));
Ir = imwarp(I2, tform, 'OutputView', outputView);
figure, imshowpair(I1, Ir, 'montage')
% 基于Kalman滤波的光流算法
[motionVect, blkIdx] = motionEstARPS(I1, I2, 16);
blkCnt = length(blkIdx);
for i = 1:blkCnt
h = blkIdx(i, 1);
w = blkIdx(i, 2);
motionVec = motionVect(h, w, :);
x1 = (w - 1) * 16 + 1;
y1 = (h - 1) * 16 + 1;
x2 = x1 + motionVec(1);
y2 = y1 + motionVec(2);
line([x1 x2], [y1 y2], 'Color', 'r');
end
% 基于Horn-Schunck光流算法
[Gx, Gy, Gt] = horn_schunck(I1, I2, 1);
u = zeros(size(I1));
v = zeros(size(I1));
alpha = 1;
for i = 1:10
uAvg = conv2(u, ones(3, 3), 'same') / 9;
vAvg = conv2(v, ones(3, 3), 'same') / 9;
du = ((Gx .* uAvg) + (Gy .* vAvg) + Gt) ./ (alpha^2 + Gx.^2 + Gy.^2);
dv = ((Gx .* vAvg) + (Gy .* uAvg) + Gt) ./ (alpha^2 + Gx.^2 + Gy.^2);
u = uAvg - Gx .* du;
v = vAvg - Gy .* dv;
end
figure, imshow(I1)
hold on
[x, y] = meshgrid(1:16:size(I1,2), 1:16:size(I1,1));
quiver(x, y, u(1:16:end, 1:16:end), v(1:16:end, 1:16:end), 2, 'r');
% 计算精度
groundTruth = readFlowFile('groundtruth.flo');
flowLK = estimateFlowLK(I1, I2);
flowKalman = motion2flow(motionVect);
flowHS = flow2uv(u, v);
errLK = flow_error(groundTruth, flowLK);
errKalman = flow_error(groundTruth, flowKalman);
errHS = flow_error(groundTruth, flowHS);
fprintf('Lucas-Kanade光流算法平均误差:%f\n', mean(errLK));
fprintf('基于Kalman滤波的光流算法平均误差:%f\n', mean(errKalman));
fprintf('基于Horn-Schunck光流算法平均误差:%f\n', mean(errHS));
```
需要注意的是,这里的`motionEstARPS`、`horn_schunck`、`motion2flow`、`flow2uv`、`flow_error`和`readFlowFile`等函数并不是Matlab自带的函数,需要自己实现或者下载相应的代码库。
阅读全文