python+opencv 轮廓发现(基于二值图像)

轮廓发现实基于图像边缘提取的基础寻找对象轮廓的方法。所以边缘提取的阈值选定会影响最终轮廓发现的结果。

API介绍:

1、——findContours   发现轮廓

2、——drawContours    绘制轮廓

cv.RETR_TREE,外轮廓内部的轮廓也会标记

cv.RETR_EXTERNAL,只标记外轮廓

import cv2 as cv
import numpy as np


def edge_demo(image):
    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, 50, 150)
    cv.imshow('Canny Edge', edge_output)
    return edge_output


def contours_demo(image):
    # dst = cv.GaussianBlur(image, (3, 3), 0)
    # gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
    # ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    # cv.imshow('binary image', binary)
    binary = edge_demo(image)

    contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    for i, contour in enumerate(contours):
        # 最后一个参数是像素值,设为-1时,会将整个轮廓都填充为相应的颜色
        cv.drawContours(image, contours, i, (0, 0, 255), -1)
        print(i)
    cv.imshow('detect contours', image)


src = cv.imread('C:/Users/Y/Pictures/Saved Pictures/coins.jpg')
cv.namedWindow('input image', cv.WINDOW_AUTOSIZE)
cv.imshow('input image', src)
contours_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()

 

第四幅图和第五幅图是没有提取边缘得到的图像,第二幅图和第三幅图是上述代码运行得到的图像。

发布了70 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Acmer_future_victor/article/details/104153667