-1

这个问题是我之前 2 个问题的后续问题:Python Image tutorial works, other images 表现不同(使用 Pylab 显示图像)Detect objects on a white background in Python

我想要实现的是能够以编程方式计算白色背景上单个对象的数量。正如在其他 2 篇文章中看到的那样,我已经能够在某种程度上实现这一目标。此刻,当图像上几乎没有阴影时,我能够计算对象的数量。我试图分析的图像(这篇文章的底部)确实有一些阴影,这些阴影会导致对象合并并被视为一个单独的对象。

我需要一些简单的方法来消除阴影,我已经尝试使用 scikit-image 进行自适应阈值处理(http://scikit-image.org/docs/dev/auto_examples/plot_threshold_adaptive.html#example-plot-threshold-adaptive- py),但我偶然发现了一些问题(https://imgur.com/uYnj6af)。有什么不太复杂的方法可以让它工作吗?我以前的帖子中已经有很多代码,但是如果您想查看任何其他代码,请告诉我!

提前致谢。

在此处输入图像描述

4

1 回答 1

3

也许对二进制图像进行操作更容易。在下面的代码中,我通过计算滑动窗口上的方差并对其进行阈值化来获得这样的图像。

方差图的二进制阈值

from skimage import io, exposure, color, util
import matplotlib.pyplot as plt

image = color.rgb2gray(io.imread('tools.jpg'))

exposure.equalize_adapthist(image)
Z = util.view_as_windows(image, (5, 5))
Z = Z.reshape(Z.shape[0], Z.shape[1], -1)
variance_map = Z.var(axis=2)

plt.imshow(variance_map > 0.005, cmap='gray')
plt.savefig('tools_thresh.png')

plt.show()

更新

在此处输入图像描述

该代码的扩展版本标识了 8 个工具。

from skimage import io, exposure, color, util, measure, morphology
from scipy import ndimage as ndi
import numpy as np
import matplotlib.pyplot as plt

image = color.rgb2gray(io.imread('tools.jpg'))

exposure.equalize_adapthist(image)
Z = util.view_as_windows(image, (5, 5))
Z = Z.reshape(Z.shape[0], Z.shape[1], -1)
variance_map = Z.var(axis=2)

tools_bw = variance_map > 0.005
tools_bw = morphology.binary_closing(tools_bw, np.ones((5, 5)))
tools_bw = ndi.binary_fill_holes(tools_bw)


labels = measure.label(tools_bw)
regions = measure.regionprops(labels)
regions = [r for r in regions if r.perimeter > 500 and r.major_axis_length > 200]

print(len(regions))

out = np.zeros_like(tools_bw, dtype=int)
for i, r in enumerate(regions):
    out[labels == r.label] = i + 1

plt.imshow(out, cmap='spectral')
plt.savefig('tools_identified.png', bbox_inches='tight')

plt.show()
于 2015-01-21T03:26:21.797 回答