计算Hu距:
C++
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main(int argc, char **argv)
{
bool showLogTransformedHuMoments = true;
for (int i = 1; i < argc; i++)
{
// Obtain filename from command line argument
string filename(argv[i]);
// Read Image
Mat im = imread(filename,IMREAD_GRAYSCALE);
// Threshold image
threshold(im, im, 128, 255, THRESH_BINARY);
// Calculate Moments
Moments moment = moments(im, false);
// Calculate Hu Moments
double huMoments[7];
HuMoments(moment, huMoments);
// Print Hu Moments
cout << filename << ": ";
for(int i = 0; i < 7; i++)
{
if(showLogTransformedHuMoments)
{
// Log transform Hu Moments to make squash the range
cout << -1 * copysign(1.0, huMoments[i]) * log10(abs(huMoments[i])) << " ";
}
else
{
// Hu Moments without log transform.
cout << huMoments[i] << " ";
}
}
// One row per file
cout << endl;
}
}
Python
import cv2, sys, os
from math import copysign, log10
def main():
showLogTransformedHuMoments = True
for i in range(1,len(sys.argv)):
# Obtain filename from command line argument
filename = sys.argv[i]
# Read image
im = cv2.imread(filename,cv2.IMREAD_GRAYSCALE)
# Threshold image
_,im = cv2.threshold(im, 128, 255, cv2.THRESH_BINARY)
# Calculate Moments
moment = cv2.moments(im)
# Calculate Hu Moments
huMoments = cv2.HuMoments(moment)
# Print Hu Moments
print("{}: ".format(filename),end='')
for i in range(0,7):
if showLogTransformedHuMoments:
# Log transform Hu Moments to make
# squash the range
print("{:.5f}".format(-1*copysign(1.0,\
huMoments[i])*log10(abs(huMoments[i]))),\
end=' ')
else:
# Hu Moments without log transform
print("{:.5f}".format(huMoments[i]),end=' ')
print()
if __name__ == "__main__":
main()
匹配Hu距
C++
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main(int argc, char **argv)
{
Mat im1 = imread("images/S0.png",IMREAD_GRAYSCALE);
Mat im2 = imread("images/K0.png",IMREAD_GRAYSCALE);
Mat im3 = imread("images/S4.png",IMREAD_GRAYSCALE);
double m1 = matchShapes(im1, im1, CONTOURS_MATCH_I2, 0);
double m2 = matchShapes(im1, im2, CONTOURS_MATCH_I2, 0);
double m3 = matchShapes(im1, im3, CONTOURS_MATCH_I2, 0);
cout << "Shape Distances Between " << endl << "-------------------------" << endl;
cout << "S0.png and S0.png : " << m1 << endl;
cout << "S0.png and K0.png : " << m2 << endl;
cout << "S0.png and S4.png : " << m3 << endl;
}
Python
import cv2
def main():
im1 = cv2.imread("images/S0.png",cv2.IMREAD_GRAYSCALE)
im2 = cv2.imread("images/K0.png",cv2.IMREAD_GRAYSCALE)
im3 = cv2.imread("images/S4.png",cv2.IMREAD_GRAYSCALE)
m1 = cv2.matchShapes(im1,im1,cv2.CONTOURS_MATCH_I2,0)
m2 = cv2.matchShapes(im1,im2,cv2.CONTOURS_MATCH_I2,0)
m3 = cv2.matchShapes(im1,im3,cv2.CONTOURS_MATCH_I2,0)
print("Shape Distances Between \n-------------------------")
print("S0.png and S0.png : {}".format(m1))
print("S0.png and K0.png : {}".format(m2))
print("S0.png and S4.png : {}".format(m3))
if __name__ == "__main__":
main()