輪郭特徴(モーメント、面積、重心、ペリメータ(周囲長))の算出

V3.0.0

In [3]:
# -*- 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"                       
ID:5のオブジェクトのモーメント
モーメント
m00: 8856.0
m10: 490351.333333
m01: 1939139.5
m11: 107810794.0
m02: 434052048.5
m20: 31416618.0
m12: 24229054999.9
m21: 6916467692.75
m03: 99203242179.8
m30: 2211932936.4


中心モーメント
mu11: 441819.367623
mu12: 2372581.94249
mu21: -11547026.3358
mu02: 9451551.60973
mu20: 4266162.92979
mu03: 22661056.4788
mu30: -15786.1388159


正規化した中心モーメント
nu11: 0.0056333863091
nu12: 0.000321460192934
nu21: -0.00156450205037
nu02: 0.120511334133
nu20: 0.0543954059108
nu03: 0.00307033761713
nu30: -2.13885773071e-06


面積: 8856.0 

重心(Xg,Yg): 55 218 

ペリメータ: 390.249780416 




inserted by FC2 system