Python Opencv实践 - 轮廓检测

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread("../SampleImages/map.jpg")
print(img.shape)
plt.imshow(img[:,:,::-1])

#Canny边缘检测
edges = cv.Canny(img, 127, 255, 0)
plt.imshow(edges, cmap=plt.cm.gray)

#查找轮廓
#cv.findContours(image, mode, method[, contours[, hierarchy[, offset ]]])
#image: 原图
#mode: 轮廓模式
#    cv2.RETR_EXTERNAL表示只检测外轮廓
#    cv2.RETR_LIST检测的轮廓不建立等级关系
#    cv2.RETR_CCOMP建立两个等级的轮廓,上面的一层为外边界,里面的一层为内孔的边界信息。如果内孔内还有一个连通物体,这个物体的边界也在顶层。
#    cv2.RETR_TREE建立一个等级树结构的轮廓。
#method: 轮廓的近似方法
#    cv2.CHAIN_APPROX_NONE存储所有的轮廓点,相邻的两个点的像素位置差不超过1,即max(abs(x1-x2),abs(y2-y1))==1
#    cv2.CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息
#    cv2.CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS使用teh-Chinl chain 近似算法
#返回值: opencv2返回两个值:contours:hierarchy。注:opencv3会返回三个值,分别是img, countours, hierarchy
#参考资料:https://blog.csdn.net/leemboy/article/details/84932885
contours,hierachy = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)

#绘制轮廓
#cv.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset ]]]]]) 
#image:原图
#contours: 轮廓数据
#contouridx:要绘制的轮廓的index,如果是-1,表示绘制所有轮廓。
#color,thickness,lineType: 轮廓线条颜色,厚度和线的类型
img = cv.drawContours(img, contours, -1, (0,255,0), 2)

plt.imshow(img[:,:,::-1])

 

 

猜你喜欢

转载自blog.csdn.net/vivo01/article/details/132635343