Python-OpenCV中的图像轮廓检测


  主要记录Python-OpenCV中的cv2.findContours()方法;官方文档


cv2.findContours()

  在二值图像中寻找图像的轮廓;与cv2.drawubgContours()配合使用;

# 方法中使用的算法来源
Satoshi Suzuki and others. Topological structural analysis of digitized binary images by border following. Computer Vision, Graphics, and Image Processing, 30(1):32–46, 1985.
def findContours(image, mode, method, contours=None, hierarchy=None, offset=None):
"""
检测二值图像的轮廓信息
Argument:
	image: 待检测图像
	mode: 轮廓检索模式
	method: 轮廓近似方法
	contours: 检测到的轮廓;每个轮廓都存储为点矢量
	hierarchy: 
	offset: 轮廓点移动的偏移量
"""

示例:检测下图中的轮廓

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time    : 19-4-20 下午6:29
# @Author  : chen

import cv2
import matplotlib.pyplot as plt

image = cv2.imread("input_01.png")
image_BGR = image.copy()

# 将图像转换成灰度图像,并执行图像高斯模糊,以及转化成二值图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5,5), 0)
image_binary = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]

# 从二值图像中提取轮廓
# contours中包含检测到的所有轮廓,以及每个轮廓的坐标点
contours = cv2.findContours(image_binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

# 遍历检测到的所有轮廓,并将检测到的坐标点画在图像上
# c的类型numpy.ndarray,维度(num, 1, 2), num表示有多少个坐标点
for c in contours:
    cv2.drawContours(image, [c], -1, (255, 0, 0), 2)

image_contours = image

# display BGR image
plt.subplot(1, 3, 1)
plt.imshow(image_BGR)
plt.axis('off')
plt.title('image_BGR')

# display binary image
plt.subplot(1, 3, 2)
plt.imshow(image_binary, cmap='gray')
plt.axis('off')
plt.title('image_binary')

# display contours
plt.subplot(1, 3, 3)
plt.imshow(image_contours)
plt.axis('off')
plt.title('{} contours'.format(len(contours)))

plt.show()

posted @ 2019-04-20 20:25  chenzhen0530  阅读(7686)  评论(0编辑  收藏  举报