import cv2
o=cv2.imread('C:/Users/xpp/Desktop/coins.png')#原始图像
gray=cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)#将彩色图片转换为灰度图片
HuM1=cv2.HuMoments(cv2.moments(gray)).flatten()#提取轮廓特征
print("cv2.moments(gray)=n",cv2.moments(gray))
print("nHuM1=n",HuM1)
print("ncv2.moments(gray)['nu20'] cv2.moments(gray)['nu02']=%f %f=%fn"%(cv2.moments(gray)['nu20'],cv2.moments(gray)['nu02'],cv2.moments(gray)['nu20'] cv2.moments(gray)['nu02']))
print("HuM1[0]=",HuM1[0])
print("nHu[0]-(nu02 nu20)=",HuM1[0]-(cv2.moments(gray)['nu20'] cv2.moments(gray)['nu02']))
cv2.imshow("original",o)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.moments(gray)= {'m00': 23160406.0, 'm10': 5309406395.0, 'm01': 5285254759.0, 'm20': 1619320556027.0, 'm11': 1220530213240.0, 'm02': 1561476861069.0, 'm30': 556196938824935.0, 'm21': 372633547500752.0, 'm12': 360387607561568.0, 'm03': 521393967073471.0, 'mu20': 402165888390.0469, 'mu11': 8912186481.799707, 'mu02': 355370289900.4225, 'mu30': 586851719266.3297, 'mu21': -985054646724.5199, 'mu12': -1640656702725.486, 'mu03': 2869030902656.4194, 'nu20': 0.0007497438198269416, 'nu11': 1.6614677994256044e-05, 'nu02': 0.0006625044199286802, 'nu30': 2.2733324991600768e-07, 'nu21': -3.815881709688264e-07, 'nu12': -6.35553765938273e-07, 'nu03': 1.1113984977768165e-06} HuM1= [ 1.41224824e-03 8.71490299e-09 9.64420426e-12 6.99267103e-13 1.30062645e-24 -5.17274144e-17 -1.26726221e-24] cv2.moments(gray)['nu20'] cv2.moments(gray)['nu02']=0.000750 0.000663=0.001412 HuM1[0]= 0.0014122482397556217 Hu[0]-(nu02 nu20)= 0.0
算法:Hu矩是归一化中心矩的线性组合,通过归一化中心矩的组合运算得到每一个矩。原点矩或中心矩在图像旋转、缩放、平移等操作后,不同时具有矩的不变性,但是Hu矩具有图像旋转、缩放、平移不变性。
hu=cv2.HuMoments(m)
- m表示轮廓的矩
归一化中心矩:
- 二阶Hu矩:nu20, nu11, nu02
- 三阶Hu矩:nu30, nu21, nu12, nu03
v来代替nu的归一化中心矩:
- 二阶Hu矩:v20, v11, v02
- 三阶Hu矩:v30, v21, v12, v03
Hu矩利用二阶和三阶中心矩构造七个不变矩,在连续图像条件下,保持图像旋转、缩放、平移不变性,具体定义如下:
注意:Hu矩特征只有低阶矩(最多三阶矩),对于图像的细节不能完整地描述出来,图像识别速度快,准确率低。