【发布时间】:2018-12-05 10:36:55
【问题描述】:
为了计算图像中的圆形物体,我想使用分水岭算法。 为了了解它是如何工作的以及如何使用它来满足我的需求,我在 python 中搜索了一些工作示例 (https://docs.opencv.org/3.1.0/d3/db4/tutorial_py_watershed.html ; http://scikit-image.org/docs/dev/auto_examples/segmentation/plot_label.html)
我终于找到了一个可行的解决方案,它或多或少地为我自己的目的开箱即用 (How to define the markers for Watershed in OpenCV?)
使用此代码,我得到了很好的结果,无论是使用示例文件还是使用我自己的图像。 在分水岭分析之后,我确实得到了一个奇怪的行为。出于某种原因,分水岭步骤还在图像周围添加了边框。因此,在检测到的对象旁边,图像的整个边缘也会被检测到并着色。
我的猜测是我应该更改代码中的参数以阻止这种情况发生,但到目前为止我无法找到我应该做什么。
这是代码:
import cv2
import numpy as np
from scipy.ndimage import label
def segment_on_dt(a, img):
border = cv2.dilate(img, None, iterations=3)
border = border - cv2.erode(border, None)
dt = cv2.distanceTransform(img, cv2.DIST_L2, 3)
dt = ((dt - dt.min()) / (dt.max() - dt.min()) * 255).astype(np.uint8)
_, dt = cv2.threshold(dt, 200, 255, cv2.THRESH_BINARY)
lbl, ncc = label(dt)
# Completing the markers now.
lbl[border == 255] = 255
lbl = lbl.astype(np.int32)
cv2.watershed(a, lbl)
lbl[lbl == -1] = 0
lbl = lbl.astype(np.uint8)
return 255 - lbl
# Load image file
img = cv2.imread('coins.jpg')
# Pre-processing.
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_gray = cv2.GaussianBlur(img_gray,(5,5),0)
width, height = img_gray.shape
_, img_bin = cv2.threshold(img_gray, 0, 255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
img_bin = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN,np.ones((5, 5), dtype=int))
result = segment_on_dt(img, img_bin)
result[result != 255] = 0
result = cv2.dilate(result, None)
img[result == 255] = (0, 0, 255)
cv2.imwrite('Img_output.png',img)
运行这段代码会给出这个结果(至少在我的电脑上)
检测硬币的结果对于我的目的来说已经足够了,但我对也检测到的图像边缘有点困惑。从我在调试过程中看到的情况来看,分水岭增加了这一优势,但我不清楚为什么会发生这种情况。
【问题讨论】: