【问题标题】:OpenCV-Python doesn't find one bubble from pictureOpenCV-Python 没有从图片中找到一个气泡
【发布时间】:2023-01-12 05:49:10
【问题描述】:

我有一张有 9 个泡泡的图片。我的任务是计算它们并输出图像中气泡的数量。首先,我尝试为图像添加高斯模糊,然后我使用 Canny 边缘检测,最后它应该绘制检测到的气泡的轮廓。但是,仍然缺少一个气泡,我真的不知道为什么。我该如何解决这个问题? 这是我的代码:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('objects.jpg', cv2.IMREAD_GRAYSCALE)
img_blur = cv2.GaussianBlur(img, (3, 3), 0)

plt.imshow(img_blur, cmap='gray')

# Canny Edge Detection
edge = cv2.Canny(img_blur, 0, 250)

fig, ax = plt.subplots(1, 2, figsize=(18, 6))
ax[0].imshow(img, cmap='gray')
ax[1].imshow(edge, cmap='gray')

(cnt, hierarchy) = cv2.findContours(
    edge.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
cv2.drawContours(rgb, cnt, -1, (0, 255, 0), 2)

plt.imshow(rgb)
print("number of objects in the image is: ", len(cnt))

这是我的输入图像:https://imgur.com/a/wKNB5jF

以及在绘制轮廓后缺少一个气泡的最终输出:https://imgur.com/a/dyAnKKV

【问题讨论】:

  • 不要使用 Canny 边缘检测。背景颜色的阈值(使用 cv2.inRange())并反转,使彩色对象在黑色背景上呈白色。然后使用形态学来关闭并去除小斑点。然后获取轮廓并计算轮廓。

标签: python opencv


【解决方案1】:

这是一种方法。我不建议使用 Canny 边缘。这就是我建议在 Python/OpenCV 中这样做的方式。

  • 读取输入
  • 背景颜色的阈值和反转
  • 应用形态学填充孔并去除小斑点
  • 获取外部轮廓并将它们绘制在输入的副本上
  • 计算轮廓的数量
  • 保存结果

输入:

import cv2
import numpy as np

# read the input
img = cv2.imread('objects.jpg')

# threshold on background color and invert
lower = (200,180,170)
upper = (240,220,210)
thresh = cv2.inRange(img, lower, upper)
thresh = 255 - thresh

# apply morphology to clean up
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)

result = img.copy()
(cnt, hierarchy) = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(result, cnt, -1, (0, 255, 0), 2)

print("number of objects in the image is: ", len(cnt))

# save results
cv2.imwrite('objects_thresh.jpg', thresh)
cv2.imwrite('objects_morph.jpg', morph)
cv2.imwrite('objects_contours.jpg', result)

# show results
cv2.imshow('thresh', thresh)
cv2.imshow('morph', morph)
cv2.imshow('result', result)
cv2.waitKey(0)

阈值图像:

形态学清理图像:

生成的轮廓图像:

number of objects in the image is:  9

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2018-01-24
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多