## 学习笔记(04):一学即懂的计算机视觉（第一季）-图像表示描述实战演练

import numpy as np
import cv2
import copy

gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#去噪声
kernel=cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
gray=cv2.morphologyEx(gray,cv2.MORPH_OPEN,kernel)
gray=cv2.morphologyEx(gray,cv2.MORPH_CLOSE,kernel)

thr,bw=cv2.threshold(gray,1,255,cv2.THRESH_BINARY)#thr阈值，bw处理后图像
cv2.imshow('Source',img)
cv2.imshow('Threshold',bw)
cv2.waitKey()
cv2.destroyAllWindows()
#图像轮廓
cnts,hier=cv2.findContours(bw,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)

disp_poly=img.copy()
disp_elli=img.copy()
for i in range(len(cnts)):
c=cnts[i]       #轮廓提取
poly=cv2.approxPolyDP(c,5,True)#外接矩形拟合,5代表允许误差大小,1,几乎看不出折线
cv2.polylines(disp_poly,[poly],True,(255,255,255),2)  #画出外接矩形

#拟合椭圆
if(len(c)>5):
ellipse=cv2.fitEllipse(c)
cv2.ellipse(disp_elli,ellipse,(255,255,255),2)

area=cv2.contourArea(c)#面积计算
length=cv2.arcLength(c,True)
moments=cv2.moments(c)#普通距的计算
hu=cv2.HuMoments(moments)#计算Hu不变矩
print(i+1,' : ','length=%.1f'%length,'area=',area,
'm00=%.3f,m01=%.3f,m10=%.3f,m11=%.3f'%(hu[0],hu[1],hu[2],hu[3]))
#得到对应区域包围框，并在左上角限时序号
x,y,w,h=cv2.boundingRect(c)
cv2.putText(disp_poly,str(i+1),(x,y),cv2.FONT_HERSHEY_PLAIN,0.8,(0xff,0xff,0xff))
cv2.imshow('poly',disp_poly)
cv2.imshow('elli',disp_elli)
cv2.waitKey()
cv2.destroyAllWindows()