OpenCV—Python 轮廓检测(findContours)

版权声明:转载请说明来源,谢谢 https://blog.csdn.net/wsp_1138886114/article/details/82945328

1 获取轮廓

OpenCV2获取轮廓主要是用 cv2.findContours()

import cv2
import numpy as np

imgray = cv2.imread('test.jpg',0)              # 以灰度图形式读入
ret,thresh = cv2.threshold(imgray,127,255,0)   # 二值化,设定阈值127(大小影响二值化结果)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

其中,cv2.findContours() 的第二个参数主要有

  • cv2.RETR_LIST:检测的轮廓不建立等级关系
  • cv2.RETR_TREE:L建立一个等级树结构的轮廓。
  • cv2.RETR_CCOMP:建立两个等级的轮廓,上面的一层为外边界,里面的一层为内孔的边界信息。
  • cv2.RETR_EXTERNAL:表示只检测外轮廓

cv2.findContours() 的第三个参数 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 近似算法

2 绘出轮廓

cv2.drawContours()函数
cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset ]]]]])

  • 第一个参数是指明在哪幅图像上绘制轮廓;
  • 第二个参数是轮廓本身,在Python中是一个list。
  • 第三个参数指定绘制轮廓list中的哪条轮廓,如果是-1,则绘制其中的所有轮廓。后面的参数很简单。其中thickness表明轮廓线的宽度,如果是-1(cv2.FILLED),则为填充模式。绘制参数将在以后独立详细介绍。

为了看到自己画了哪些轮廓,可以使用 cv2.boundingRect()函数获取轮廓的范围,即左上角原点,以及他的高和宽。然后用cv2.rectangle()方法画出矩形轮廓

for i in range(0,len(contours)):  
    x, y, w, h = cv2.boundingRect(contours[i])   
    cv2.rectangle(image, (x,y), (x+w,y+h), (153,153,0), 5) 

3 获取轮廓区域

new_image=image[y+2:y+h-2,x+2:x+w-2]    # 先用y确定高,再用x确定宽
input_dir=("E:/cut_image/")
if not os.path.isdir(input_dir):
    os.makedirs(input_dir)
cv2.imwrite( nrootdir+str(i)+".jpg",newimage) 
print (i)

鸣谢
https://blog.csdn.net/loovelj/article/details/78739790
https://blog.csdn.net/hjxu2016/article/details/77833336
https://blog.csdn.net/sunny2038/article/details/12889059

猜你喜欢

转载自blog.csdn.net/wsp_1138886114/article/details/82945328