Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a random colour image in OpenCV

I am new to OpenCV. I am trying to create a random color image. Firstly I tried to create a random grayscale image. The code I have attached below

void random_colour(Mat input_image) {
    for (int i = 0; i < image.rows; i++)
        for (int j = 0; j < image.cols; j++)
            image.at<uchar>(i,j)= rand()%255;
    imwrite("output.tif",image);
}


int main( int argc, char** argv )
{
    Mat img=Mat::zeros(100,100,CV_8UC1);
    random_colour(img);
    waitKey(0);
    return 0;
}

The output obtained is

enter image description here

Now I changed my above code to create a random colour image as.

void random_colour(Mat input_image) {
    for (int i = 0; i < image.rows; i++)
    {
        for (int j = 0; j < image.cols; j++)
        {
            image.at<Vec3b>(i,j)[0] = rand()%255;
            image.at<Vec3b>(i,j)[1] = rand()%255;
            image.at<Vec3b>(i,j)[2] = rand()%255;
         }
    }
    imwrite("output.tif",image);
}

The main function remains same. While doing so, I get a runtime error. Please help me on what should I do. What I understood is that each pixel in colour space has three component RGB. So therefore I am changing all the three component of each pixel. I am not getting the output what I wanted.

like image 416
Abhishek Avatar asked Aug 21 '17 16:08

Abhishek


2 Answers

no need to reinvent the wheel, please use cv::randu()

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

using namespace cv;

int main(int argc, char** argv)
{
    Mat img(100, 100, CV_8UC3);
    randu(img, Scalar(0, 0, 0), Scalar(255, 255, 255));

    imshow("random colors image", img);
    waitKey();

    return 0;
}

enter image description here

like image 58
sturkmen Avatar answered Sep 28 '22 07:09

sturkmen


This line creates a greyscale image, it doesn't have three channels.

 Mat img=Mat::zeros(100,100,CV_8UC1);

That means when you use this line, its going to crash:

 image.at<Vec3b>(i,j)[0] = rand()%255;

You need to not use CV_8UC1 because that creates 1 channel (C1) try it with CV_8UC3 instead

Mat img=Mat::zeros(100,100,CV_8UC3);

FYI 8u means 8 bit so values 0 to 255, CX is the number of channels in the image. If you want BGR you need C3.

like image 45
GPPK Avatar answered Sep 28 '22 06:09

GPPK