python图像检测_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: 轮廓点移动的偏移量

"""

示例:检测下图中的轮廓

ubuntu_005.png

#!/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()

ubuntu_004.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值