在OpenCV中查找多边形边界内的平均颜色 [英] Finding the Average Color within a Polygon Bound in OpenCV

查看:150
本文介绍了在OpenCV中查找多边形边界内的平均颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a utility that will return the average pixel color within a given polygon using OpenCV. The polygon will be defined via 4 points, but it is not necessarily a rectangle/square. For example, the following structures are to be expected:

     A__________B    A_______B
    /          /     \       \
   /          /       \       \
 D/__________/C       D\_______\C


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


Given a cv::Mat image in OpenCV and a polygon defined by the points (A, B, C, D). I know points A, B, C, and D, but I want to calc the average pixel color within the polygon. I wanted to get some suggestions from the OpenCV community on how to do this most efficiently.

关于StackOverflow的另一条帖子建议使用 fillPoly 函数.

Another post on StackOverflow suggested drawing contours using the drawContours function and then take the mean of the bounding rectangle surrounding the contour. I would obviously have to modify the mean calculation so that it uses the polygons drawn by the fillPoly function instead.

非常感谢您提出建议/问题!

Suggestions/Concerns are much appreciated!

推荐答案

您可以简单地使用平均值功能,其中蒙版是您填充的多边形.

You can simply use the mean function with a mask, where the mask is your filled polygon.

#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;
}

这篇关于在OpenCV中查找多边形边界内的平均颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆