【opencv学习笔记 23轮廓发现】

本文介绍了一种基于图像边缘提取的轮廓发现方法,通过使用Canny边缘检测算法和轮廓追踪技术,有效地找到图像中对象的边界。文章详细展示了如何利用Python的OpenCV库进行边缘检测,并进一步提取图像中的轮廓。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

轮廓发现

是基于图像边缘提取的基础寻找对象轮廓的方法。所以边缘提取阈值的选定会影响最终轮廓发现的结果。
利用梯度来避免阈值的烦恼

相关代码

import cv2 as cv


def edge_demo(image):
    """
    边缘处理
    :param image:
    :return:
    """
    blurred = cv.GaussianBlur(image, (3, 3), 0)
    gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
    # X Gradient
    xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0)
    # Y Gradient
    ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1)
    # edge
    # edge_output = cv.Canny(xgrad, ygrad, 50, 150)
    edge_output = cv.Canny(gray, 30, 100)
    cv.imshow("Canny Edge", edge_output)
    return edge_output


def contours_demo(image):
    binary = edge_demo(image)
    # 查找轮廓 这里最新的返回值只有两个
    contours, heriachy = cv.findContours(binary, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
    for i, contour in enumerate(contours):
        #                                               2为绘图的线宽 可以设定为-1表示填充整个轮廓
        cv.drawContours(image, contours, i, (0, 0, 255), -1)
        approxCurve = cv.approxPolyDP(contour, 4, True)
        if approxCurve.shape[0] > 6:
            cv.drawContours(image, contours, i, (0, 255, 255), 2)
        if approxCurve.shape[0] == 4:
            cv.drawContours(image, contours, i, (255, 255, 0), 2)
        print(approxCurve.shape[0])
        print(i)
    cv.imshow("detect contours", image)


src = cv.imread("main.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
contours_demo(src)
cv.waitKey(0)

cv.destroyAllWindows()

结果展示

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值