33,322
社区成员




#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace cv;
double startx = 2752.02; //模板图片圆心位置。阈值15:x =2752.32、x =2750.5;阈值20:x =2752.26、x =2753.取均值
int main()
{
Mat ym = imread("_8_1_1.bmp", 0); //初始位置检测掩膜图片
Mat curimg = imread("8.bmp", 0); //待检测模板图片
Mat ymfz(curimg.size(), CV_8UC1, Scalar(255));
//掩膜复制
for (int k = 0; k < curimg.rows; ++k)
{
for (int j = 0; j < curimg.cols; ++j)
{
if (ym.at<uchar>(k, j) == 255)
{
ymfz.at<uchar>(k, j) = curimg.at<uchar>(k, j);
}
}
}
//阈值分割
threshold(ymfz, ymfz, 15, 255, THRESH_BINARY);
//提取轮廓
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(ymfz, contours, hierarchy, CV_RETR_TREE, CHAIN_APPROX_NONE);
drawContours(ymfz, contours, -1, 122, 2);
cout << "contours.size()=" << contours.size() << endl;
cvtColor(ymfz, ymfz, CV_GRAY2BGR);
//圆拟合(图片尺寸5496*3672)
int i = 0;
int n = 0;
double sumx = 0;
for (;i <= contours.size();)
{
if (i >= contours.size() || i < 0) {
cout << "break" << endl;
break; //避免vector下标越界
}
float radius;
Point2f center;
minEnclosingCircle(contours[i], center, radius);
//判断是否为目标圆
if (radius > 40 && radius < 70) {
cout << "i=" << i << endl;
cout << "radius =" << radius << endl;
cout << "x =" << center.x << endl;
cout << "y =" << center.y << endl;
sumx += center.x;
circle(ymfz, center, static_cast<int>(radius), Scalar(0,0,255), 1);
imwrite("res.bmp", ymfz);
n++;
}
i++;
}
double dx = sumx/n - startx; //dx>0,圆心右偏,相机左偏,坐标系原点y值 减小
cout << "机械手偏移:" << abs(dx) << endl;
if (abs(dx) < 1) {
cout << "当前已位于初始位置,可进行图像检测" << endl;
//return;
}
else {
cout << "当前不在初始位置,请进行校准" << endl;
}
}