基于OpenCV的排针弯针检测方法及实现代码
排针弯针检测需求
我有一张排针的图片,需要使用OpenCV检测其中是否存在弯针。

更新:问题已解决
感谢Nick的帮助,我实现了一个效果不错的方案,虽不完美但可用!
核心思路:使用findContours函数查找图像中所有轮廓,遍历每个轮廓并通过minAreaRect计算最小外接矩形,绘制对应尺寸的矩形框。当矩形框宽度超过设定阈值时,判定该排针为弯针(不符合规格)。
for (const auto &entry: fs::directory_iterator(SAMPLES)) { try { // 加载源图像 src = imread(entry.path(), IMREAD_COLOR); // 中值模糊处理 medianBlur(src, blurred, 3); // 二值化阈值处理 threshold(blurred, blurred, 100, 255, cv::THRESH_BINARY); // Canny边缘检测 Canny(blurred, detected_edges, thres1, thres2, 3); // imshow("blurred", blurred); vector<vector<Point>> contours; // 查找图像中所有轮廓 findContours(detected_edges, contours, RETR_TREE, CHAIN_APPROX_SIMPLE); vector<RotatedRect> minRect(contours.size()); vector<vector<Point>> contours_poly(contours.size()); vector<Rect> boundRect(contours.size()); int bendPins = 0; for (size_t i = 0; i < contours.size(); i++) { // 绑定轮廓对应的形状数据到向量 minRect[i] = minAreaRect(contours[i]); approxPolyDP(contours[i], contours_poly[i], 3, true); boundRect[i] = boundingRect(contours_poly[i]); // 绘制外接矩形框 Rect rect(boundRect[i].tl(), boundRect[i].br()); rectangle(src, rect, Scalar(0, 0, 255), 2); // 判定弯针:矩形宽度超过阈值则标记 if (rect.width > threshold_bend) { Point centerRect = (boundRect[i].br() + boundRect[i].tl()) * 0.5; circle(src, centerRect, 20, Scalar(255, 0, 255), 2); bendPins++; } // 绘制最小外接矩形的四条边 Point2f rect_points[4]; minRect[i].points(rect_points); for (int j = 0; j < 4; j++) { line(src, rect_points[j], rect_points[(j + 1) % 4], Scalar(0, 255, 255), 1); } } char buffer[100]; snprintf(buffer, 100, "发现弯针数量: %d", bendPins); putText(src, buffer, Point(10, 25), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(255, 255, 255), 2); imshow(entry.path().filename(), src); waitKey(); } catch (const std::exception &e) { cout << e.what() << endl; } }
检测结果

内容的提问来源于stack exchange,提问作者Stefan de Kraker
相关产品推荐
相关产品推荐

