HuMoments.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import cv2, sys, os
  2. from math import copysign, log10
  3. def main():
  4. showLogTransformedHuMoments = True
  5. for i in range(1,len(sys.argv)):
  6. # Obtain filename from command line argument
  7. filename = sys.argv[i]
  8. # Read image
  9. im = cv2.imread(filename,cv2.IMREAD_GRAYSCALE)
  10. # Threshold image
  11. _,im = cv2.threshold(im, 128, 255, cv2.THRESH_BINARY)
  12. # Calculate Moments
  13. moment = cv2.moments(im)
  14. # Calculate Hu Moments
  15. huMoments = cv2.HuMoments(moment)
  16. # Print Hu Moments
  17. print("{}: ".format(filename),end='')
  18. for i in range(0,7):
  19. if showLogTransformedHuMoments:
  20. # Log transform Hu Moments to make
  21. # squash the range
  22. print("{:.5f}".format(-1*copysign(1.0,\
  23. huMoments[i])*log10(abs(huMoments[i]))),\
  24. end=' ')
  25. else:
  26. # Hu Moments without log transform
  27. print("{:.5f}".format(huMoments[i]),end=' ')
  28. print()
  29. if __name__ == "__main__":
  30. main()