这里是“PythonOpencv轮廓常用操作代码实例解析”的完整攻略:
一、轮廓概述
轮廓是图像分析中的基本概念,在计算机视觉中是指将连续的边缘连接起来形成的曲线,轮廓可以被用来识别物体的形状,并在图像中分割出物体。
二、轮廓的基本操作
1.读取并显示图像
import cv2
image = cv2.imread("example.jpg") # 读取图像
cv2.imshow("image", image) # 显示图像
cv2.waitKey(0) # 等待按键
2.转换为灰度图像
import cv2
image = cv2.imread("example.jpg") # 读取图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
cv2.imshow("gray", gray) # 显示灰度图像
cv2.waitKey(0) # 等待按键
3.二值化
import cv2
image = cv2.imread("example.jpg") # 读取图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 二值化
cv2.imshow("binary", binary) # 显示二值化图像
cv2.waitKey(0) # 等待按键
4.边缘检测
import cv2
image = cv2.imread("example.jpg") # 读取图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 二值化
edges = cv2.Canny(binary, 30, 150) # 边缘检测
cv2.imshow("edges", edges) # 显示边缘图像
cv2.waitKey(0) # 等待按键
5.轮廓提取
import cv2
image = cv2.imread("example.jpg") # 读取图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 二值化
edges = cv2.Canny(binary, 30, 150) # 边缘检测
_, contours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # 轮廓提取
cv2.drawContours(image, contours, -1, (0, 0, 255), 2) # 绘制轮廓
cv2.imshow("contours", image) # 显示轮廓图像
cv2.waitKey(0) # 等待按键
三、示例说明
示例一:检测并标记图像中的瓶盖
import cv2
image = cv2.imread("cap.jpg") # 读取图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
_, binary = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY) # 二值化
edges = cv2.Canny(binary, 120, 240) # 边缘检测
_, contours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # 轮廓提取
max_area = 0
max_contour = None
for contour in contours:
area = cv2.contourArea(contour)
if area > max_area:
max_area = area
max_contour = contour
if max_contour is not None:
cv2.drawContours(image, [max_contour], -1, (0, 0, 255), 2)
cv2.imshow("cap", image)
cv2.waitKey(0)
示例二:检测并标记图像中的手写字母
import cv2
image = cv2.imread("letters.jpg") # 读取图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 二值化
edges = cv2.Canny(binary, 30, 150) # 边缘检测
_, contours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # 轮廓提取
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if 10 < h < 100 and 10 < w < 100:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imshow("letters", image)
cv2.waitKey(0)
至此,完整的“PythonOpencv轮廓常用操作代码实例解析”的攻略已经介绍完毕。