Advertisement

Python OpenCV-物体轮廓检测

阅读量:

cv2.findContours() 函数检测轮廓

复制代码
    import cv2
    img = cv2.imread('C:/Users/Administrator/Desktop/New_Study/IMAGE/Pictures/1.jpg')  
     
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  
    ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)  
     
    contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)  
    cv2.drawContours(img,contours,-1,(0,0,255),3)  
     =
    cv2.imshow("img", img)  
    
    cv2.imwrite('C:/Users/Administrator/Desktop/New_Study/IMAGE/Pictures/findContours.jpg',img)
    
    cv2.waitKey(0)  
    
    
    bash
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-07-13/48DqGtpurIXZYzEcCdWoy3iwxTMK.png)
在这里插入图片描述
在这里插入图片描述

2.cv2.Canny()函数检测轮廓

复制代码
    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    img = cv2.imread('C:/Users/Administrator/Desktop/New_Study/IMAGE/Pictures/1.jpg',1)
    edges = cv2.Canny(img,100,200)
    
    #Matplotlib显示
    plt.figure(figsize=(12,8))
    plt.subplot(121)
    plt.imshow(img,cmap='gray')
    plt.title('original')
    plt.xticks([])
    plt.yticks([])
    
    plt.subplot(122)
    plt.imshow(edges,cmap='gray')
    plt.title('edge')
    plt.xticks([])
    plt.yticks([])
    
    plt.show()
    
    #OpenCV 显示
    img = cv2.imread('C:/Users/Administrator/Desktop/New_Study/IMAGE/Pictures/1.jpg')
    edges = cv2.Canny(img,100,200)
    cv2.namedWindow('img',cv2.WINDOW_NORMAL)
    cv2.imshow('img',img)
    cv2.namedWindow('edges',cv2.WINDOW_NORMAL)
    cv2.imshow('edges',edges)
    
    cv2.waitKey()
    cv2.destroyAllWindows()
    
    
    bash
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-07-13/DVnIlMj0OS7H5xGJ8qdpEtkCeTQh.png)

在这里插入图片描述

不建议用Matplotlib展示图像,失真严重,效果如下图

在这里插入图片描述

特别注明

全部评论 (0)

还没有任何评论哟~