【OpenCV】12 图像轮廓
图像轮廓:具有相同颜色或相同强度的连续点的曲线。
作用:
- 图形分析
- 物体的识别和检测
注意点:
- 为了检测准确性,需要先对图像进行二值化或者Canny操作
- 画轮廓时会修改输入图像
mode
RETR_EXTERNAL = 0 只检测外轮廓

RETR_LIST = 1 检测的轮廓不建立等级关系
从里到外,从右到左

RETR_CCOMP = 2 每层最多两级

RETR_TREE = 3 按树形存储轮廓

import cv2
import numpy as np
cat = cv2.imread('img/maodie.jpg')
cat_gray = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
ret, cat_binary = cv2.threshold(cat_gray, 210, 255, cv2.THRESH_BINARY)
# 寻找最外层轮廓
contours, hierarchy = cv2.findContours(cat_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
# contourIdx -1 绘制所有轮廓
# thickness 线宽 -1 全部填充
cv2.drawContours(cat_binary, contours, -1, (0, 0, 255), 1)
# 计算面积
area = cv2.contourArea(contours[0])
print("area=%d"%(area))
# 计算周长
len = cv2.arcLength(contours[0], True)
print("len=%d"%(len))
cv2.imshow('cat', cat)
cv2.imshow('cat_binary', cat_binary)
cv2.waitKey(0)
多边形逼近和凸包
import cv2
import numpy as np
def drawShape(src, points):
i = 0
while i < len(points):
if i== len(points) - 1:
x, y = points[i][0]
x1, y1 = points[0][0]
cv2.line(src, (x, y), (x1, y1), (0, 0, 255), 3)
else:
x, y = points[i][0]
x1, y1 = points[i+1][0]
cv2.line(src, (x, y), (x1, y1), (0, 0, 255), 3)
i = i + 1
cat = cv2.imread('img/maodie.jpg')
cat_gray = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
ret, cat_binary = cv2.threshold(cat_gray, 210, 255, cv2.THRESH_BINARY)
# 寻找最外层轮廓
contours, hierarchy = cv2.findContours(cat_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
# contourIdx -1 绘制所有轮廓
# thickness 线宽 -1 全部填充
cv2.drawContours(cat_binary, contours, -1, (0, 0, 255), 1)
e = 5
approx = cv2.approxPolyDP(contours[0], e, True)
drawShape(cat, approx)
# 绘制凸包
hull = cv2.convexHull(contours[0])
drawShape(cat, hull)
cv2.imshow('cat', cat)
cv2.imshow('cat_binary', cat_binary)
cv2.waitKey(0)
外接矩形

import cv2
import numpy as np
def drawShape(src, points):
i = 0
while i < len(points):
if i== len(points) - 1:
x, y = points[i][0]
x1, y1 = points[0][0]
cv2.line(src, (x, y), (x1, y1), (0, 0, 255), 3)
else:
x, y = points[i][0]
x1, y1 = points[i+1][0]
cv2.line(src, (x, y), (x1, y1), (0, 0, 255), 3)
i = i + 1
cat = cv2.imread('img/maodie.jpg')
cat_gray = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
ret, cat_binary = cv2.threshold(cat_gray, 210, 255, cv2.THRESH_BINARY)
# 轮廓查找
contours, hierarchy = cv2.findContours(cat_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 最小外接矩阵
r = cv2.minAreaRect(contours[1])
box = cv2.boxPoints(r)
box = np.array(box, dtype=np.int32)
cv2.drawContours(cat, [box], 0, (0, 0, 255), 2)
# 最大外接矩形
x, y, w, h = cv2.boundingRect(contours[1])
cv2.rectangle(cat, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('cat', cat)
cv2.imshow('cat_binary', cat_binary)
cv2.waitKey(0)
浙公网安备 33010602011771号