今天在一个视觉群里看到有人问木板计数的事情,图片是这样的:
群里的大神勇哥给出了halcon的方法 灰度投影:
这里还有大神 详细介绍灰度投影的运用的文章,非常不错的思路,opencvsharp有没有相同的函数呢,网上找了找都是遍历像素的,其实遍历像素也可以实现,但如果有现成的函数更高效一些,最后还真找到了一个相似的:Reduce,先看效果:
OK,Talk is cheap. Show me the code:
public void Run()
{
Mat src = Cv2.ImRead("./Data/Image/ji2.jpg", ImreadModes.Grayscale);
Cv2.Resize(src, src, new(600, 400));
Cv2.ImShow("src", src);
Mat dst = new();
Mat dstColumn = new();
Cv2.Reduce(src, dst, ReduceDimension.Row, ReduceTypes.Avg, -1);
// Cv2.ImShow("dst", dst);
Cv2.Reduce(dst, dstColumn, ReduceDimension.Column, ReduceTypes.Avg, -1);
var width = dstColumn.Get<byte>(0, 0);
Mat hist = new Mat(new Size(dst.Width, 256), MatType.CV_8UC1, new Scalar(0));
for (int i = 0; i < dst.Width; i++)
{
var len = dst.Get<byte>(0, i);
Cv2.Line(hist, i, 255, i, 256 - len, new Scalar(255));
}
Mat submat = hist[0, 256-width, 0, hist.Width];
var Cc = Cv2.ConnectedComponentsEx(submat);
if (Cc.LabelCount < 2)
return;
Cc.RenderBlobs(submat);
List<ConnectedComponents.Blob> BlobList = new();
foreach (var blob in Cc.Blobs.Skip(1))
{
if (blob.Area < 100) continue;
BlobList.Add(blob);
}
submat.PutText("find: " + (BlobList.Count), new(10, 20), HersheyFonts.HersheySimplex, 0.5d, Scalar.White, 1); ;
Mat histColor = hist.CvtColor(ColorConversionCodes.GRAY2BGR);
histColor[0, submat.Height, 0, submat.Width] = submat;
Cv2.ImShow("histColor", histColor);
Cv2.WaitKey();
}