import?cv2?#opencv读取的格式是BGR import?matplotlib.pyplot?as?plt import?numpy?as?np %matplotlib?inline
def?cv_show(name,img): ????cv2.imshow(name,img) ????cv2.waitKey(0) ????cv2.destroyAllWindows()
1??图像轮廓
????cv2.findContours(img,mode,method)
????RETR_EXTERNAL:
????RETR_LIST:
????RETR_CCOMP:
????RETR_TREE:这个常用,检索所有的轮廓,并重构嵌套轮廓的整个层次
????method:轮廓逼近方法
????CHAIN_APPROXNONE:以Freeman链码的方式输出轮廓,所有其它方法输出多边形(顶点的序列)
????CHAIN_APPROX_SIMPLE:压缩水平的,垂直的和斜的部分,也就是,函数只保留他们的终点部分
先把图变成灰度 img?=?cv2.imread("./car.png") img?=?cv2.imread("./contours.png") gray?=?cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,?thresh?=?cv2.threshold(gray,127,255,cv2.THRESH_BINARY) cv_show("thresh",thresh)
#第一个是灰度图,第二个是轮廓数据,第三个是层级 contours,?hierarchy?=?cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#传入绘制图像,轮廓,轮郭索引,顔色模式,线条厚度 #注意需要copy,要不原图会变 #-1表示所有的轮廓,如果是数量表示第几个轮廓,0,0,255表示BGR色值 draw_img?=?img.copy() res?=?cv2.drawContours(draw_img,contours,-1,(0,0,255),2) cv_show("res",res)
draw_img?=?img.copy() res?=?cv2.drawContours(draw_img,contours,0,(0,0,255),2) cv_show("res",res)
2??轮廓特证
#面积 cv2.contourArea(contours[0])#表示第0个轮廓的面积
#周长,True表示闭合的 cv2.arcLength(contours[0],True)
3??轮廓近似
img2?=?cv2.imread("./contours2.png") gray?=?cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret,?thresh?=?cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours,?hierarchy?=?cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cnt?=?contours[0]
draw_img?=?img2.copy() res?=?cv2.drawContours(draw_img,contours,-127,(0,0,255),2) cv_show("res",res)
epsilon?=?0.1*cv2.arcLength(cnt,True) approx?=?cv2.approxPolyDP(cnt,epsilon,True)
draw_img?=?img2.copy() res?=?cv2.drawContours(draw_img,[approx],-127,(0,0,255),2) cv_show("res",res)
4??外接矩形
img3?=?cv2.imread("./contours.png") gray?=?cv2.cvtColor(img3,cv2.COLOR_BGR2GRAY) ret,?thresh?=?cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours,?hierarchy?=?cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cnt?=?contours[3]
x,y,w,h?=?cv2.boundingRect(cnt) img4?=?cv2.rectangle(img3,(x,y),(x+h,y+h),(0,255,0),2) cv_show("img4",img4)
5??外接贺
?
?
?
(x,y),radius?=?cv2.minEnclosingCircle(cnt) center?=?(int(x),int(y)) radius?=?int(radius) img5?=?cv2.circle(img,center,radius,(0,255,0),2) cv_show("img5",img5)
?
|