我有一个透明的塑料管,应该包含10个黑色小球。但有时会有11或9粒药片。有没有办法检测管中的球数。
现在使用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()
我得到一张黑白图像以获得更好的对比度。
我尝试计算黑色像素的数量,然后将其除以一个数字以获得球的数量。但由于有许多球相互重叠,无论我如何调整这个数字,它都无法正常工作。
还有其他方法来计算它们。
以下是更多示例:
答案 0 :(得分:7)
你可能想尝试黑白图像 - >距离变换 - >模糊 - >分水岭变换。这是我在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'));