在OpenCV中查找多边形边界内的平均颜色

Jon*_*han 6 c++ opencv image-processing

背景

我正在尝试创建一个实用程序,它将返回给定多边形内的平均像素颜色OpenCV.多边形将通过4个点定义,但不一定是矩形/正方形.例如,可以预期以下结构:

     A__________B    A_______B
    /          /     \       \
   /          /       \       \
 D/__________/C       D\_______\C
Run Code Online (Sandbox Code Playgroud)

给定cv::MatOpenCV中的图像和由点(A,B,C,D)定义的多边形.我知道点A,B,C和D,但我想计算多边形内的平均像素颜色.我想从OpenCV社区获得一些关于如何最有效地做到这一点的建议.


研究完成

StackOverflow上的另一篇文章建议使用该drawContours函数绘制轮廓,然后使用mean围绕轮廓的边界矩形.我显然必须修改平均值计算,以便它使用fillPoly函数绘制的多边形.

建议/关注非常感谢!

Mik*_*iki 11

您可以简单地使用带掩码的mean函数,其中mask是填充多边形.

#include <opencv2\opencv.hpp>
#include <iostream>
using namespace cv;

int main()
{
    // Create a black image with a gray rectangle on top left
    Mat1b img(300, 300, uchar(0));
    rectangle(img, Rect(0, 0, 100, 100), Scalar(100), CV_FILLED);

    // Define a polygon
    Point pts[1][4];
    pts[0][0] = Point(20, 20);
    pts[0][1] = Point(40, 100);
    pts[0][2] = Point(200, 60);
    pts[0][3] = Point(150, 30);

    const Point* points[1] = {pts[0]};
    int npoints = 4;

    // Create the mask with the polygon
    Mat1b mask(img.rows, img.cols, uchar(0));
    fillPoly(mask, points, &npoints, 1, Scalar(255));

    // Compute the mean with the computed mask
    Scalar average = mean(img, mask);

    std::cout << average << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)