Detect objects on a white background in Python

家住魔仙堡 提交于 2019-12-30 07:10:34

问题


I'm trying to use Python to detect how many objects are on a white surface. An example image is found at the end of this post.

I'm wondering how I should do this, mainly because the background is white and most of the time it gets detected as foreground.

What I have now in Python based on this tutorial (http://pythonvision.org/basic-tutorial) uses several libraries and detects the white as the object so count is 1, the tools get detected as background and thus are ignored:

dna = mahotas.imread('dna.jpeg')
dna = dna.squeeze()
dna = pymorph.to_gray(dna)


print dna.shape
print dna.dtype
print dna.max()
print dna.min()

dnaf = ndimage.gaussian_filter(dna, 8)
T = mahotas.thresholding.otsu(dnaf)
labeled, nr_objects = ndimage.label(dnaf > T)
print nr_objects
pylab.imshow(labeled)
pylab.jet()
pylab.show()

Are there any options for getting the white part as background and the tools as foreground?

Thanks in advance!

Example image:

The segmented image where red is foreground and blue background (the few tools merging is not a problem):


回答1:


If the shadow is not a problem

You can label the images in mahotas (http://mahotas.readthedocs.org/en/latest/labeled.html) given this binary image. You can also use skimage.morphology (which uses ndlabel as was mentioned in comments). http://scikit-image.org/docs/dev/auto_examples/plot_label.html

These are examples of connect-component algorithms and are standard in any general image processing package. ImageJ also makes this quite simple.

If the shadow is a problem

Otsu thresholding returns a single value: a pixel brightness, and all you're doing is keeping all pixels that are dimmer than this threshold. This method is getting tripped up by your shadows, so you need to try another segmentation algorithm, preferably one that does local segmentation (IE it segments small regions of the image individually.)

Adaptive or local methods don't have this problem and would be really well-suited to your image's shadows:

http://scikit-image.org/docs/dev/auto_examples/plot_threshold_adaptive.html#example-plot-threshold-adaptive-py

In mahotas there should be other segmentation methods but I'm only knowledgeable about scikit-image. If you want a serious overview on segmentation, check out this paper: https://peerj.com/preprints/671/

Full disclosure, it's my paper.



来源:https://stackoverflow.com/questions/28032722/detect-objects-on-a-white-background-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!