思路:图像转为灰度图,然后二值化得到只有0或255的点坐标,此处圆是黑点,所以添加所有像素值为0的坐标。在这些坐标中找到圆上最左边、最顶端、最右边、最底端的四个点,这时可求出圆心坐标。
.cpp文件
#include <opencv2/opencv.hpp>
#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <map>
#include <any>
// 1.获取图片 cv::Mat src = cv::imread("D:\\1.bmp"); // 2.将彩色图像转换为灰度图像 cv::Mat gray_image; cv::cvtColor(src, gray_image, cv::COLOR_BGR2GRAY); // 3.二值化处理 cv::Mat dst; cv::threshold(gray_image, dst, threshold, 255, cv::THRESH_BINARY); // 4.找到所有目标坐标 cv::Point leftPoint; cv::Point rightPoint; cv::Point topPoint; cv::Point bottomPoint; std::vector<cv::Point> points; for (int i = 0; i < dst.rows; ++i) { for (int j = 0; j < dst.cols; ++j) { if (dst.at<uchar>(i, j) != 255) { // 0:白色、255:黑色 cv::Point tempPoint = cv::Point(j, i); // 去除边缘干扰点位,按实际需求添加 if (j < 50 || i < 50) { continue; } // 赋值初始坐标 if (leftPoint.x == 0 && leftPoint.y == 0) { leftPoint = tempPoint; } if (rightPoint.x == 0 && rightPoint.y == 0) { rightPoint = tempPoint; } if (topPoint.x == 0 && topPoint.y == 0) { topPoint = tempPoint; } if (bottomPoint.x == 0 && bottomPoint.y == 0) { bottomPoint = tempPoint; } points.push_back(tempPoint); // 注意OpenCV的坐标系是(列,行) //else { if (leftPoint.x == 0 || tempPoint.x < leftPoint.x) { leftPoint = tempPoint; } if (topPoint.y == 0 || tempPoint.y < topPoint.y) { topPoint = tempPoint; } if (rightPoint.x == 0 || tempPoint.x > rightPoint.x) { rightPoint = tempPoint; } if (bottomPoint.y == 0 || tempPoint.y > bottomPoint.y) { bottomPoint = tempPoint; } //} } } } // 5.求圆半径, int r1 = rightPoint.x - leftPoint.x; int r2 = bottomPoint.y - topPoint.y; int r = (r1 + r2) / 2;
// 6.求圆心坐标
cv::Point circleCenter(leftPoint.x + r, topPoint.y + r);
// 7.对圆画框
// 7.1.定义矩形的左上角和右下角坐标
cv::Point2f rect_start(leftPoint.x, topPoint.y);
cv::Point2f rect_end(rightPoint.x, bottomPoint.y);
// 7.2.画矩形框
cv::rectangle(src, rect_start, rect_end, cv::Scalar(0, 255, 0));
标签:leftPoint,OpenCv,topPoint,C++,cv,tempPoint,bottomPoint,rightPoint,二值化 From: https://www.cnblogs.com/resplendent/p/18527563