Link API Reference .
# -*- coding: utf-8 -*-
import cv2
#Ipythonで表示用の設定
import matplotlib.pyplot as plt
%matplotlib inline
#画像読込
in_img1 = cv2.imread("pic1.png") #処理用
in_img2 = cv2.imread("pic1.png") #表示用
#グレイ画像へ変換
gray_img = cv2.cvtColor(in_img1, cv2.COLOR_BGR2GRAY)
#2値化
ret,thresh = cv2.threshold(gray_img,220,1,0)
#輪郭抽出
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#ID:5の輪郭をオーバレイ
cv2.drawContours(in_img2, contours, 5, (0,255,0), 3)
#ID:5のオブジェクトのモーメント算出
cnt = contours[5]
M = cv2.moments(cnt)
#ID:5のオブジェクトの面積
area = cv2.contourArea(cnt)
#ID:5のオブジェクトの重心
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
#ID:5のオブジェクトのペリメータ(周囲長)
perimeter = cv2.arcLength(cnt,True)
#OpenCVがBGRなのでRGBに変換
disp_out_img = cv2.cvtColor(in_img2, cv2.COLOR_BGR2RGB)
#画像表示
plt.figure(figsize=(6,6))
plt.imshow(disp_out_img)
print "ID:5のオブジェクトのモーメント"
print "モーメント"
print "m00:",M['m00']
print "m10:",M['m10']
print "m01:",M['m01']
print "m11:",M['m11']
print "m02:",M['m02']
print "m20:",M['m20']
print "m12:",M['m12']
print "m21:",M['m21']
print "m03:",M['m03']
print "m30:",M['m30']
print "\n"
print "中心モーメント"
print "mu11:",M['mu11']
print "mu12:",M['mu12']
print "mu21:",M['mu21']
print "mu02:",M['mu02']
print "mu20:",M['mu20']
print "mu03:",M['mu03']
print "mu30:",M['mu30']
print "\n"
print "正規化した中心モーメント"
print "nu11:",M['nu11']
print "nu12:",M['nu12']
print "nu21:",M['nu21']
print "nu02:",M['nu02']
print "nu20:",M['nu20']
print "nu03:",M['nu03']
print "nu30:",M['nu30']
print "\n"
print "面積:", area, "\n" #モーメントM['m00']も面積
print "重心(Xg,Yg):", cx, cy, "\n"
print "ペリメータ:", perimeter, "\n"
print "\n"