OpenCV自学笔记4:轮廓检测

轮廓检测

引言
在计算机视觉中,轮廓检测是一个十分重要的任务。与边缘不同,图像中的轮廓包含更多的实际意义。OpenCV提供了 findContours() 函数和 drawContours() 函数实现轮廓的检测和绘制

————————————————————

OpenCV轮廓检测的例子

# -*- coding:utf-8 -*-

import cv2

# Step1. 读入图像
image = cv2.imread('images/leaf.png', 0)

# Step2. 二值化
ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# Step3. 轮廓提取
image, contour, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Step4. 轮廓绘制
color = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
dst = cv2.drawContours(color, contour, -1, (0,255,0), 2)

cv2.imshow("dst", dst)

cv2.waitKey(0)

关于findContours()和drawContours()的参数介绍,请移步这篇博文

程序的运行结果如下:

这里写图片描述

————————————————————

边界框、最小矩形区域、最小闭圆

# -*- coding:utf-8 -*-

import cv2
import numpy as np

# Step1. 读入图像
image = cv2.imread('images/shape.jpg', 0)

# Step2. 二值化
ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# Step3. 轮廓提取
image, contour, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Step4. 绘制边界框
color = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)

for c in contour:
    # 绘制边界框
    x,y,w,h = cv2.boundingRect(c)# 将轮廓信息转化为(x,y)坐标,并返回宽和高
    # rectangle有四个参数:要绘制的图像,左上角坐标,右下角坐标,颜色,轮廓宽度(这里为2)
    cv2.rectangle(color, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # 绘制最小矩形区域
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect) # 获得矩形四个角的坐标, 返回浮点型
    box = np.int0(box) # 把浮点型转化为整型
    cv2.drawContours(color, [box], 0, (0, 255, 0), 3)

    # 绘制最小闭圆
    (x, y), radius = cv2.minEnclosingCircle(c)
    center = (int(x), int(y))
    radius = int(radius)
    cv2.circle(color, center, radius, (0, 255, 0), 1)

    # 绘制最小外包三角形
    retval, points = cv2.minEnclosingTriangle(c)

    for i in range(0, 3):
        # 这里使用了一个小技巧, 从i 绘制到 (i + 1) % 3        
        cv2.line(color, tuple(points[i][0]), tuple(points[(i + 1) % 3][0]), (0, 255, 0), 2) 

cv2.imshow("dst", color)

cv2.waitKey(0)

程序的运行结果如下:

这里写图片描述

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值