Search code examples
c++opencvmatrect

How to build cv::Mat from coloured rectangles


My goal is to create yield maps using OpenCV. These yield maps need to be built with coloured rectangles to indicate yield. An example of a Mat built by rectangles here.

So is it possible to create a cv::Mat with coloured rectangles? The amount of rectangles isn't constant, thus changes with every use.

To make the question clear: if I have 4 boxes (2x2 grid) I want to automatically make a Mat which is as big as the 4 boxes. If I have 16 boxes (4x4 grid) I want to make a Mat which is as big as the 16 boxes.

I couldn't find a way to make it work, so I hope somebody here knows if it is possible.

If somebody can help me that would be great, if it is not possible alternatives are also welcome! Thanks

Some info:

  • OpenCV version:4.5.3
  • OS: Ubuntu 20.04
  • Language: C++

Solution

  • OpenCV has cv::hconcat and cv::vconcat. Use them like numpy's hstack/vstack.

    make sure your parts have the same type (and number of channels).

    The documentation has a code example.

    cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),
                           cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),
                           cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};
    cv::Mat out;
    cv::hconcat( matArray, 3, out );
    //out:
    //[1, 2, 3;
    // 1, 2, 3;
    // 1, 2, 3;
    // 1, 2, 3]