我正在做一个项目,我必须检查药品泡罩包装是否有缺失的药片。
我正在尝试使用 opencv 的 matchTemplate 函数。让我展示代码,然后展示一些结果。
int match(string filename, string templatename)
{
Mat ref = cv::imread(filename + ".jpg");
Mat tpl = cv::imread(templatename + ".jpg");
if (ref.empty() || tpl.empty())
{
cout << "Error reading file(s)!" << endl;
return -1;
}
imshow("file", ref);
imshow("template", tpl);
Mat res_32f(ref.rows - tpl.rows + 1, ref.cols - tpl.cols + 1, CV_32FC1);
matchTemplate(ref, tpl, res_32f, CV_TM_CCOEFF_NORMED);
Mat res;
res_32f.convertTo(res, CV_8U, 255.0);
imshow("result", res);
int size = ((tpl.cols + tpl.rows) / 4) * 2 + 1; //force size to be odd
adaptiveThreshold(res, res, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, size, -128);
imshow("result_thresh", res);
while (true)
{
double minval, maxval, threshold = 0.8;
Point minloc, maxloc;
minMaxLoc(res, &minval, &maxval, &minloc, &maxloc);
if (maxval >= threshold)
{
rectangle(ref, maxloc, Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows), CV_RGB(0,255,0), 2);
floodFill(res, maxloc, 0); //mark drawn blob
}
else
break;
}
imshow("final", ref);
waitKey(0);
return 0;
}
这里有一些图片。
一个好的泡罩包装的“样品”图像:
从“样本”图像裁剪的模板:
“样本”图像的结果:
检测到此包装中缺少的平板电脑:
但这里有问题:
我目前不知道为什么会发生这种情况。任何建议和/或帮助表示赞赏。
我遵循和修改的原始代码在这里: http: //opencv-code.com/quick-tips/how-to-handle-template-matching-with-multiple-occurences/