使用C++,利用opencv,读取图片,识别图内半圆,计算圆心坐标和直径
时间: 2024-06-14 20:06:17 浏览: 15
以下是使用C++和OpenCV读取图片,识别图内半圆,计算圆心坐标和直径的示例代码:
```cpp
#include <opencv2/opencv.hpp>
int main() {
// 读取图片
cv::Mat image = cv::imread("image.jpg");
// 灰度化处理
cv::Mat gray;
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
// 边缘检测
cv::Mat edges;
cv::Canny(gray, edges, 50, 150);
// 查找轮廓
std::vector<std::vector<cv::Point>> contours;
cv::findContours(edges, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
// 遍历轮廓,找到半圆
for (const auto& contour : contours) {
double area = cv::contourArea(contour);
cv::Rect boundingRect = cv::boundingRect(contour);
double aspectRatio = static_cast<double>(boundingRect.width) / boundingRect.height;
// 判断是否为半圆
if (aspectRatio > 0.9 && aspectRatio < 1.1 && area > 1000) {
// 计算圆心坐标和直径
cv::Point center = cv::Point(boundingRect.x + boundingRect.width / 2, boundingRect.y + boundingRect.height / 2);
int diameter = boundingRect.width;
// 在图像上绘制圆心和直径
cv::circle(image, center, 2, cv::Scalar(0, 255, 0), -1);
cv::circle(image, center, diameter / 2, cv::Scalar(0, 255, 0), 2);
}
}
// 显示结果图像
cv::imshow("Result", image);
cv::waitKey(0);
return 0;
}
```
请注意,上述代码假设你已经安装了OpenCV,并且将图片命名为"image.jpg"。你可以根据实际情况进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)