轮廓检测
引言
在计算机视觉中,轮廓检测是一个十分重要的任务。与边缘不同,图像中的轮廓包含更多的实际意义。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)
程序的运行结果如下: