Link API Reference .
# -*- coding: utf-8 -*-
import cv2
import numpy as np
#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]
x,y,w,h = cv2.boundingRect(cnt)
print "ASPECT RATIO:", float(w)/h,"\n"
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
print "SOLIDITY:",float(area)/hull_area,"\n"
print "Equivalent Diameter:", np.sqrt(4*area/np.pi),"\n"
area = cv2.contourArea(cnt)
rect_area = w*h
print "EXTENT:",float(area)/rect_area,"\n"
(x,y),(MA,ma),angle = cv2.fitEllipse(cnt)
print "Major Axis and Minor Axis lengths:", ma, MA,"\n"
print "ANGLE", angle,"\n"
mask = np.zeros(in_img1.shape,np.uint8)
cv2.drawContours(mask,[cnt],0,255,-1)
print "Pixel Points:\n", np.transpose(np.nonzero(mask))
#OpenCVがBGRなのでRGBに変換
disp_out_img = cv2.cvtColor(in_img2, cv2.COLOR_BGR2RGB)
#画像表示
plt.figure(figsize=(6,6))
plt.imshow(disp_out_img)