opencv学习笔记(15)轮廓发现

参考:python-opencv2利用cv2.findContours()函数来查找检测物体的轮廓
试验用图:
在这里插入图片描述

1.图像二值化寻找边缘

#coding=UTF-8
import cv2 as cv
import numpy as np

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_INV|cv.THRESH_OTSU)
    #binary = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,9,4)
    cv.imshow("binary",binary)
    cloneImage,contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
    for i,contour in enumerate(contours):
        cv.drawContours(image,contours,i,(0,255,0),2)
    cv.imshow("detect contours",image)
    
    

scr = cv.imread("D:/academic/picture/opencv_data/pic3.png")
cv.imshow("input image",scr)
contours_demo(scr)
cv.waitKey(0)
cv.destroyAllWindows()

效果:
在这里插入图片描述

tips:
1.如果二值化之后的图像的底色是白色,那么最后的绘图会把整张图片框进去,如图所示(第三章图片的边框是绿色的):
在这里插入图片描述
2.

cloneImage,contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)

这行代码因opencv版本而异,opencv2.x和4.x只需要写成

contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)

而opencv3.x要写成第一行那种。

2.canny边缘检测寻找边缘

#coding=UTF-8
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)
    grad_x = cv.Sobel(gray,cv.CV_16SC1,1,0)
    grad_y = cv.Sobel(gray,cv.CV_16SC1,0,1)
    #edge_output = cv.Canny(image,50,150)
    # canny的高低阈值比例一般为1213
    edge_output = cv.Canny(grad_x,grad_y,50,150)
    return edge_output

def contours_demo(image):
    binary = edge_demo(image)
    cv.imshow("binary",binary)
    cloneImage,contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
    for i,contour in enumerate(contours):
        cv.drawContours(image,contours,i,(0,255,0),2)
    cv.imshow("detect contours",image)
    
    

scr = cv.imread("D:/academic/picture/opencv_data/pic3.png")
cv.imshow("input image",scr)
contours_demo(scr)
cv.waitKey(0)
cv.destroyAllWindows()

效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值