参考资料:矩特征---OpenCV-Python开发指南(25)_cv2.moments_李元静的博客-CSDN博客
探究opencv中的moments函数和HuMoments函数_opencv moment_傲笑风的博客-CSDN博客
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread("../SampleImages/stars.png", cv.IMREAD_GRAYSCALE)
plt.imshow(img, cmap=plt.cm.gray)
#直接计算灰度图的距
#cv.moments(array, binaryImage=False)
#array:输入的数组,可以是灰度图像或二维数组,比如轮廓提取结果
#binaryImage:默认False,若为True,则所有非零的像素会按值1对待,
# 也就是相当于对图像进行了二值化,阈值为1,次参数仅对图像生效
#参考资料:https://blog.csdn.net/liyuanjinglyj/article/details/113916287
img_gray_moments = cv.moments(img)
print("Image Moments:\n", img_gray_moments)
#计算灰度图的Hu距
#cv.HuMoments(moments)
#参考资料:https://blog.csdn.net/Caesar6666/article/details/103257632
img_gray_huMoments = cv.HuMoments(img_gray_moments)
print("Image HuMoments:\n", img_gray_huMoments)
#转换为二值图
ret,img_bin = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
#提取轮廓
contours,hierarchy = cv.findContours(img_bin, 1, 2)
#计算轮廓的Hu距
for i in range(len(contours)):
contour_moments = cv.moments(contours[i])
contour_huMoments = cv.HuMoments(contour_moments)
print("Contour HuMoments", str(i), ":\n", contour_huMoments)