OpenCV-Python未从图片中找到一个气泡

eqoofvh9  于 2023-01-13  发布在  Python
关注(0)|答案(1)|浏览(194)

我有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

hiz5n14c

hiz5n14c1#

这里有一种方法。我不推荐使用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

相关问题