首页 > 解决方案 > 从图像中提取对象

问题描述

我已经使用inRange函数删除了图像中除了两个对象之外的所有组件。有什么方法可以从图像中单独提取对象?我尝试使用HoughCircle但得到的结果非常不一致。

没有 inRange 功能(原图)

与霍夫圆 与霍夫圆

标签: opencvdeep-learningobject-detection

解决方案


cv::findContours似乎很适合这里:

img = cv.imread('images/suawk.png')

search = cv.dilate(img, cv.getStructuringElement(cv.MORPH_RECT, (5,5)))
search = cv.cvtColor(search, cv.COLOR_BGR2GRAY)
contours, _ = cv.findContours(search, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
bboxes = [cv.boundingRect(c) for c in contours]

fig, axes = plt.subplots(1, sum(rect[2]*rect[3] > 250 for rect in bboxes))
fig.set_size_inches([12,3])
fig.tight_layout()
figi = 0
for i in range(len(contours)):
    rect = cv.boundingRect(contours[i])
    area = rect[2] * rect[3]
    if area < 250:
        continue

    obj = img[rect[1]:rect[1]+rect[3]+1, rect[0]:rect[0]+rect[2]+1, :]
    obj = cv.cvtColor(obj, cv.COLOR_BGR2RGB)
    axes[figi].imshow(obj)
    figi += 1

fig.show()

对象

我在 findContours 之前做了一次膨胀,这样我得到的轮廓碎片更少。我丢弃所有边界框小于 250px 的轮廓以减少噪点。


推荐阅读