【问题标题】:Draw contours around objects with OpenCV使用 OpenCV 在对象周围绘制轮廓
【发布时间】:2019-11-04 18:58:04
【问题描述】:

我正在尝试在两个重叠的对象上绘制轮廓。在这里,我拍了两支笔的照片。 但它不能完美地绘制轮廓。里面有一些小轮廓。如何删除它?

这是我的原图

结果

import cv2
import numpy as np 
from matplotlib import pyplot as plt 

img = cv2.imread('img/pen001.jpg',1)

img =  cv2.cvtColor(img , cv2.COLOR_BGR2RGB)

imgray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

ret, thresh = cv2.threshold(imgray, 102 , 160, 0)

kernel = np.ones((5,5), np.float32)/10
dst = cv2.filter2D(thresh, -1, kernel)

contour1, hierarchy = cv2.findContours(dst, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img , contour1, -1, (0, 255, 0), 3 )
plt.imshow(dst)
plt.show()
plt.imshow(img)
plt.show()

【问题讨论】:

    标签: python image opencv image-processing contour


    【解决方案1】:

    这是获取轮廓的潜在方法

    • 将图像转换为灰度和模糊图像
    • 获取二值图像的阈值
    • 寻找轮廓
    • 遍历轮廓并使用最小轮廓区域进行过滤
    • 绘制轮廓

    阈值图像

    寻找轮廓

    请注意,在此图像中,检测到了笔内的小轮廓和纸张中不需要的轮廓。你的问题是如何去除里面的小轮廓。有两种解决方案。一种是使用cv2.RETR_EXTERNAL 而不是cv2.RETR_TREE,第二种是使用cv2.contourArea() 按区域过滤小轮廓。进行这些更改后,结果如下

    import cv2
    
    image = cv2.imread('1.jpg')
    blur = cv2.medianBlur(image, 9)
    gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 110 ,255, cv2.THRESH_BINARY_INV)[1]
    
    cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    
    min_area = 5000
    for c in cnts:
        area = cv2.contourArea(c)
        if area > min_area:
            cv2.drawContours(image,[c], 0, (36,255,12), 2)
    
    cv2.imshow('thresh', thresh)
    cv2.imshow('image', image)
    cv2.waitKey(0)
    

    【讨论】:

    • 哦,非常感谢。我从你那里了解到一些事情。
    • @PhucNguyen 看看this,它解释了cv2.RETR_TREEcv2.RETR_EXTERNAL 之间的区别。在尝试获取轮廓或边界框时,有许多过滤技术(例如面积、周长或边缘)会派上用场。考虑accepting 让其他人知道您的问题已解决的答案:)
    猜你喜欢
    • 2018-02-13
    • 1970-01-01
    • 2018-08-30
    • 2021-02-01
    • 2016-11-20
    • 1970-01-01
    • 2020-12-25
    • 2021-09-07
    • 2013-01-03
    相关资源
    最近更新 更多