OpenCV检测管中的药丸数量 [英] OpenCV detect the number pills in a tube

查看:414
本文介绍了OpenCV检测管中的药丸数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个透明的塑料管,应该包含10个黑色小球。但有时会有11或9粒药片。有没有办法检测管中的球数。

I have a transparent plastic tube that shall contain exactly 10 black little balls. But sometimes there will be 11 or 9 pills in there. Is there any way to detect the number of balls in the tube.

现在使用 cv2 ,我能做的最好的是:

Now with cv2, the best I can do is the following:

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()

我得到一张黑白图像以获得更好的对比度。

I get a black and white image for a better contrast.

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

I tried to count the number of black pixels then divide it by a number to get the number of balls. But since there are many balls overlapping each other, it doesn't work well no matter how I tune that number.

还有其他方法来计算它们。

Is there any other way to count them.

以下是更多示例:

推荐答案

您可能想尝试黑色 - 白色图像 - >距离变换 - >模糊 - >分水岭变换。这是我在MATLAB中得到的结果

You might want to try black-white image --> distance transform --> blur --> watershed transform. Here is the result I got in MATLAB

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'));

这篇关于OpenCV检测管中的药丸数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆