Opencv filled rectangle with red color and every 5 pixel should have the color black

im beginner in Opencv with c++. I have to draw a filled rectangle(10x10) in the middle of a image where every 5th pixel is black.

i Know how to create a rectangle. But how i can fill it and change the color of every 5th pixel ? Would be nice if someone can help :/

void cv::rectangle  (   InputOutputArray    img,
Point   pt1,
Point   pt2,
const Scalar &  color,
int     thickness = 1,
int     lineType = LINE_8,
int     shift = 0 

My code so far:

#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;

int main(void)

    //Laden vom Bild

    Mat img;
    img = imread("C:\\Users\\Mehmet\\Desktop\\yoshi.png");
    if (!
        cout << "Could not find the image";
        return -1;
    imshow("window", img);
    imwrite("C:\\Users\\Max Mustermann\\Desktop\\11.png", img); 

    cv::Size sz = img.size();
    int imageWidth = sz.width;
    int imageHeight = sz.height;

    cout <<"Es gibt " <<img.channels()<<" Farbkanäle" << endl;;
    cout << "Die Breite betreagt: "<<sz.width << endl;
    cout <<"Die Hoehe betreagt: " << sz.height<<endl;
    std::cout << img.type();

    Mat img1;
    img.convertTo(img1, CV_32FC3, 1 / 255.0);

    return 0;

1 answer

  • answered 2021-05-16 04:59 jiyang.lee

    You may be able to find the answer to your question in the opencv document.

    To fill the rectangle, you can change the parameter 'thickness'

    ==> 'thickness Thickness of lines that make up the rectangle. Negative values, like FILLED, mean that the function has to draw a filled rectangle.'


    And, changing color can be done by the color parameter. Controlling this parameter is easy with using cv::Scalar(BLUE, GREEN, RED).

    For example, Rectangle(~~~,cv::Scalar(255,0,0),~~~); will make blue colorized rectangle with depending other parameters. So, if you want to change the color, change these values as what you want.

    Consequently, if you want to change the color of rectangle repeatably, I think you can surely make the loop with this two parameters.