Hu矩提取matlab代码
时间: 2023-11-25 13:29:29 浏览: 185
Hu矩提取是一种基于轮廓分析的图像特征提取算法,其实现代码在Matlab中如下:
% 读取图像
I = imread('image.png');
% 将图像转化为二值图像
I_binary = imbinarize(I);
% 根据二值图像获取其轮廓
[B, L] = bwboundaries(I_binary, 'noholes');
% 计算轮廓的Hu矩
hu_moments = hu_moments(B{1});
% 输出Hu矩值
disp(hu_moments);
其中hu_moments是自定义的一个函数,实现如下:
function hu_moments = hu_moments(boundary)
% 计算轮廓的Hu矩
hu_moments = zeros(1, 7);
hu_moments(1) = inv_moment(boundary, 2, 0) + inv_moment(boundary, 0, 2);
hu_moments(2) = (inv_moment(boundary, 2, 0) - inv_moment(boundary, 0, 2))^2 + 4*inv_moment(boundary, 1, 1)^2;
hu_moments(3) = (inv_moment(boundary, 3, 0) - 3*inv_moment(boundary, 1, 2))^2 + (3*inv_moment(boundary, 2, 1) - inv_moment(boundary, 0, 3))^2;
hu_moments(4) = (inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))^2 + (inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))^2;
hu_moments(5) = (inv_moment(boundary, 3, 0) - 3*inv_moment(boundary, 1, 2))*(inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))*((inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))^2 - 3*((inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))^2)) + (3*inv_moment(boundary, 2, 1) - inv_moment(boundary, 0, 3))*(inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))*(3*(inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))^2 - ((inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))^2));
hu_moments(6) = (inv_moment(boundary, 2, 0) - inv_moment(boundary, 0, 2))*((inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))^2 - (inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))^2) + 4*inv_moment(boundary, 1, 1)*(inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))*(inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3));
hu_moments(7) = (3*inv_moment(boundary, 2, 1) - inv_moment(boundary, 0, 3))*(inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))*((inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))^2 - 3*((inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))^2)) - (inv_moment(boundary, 3, 0) - 3*inv_moment(boundary, 1, 2))*(inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))*(3*(inv_moment(boundary, 3, 0) + inv_moment(boundary, 1, 2))^2 - ((inv_moment(boundary, 2, 1) + inv_moment(boundary, 0, 3))^2));
% 将Hu矩标准化
hu_moments = -sign(hu_moments).*log10(abs(hu_moments));
end
其中inv_moment也是自定义的一个函数,用来计算轮廓的非中心矩,实现如下:
function inv_m = inv_moment(boundary, p, q)
% 计算轮廓的非中心矩
inv_m = sum((boundary(:, 2).^p).*(boundary(:, 1).^q));
end
以上就是Hu矩提取的Matlab代码实现。
阅读全文