对轮廓图进行不变矩特征的提取,用matlab实现,并对代码进行解释
时间: 2023-05-27 20:01:31 浏览: 209
下面是matlab实现轮廓图的不变矩特征提取的代码:
```
% 读入图像
im = imread('test.jpg');
% 转换为灰度图像
gray_im = rgb2gray(im);
% 取边缘图
edge_im = edge(gray_im, 'Canny');
% 计算不变矩
m00 = sum(sum(edge_im));
[x,y] = meshgrid(1:size(edge_im, 2), 1:size(edge_im, 1));
m10 = sum(sum(x.*edge_im));
m01 = sum(sum(y.*edge_im));
xm = m10./m00;
ym = m01./m00;
x = x - xm;
y = y - ym;
m11 = sum(sum(x.*y.*edge_im));
m20 = sum(sum(x.^2.*edge_im));
m02 = sum(sum(y.^2.*edge_im));
m21 = sum(sum(x.^2.*y.*edge_im));
m12 = sum(sum(x.*y.^2.*edge_im));
mu20 = m20 - xm.^2.*m00;
mu02 = m02 - ym.^2.*m00;
mu11 = m11 - xm.*ym.*m00;
mu30 = sum(sum(x.^3.*edge_im)) - 3*xm.*mu20;
mu03 = sum(sum(y.^3.*edge_im)) - 3*ym.*mu02;
nu20 = mu20./(m00).^2;
nu02 = mu02./(m00).^2;
nu11 = mu11./(m00).^2.5;
nu30 = mu30./(m00).^2.5;
nu03 = mu03./(m00).^2.5;
% 输出结果
fprintf('nu20 = %f\n', nu20);
fprintf('nu02 = %f\n', nu02);
fprintf('nu11 = %f\n', nu11);
fprintf('nu30 = %f\n', nu30);
fprintf('nu03 = %f\n', nu03);
```
该代码实现的功能是读入一幅图像,先转换为灰度图像,然后计算出其边缘图,最后基于边缘图计算出相应的不变矩特征,并输出结果。
为了说明代码的实现原理,下面对其中的几个关键步骤进行解释:
1. 边缘图的提取
```
edge_im = edge(gray_im, 'Canny');
```
这儿使用了canny边缘检测算法提取图像的边缘。可以使用其他的边缘检测方法代替。
2. 不变矩的计算
```
m00 = sum(sum(edge_im));
[x,y] = meshgrid(1:size(edge_im, 2), 1:size(edge_im, 1));
m10 = sum(sum(x.*edge_im));
m01 = sum(sum(y.*edge_im));
xm = m10./m00;
ym = m01./m00;
x = x - xm;
y = y - ym;
m11 = sum(sum(x.*y.*edge_im));
m20 = sum(sum(x.^2.*edge_im));
m02 = sum(sum(y.^2.*edge_im));
m21 = sum(sum(x.^2.*y.*edge_im));
m12 = sum(sum(x.*y.^2.*edge_im));
mu20 = m20 - xm.^2.*m00;
mu02 = m02 - ym.^2.*m00;
mu11 = m11 - xm.*ym.*m00;
mu30 = sum(sum(x.^3.*edge_im)) - 3*xm.*mu20;
mu03 = sum(sum(y.^3.*edge_im)) - 3*ym.*mu02;
nu20 = mu20./(m00).^2;
nu02 = mu02./(m00).^2;
nu11 = mu11./(m00).^2.5;
nu30 = mu30./(m00).^2.5;
nu03 = mu03./(m00).^2.5;
```
这儿计算了轮廓图的一些不变矩特征,包括:
- m00: 轮廓图的0阶矩,即轮廓图的像素总数;
- m10, m01: 轮廓图的1阶矩,分别表示在x、y方向上轮廓图的像素分布情况;
- m11, m20, m02, m21, m12: 轮廓图的2阶矩及混合矩,用于计算不变矩;
- mu20, mu02, mu11, mu30, mu03: 轮廓图的中心矩,用于计算不变矩;
- nu20, nu02, nu11, nu30, nu03: 不变矩,是中心矩乘以某些常数得到的。
其具体计算公式较为复杂,这儿不再赘述,可参考相关文献和资料。
阅读全文