c++ opencv通过图像像素填充计算交并比的方法
交并比IOU(Intersection over Union)经常被应用在模型中作为衡量指标,来描述两个目标的重合度。
交并比一般有矩形框的交并比、旋转矩形框的交并比、凸多边形框的交并比等。
两个多边形交并比的计算方法可以通过空间几何理论计算,也可以通过图像像素填充近似计算。
程序如下:
test.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int getAreaOfRegion(cv::Mat image, int value)
{
int area = 0;
for (size_t i = 0; i < image.rows; i++)
{
uchar *p = image.ptr<uchar>(i);
for (size_t j = 0; j < image.cols; j++)
{
int cur_value = p[j];
if(cur_value == value)
{
area++;
}
}
}
return area;
}
int main()
{
cv::Mat image = cv::Mat::zeros(cv::Size(1000,1000),CV_8UC1);
int fill_value = 255;
cv::Point rook_points[1][4];
rook_points[0][0] = cv::Point(132,131);
rook_points[0][1] = cv::Point(62,266);
rook_points[0][2] = cv::Point(179,373);
rook_points[0][3] = cv::Point(422,265);
const cv::Point* ppt[1] = {rook_points[0]};
int npt[] = {4};
cv::Mat out_im1 = image.clone();
cv::fillPoly(out_im1,ppt, npt, 1, fill_value);
cv::imwrite("out_im1.jpg",out_im1);
cv::Point rook_points2[1][4];
rook_points2[0][0] = cv::Point(326,57);
rook_points2[0][1] = cv::Point(218,252);
rook_points2[0][2] = cv::Point(335,479);
rook_points2[0][3] = cv::Point(572,296);
const cv::Point* ppt2[1] = {rook_points2[0]};
cv::Mat out_im2 = image.clone();
cv::fillPoly(out_im2,ppt2, npt, 1, fill_value);
cv::imwrite("out_im2.jpg",out_im2);
cv::Mat combine_im;
cv::Mat inter_im;
cv::bitwise_or(out_im1,out_im2,combine_im);
cv::bitwise_and(out_im1,out_im2,inter_im);
cv::imwrite("combine_im.jpg",combine_im);
cv::imwrite("inter_im.jpg",inter_im);
int combine_area = getAreaOfRegion(combine_im, fill_value);
int inter_area = getAreaOfRegion(inter_im, fill_value);
float score = (inter_area)*1.0/combine_area;
std::cout<<"iou=="<<score<<std::endl;
return 0;
}
CMakeLists.txt
# 声明要求的 cmake 最低版本
cmake_minimum_required( VERSION 2.8 )
# 声明一个 cmake 工程
project( vehicle_calibrate )
# 设置编译模式
set( CMAKE_BUILD_TYPE "Debug" )
set(CMAKE_CXX_FLAGS "-std=c++11")
find_package(OpenCV 4 REQUIRED)
include_directories(${PROJECT_SOURCE_DIR})
# 添加一个可执行程序
# 语法:add_executable( 程序名 源代码文件 )
# add_executable( test test.cpp)
add_executable(test test.cpp)
# 将库文件链接到可执行程序上
# target_link_libraries( test ${OpenCV_LIBS} )
target_link_libraries( test ${OpenCV_LIBS} )
运行结果:
./test
iou==0.148643
几何图形1
几何图形2
交集
并集
【注】:
fillPoly(img,ppt,npt,1,Scalar(255,255,255),lineType);
函数参数:
(1)多边形将被画到img上
(2)多边形的顶点集为ppt
(3)绘制的多边形顶点数目为npt
(4)要绘制的多边形数量为1
(5)多边形的颜色定义为Scarlar(255,255,255),即RGB的值为白色
《完》
上一篇
上上篇