2017-03-16 82 views
1

我有一个透明的塑料管,应该包含正好10个黑色的小球。但有时在那里会有11或9粒药片。有没有什么方法可以检测管中球的数量。OpenCV检测管中的药丸数

enter image description here

现在有了cv2,我能做的最好的是:

import cv2 
import numpy as np 

original = cv2.imread("d.jpg", cv2.IMREAD_GRAYSCALE) 
retval, image = cv2.threshold(original, 50, 255, cv2.THRESH_BINARY) 

cv2.imshow('image',image) 
cv2.waitKey(0) 
cv2.destroyAllWindows() 

我得到更好的对比度黑白图像。

enter image description here

我试图计算黑色像素的数目,然后由数除以它得到球的数量。但是由于有很多球互相重叠,无论我如何调整这个数字,它都不能很好地工作。

有没有其他的方法来计算它们。

下面是更多的例子:

enter image description hereenter image description hereenter image description here

回答

6

你可能想尝试黑白图像 - >距离变换 - >模糊 - >分水岭变换。下面是我在MATLAB中有

enter image description here

im=imread('tube.png'); 

% Transform 
im=rgb2gray(im); 

% Threshold 
im=im>80; 
im=imclose(im,strel('disk',2)); 
im=bwareaopen(im,10); 

figure, 
subplot(121); 
imshow(im,[]);axis image;colormap gray 

% Distance transform 
imb=bwdist(im); 

% Blur 
sigma=4; 
kernel = fspecial('gaussian',4*sigma+1,sigma); 
im2=imfilter(imb,kernel,'symmetric'); 

% Watershed transform 
L = watershed(max(im2(:))-im2); 

% Plot 
lblImg = bwlabel(L&~im); 

subplot(122); 
imshow(label2rgb(lblImg,'jet','k','shuffle')); 
+4

本[OpenCV的教程](http://docs.opencv.org/3.2.0/d3/db4/tutorial_py_watershed.html)的结果说明了如何用Python中的OpenCV做到这一点。 – Miki