python - OpenCV 检测试管中的药丸数量

标签 python opencv image-processing

我有一个透明塑料管,里面正好装着 10 个黑色小球。但有时里面会有 11 或 9 颗药丸。有什么方法可以检测管中的球数。

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 here enter image description here enter image description here

最佳答案

您可能想尝试黑白图像 --> 距离变换 --> 模糊 --> 分水岭变换。这是我在 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'));

关于python - OpenCV 检测试管中的药丸数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828696/

相关文章:

python - 当模型表单传递自定义字典时, unique=True 不起作用?

python - OpenCV imread 发布 libpng 错误 : IEND: CRC error and not loading images

python - 执行增强(使用 ImageDataGenerator)并将增强图像保存为原始名称

Python Pandas - 初始化和填充 DataFrame

python - 如何使 pandas 子图中的线条变粗

c++ - cv::imwrite 与 cv::imencode 的输出

c# - 如何显示内存中服务器端存储的图像?

c++ - 从 RGB 值构建像素

python - Pandas 通过从重复的行值交换列值进行数据透视

ios - OpenCV 自适应阈值 OCR