用opencv和C++实现多边形ROI区域异物面积占比
时间: 2024-02-25 13:58:07 浏览: 86
C++在MFC中使用OpenCV动态绘制图像ROI区域(矩形+多边形)
实现多边形ROI区域异物面积占比的步骤如下:
1. 读取图像并显示。
```cpp
Mat img = imread("image.jpg");
imshow("Original Image", img);
```
2. 定义ROI区域的多边形顶点坐标,并将其转换为OpenCV的Point类型。
```cpp
vector<Point> roi_points;
roi_points.push_back(Point(100, 100));
roi_points.push_back(Point(200, 100));
roi_points.push_back(Point(200, 200));
roi_points.push_back(Point(100, 200));
```
3. 构建多边形掩膜,将ROI区域设置为白色,其余区域设置为黑色。
```cpp
Mat mask = Mat::zeros(img.size(), CV_8UC1);
fillConvexPoly(mask, roi_points, Scalar(255), LINE_8);
```
4. 将掩膜与原始图像进行按位与操作,得到ROI区域的图像。
```cpp
Mat roi_img;
img.copyTo(roi_img, mask);
imshow("ROI Image", roi_img);
```
5. 对ROI区域进行灰度化和二值化处理。
```cpp
Mat gray_img, binary_img;
cvtColor(roi_img, gray_img, COLOR_BGR2GRAY);
threshold(gray_img, binary_img, 0, 255, THRESH_BINARY | THRESH_OTSU);
```
6. 计算二值化图像中像素值为255的像素点数,即异物像素点数。
```cpp
int total_pixels = binary_img.total();
int white_pixels = countNonZero(binary_img);
int black_pixels = total_pixels - white_pixels;
```
7. 计算异物面积占比。
```cpp
double area_ratio = (double)white_pixels / total_pixels;
```
完整代码如下:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 读取图像并显示
Mat img = imread("image.jpg");
imshow("Original Image", img);
// 定义ROI区域的多边形顶点坐标
vector<Point> roi_points;
roi_points.push_back(Point(100, 100));
roi_points.push_back(Point(200, 100));
roi_points.push_back(Point(200, 200));
roi_points.push_back(Point(100, 200));
// 构建多边形掩膜
Mat mask = Mat::zeros(img.size(), CV_8UC1);
fillConvexPoly(mask, roi_points, Scalar(255), LINE_8);
// 将掩膜与原始图像进行按位与操作,得到ROI区域的图像
Mat roi_img;
img.copyTo(roi_img, mask);
imshow("ROI Image", roi_img);
// 对ROI区域进行灰度化和二值化处理
Mat gray_img, binary_img;
cvtColor(roi_img, gray_img, COLOR_BGR2GRAY);
threshold(gray_img, binary_img, 0, 255, THRESH_BINARY | THRESH_OTSU);
// 计算异物面积占比
int total_pixels = binary_img.total();
int white_pixels = countNonZero(binary_img);
int black_pixels = total_pixels - white_pixels;
double area_ratio = (double)white_pixels / total_pixels;
cout << "异物面积占比:" << area_ratio << endl;
waitKey(0);
return 0;
}
```
阅读全文