OpenCV__Python 轮廓检测_教程23

博客围绕OpenCV和Python的检测功能展开,虽未提供具体内容,但可推测是利用Python结合OpenCV库进行相关检测操作,在信息技术领域的图像处理等方面有应用价值。

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

#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys


#countours
def countours_detection(img):
    #(1)加滤波,能消除噪声
    dst = cv.GaussianBlur(img,(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)
   
    #contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)  #查找所有
    #只找最外面的,重要!!!
    contours,heriachy = cv.findContours(binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    #cv.drawContours(img,contours,-1,(0,0,255),2)  #画出所有
    for i,countour in enumerate(contours):
        cv.drawContours(img,contours,i,(0,0,255),2)
        #-1参数会填充掉轮廓,注意!
        #cv.drawContours(img,contours,i,(0,0,255),-1)
        print(i)
    return img
    

#edge_detection
def edge_detection(img):

    blurred = cv.GaussianBlur(img,(3,3),0)
    gray = cv.cvtColor(blurred,cv.COLOR_BGR2GRAY)
    edge_output = cv.Canny(gray,50,150)
    cv.namedWindow("canny_edge",cv.WINDOW_NORMAL)
    cv.imshow("canny_edge",edge_output)
    return edge_output


#countours2
def countours2_detection(img):  
    binary = edge_detection(img)
    #contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)  #查找所有
    #只找最外面的,重要!!!
    contours,heriachy = cv.findContours(binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    #cv.drawContours(img,contours,-1,(0,0,255),2)  #画出所有
    for i,countour in enumerate(contours):
        cv.drawContours(img,contours,i,(0,0,255),2)
        #-1参数会填充掉轮廓,注意!
        #cv.drawContours(img,contours,i,(0,0,255),-1)
        print(i)
    return img


def img_test():
    #img = cv.imread('E:/chenopencvblogimg/lena.jpg')
    #img = cv.imread('E:/chenopencvblogimg/star.png')
    img = cv.imread('E:/chenopencvblogimg/circle.png')
    #判断是否读取成功
    if img is None:
        print("Could not read the image,may be path error")
        return
    cv.namedWindow("origin Pic",cv.WINDOW_NORMAL)
    cv.imshow("origin Pic",img)
    #countours_detection(img)
    
    img_show = countours_detection(img)
    cv.namedWindow("countours_detection",cv.WINDOW_NORMAL)
    cv.imshow("countours_detection",img_show)

    img_show = countours2_detection(img)
    cv.namedWindow("countours2_detection",cv.WINDOW_NORMAL)
    cv.imshow("countours2_detection",img_show)

    
    #让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
    cv.waitKey(0)
    #销毁窗口
    cv.destroyAllWindows()

if __name__ == '__main__':
    sys.exit(img_test() or 0)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值