0

I'm new to C++ and I'm trying to create an 500x500 pixel RGB image. The image should be filled by linear interpolation of four colours, each defined for one of the corners so I should have something like:

Vec3b ul( 255, 0, 0 ); //upper left corner
Vec3b ur( 0, 255, 0 ); //upper right corner
Vec3b bl( 0, 0, 255 ); //bottom left corner
Vec3b br( 255, 0, 255 ); //bottom right corner

The end result should look like this:

enter image description here

The program then displays the image in a window etc etc... I can do that stuff but I just need to figure out how to put the colours in the image. My code so far is this:

#include <QtCore/QCoreApplication>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
#include <string>
#include <sys/stat.h>

using namespace cv;
int main()
{

    Mat image;
    image.create( 500, 500, CV_8UC3);
    //upper left corner
    Vec3b ul( 255, 0, 0 );
    //upper right corner
    Vec3b ur( 0, 255, 0 );
    //bottom left corner
    Vec3b bl( 0, 0, 255 );
    //bottom right corner
    Vec3b br( 255, 0, 255 );

    namedWindow("Colored Pixels");
    imshow("Colored Pixels", image);
    // shows image for 5 seconds
    waitKey(5000);
    return 0;
}

and the output is

enter image description here

I'd be glad to hear your suggestions!

4

1 回答 1

1

It sounds like what you're really asking is 'How do I set elements of an OpenCV Mat instance that represents an image?' A little Googling produces this link, which documents the Mat interface. It includes a function with this signature:

template _Tp& Mat::at(int i, int j)

So, you should be able to make calls like image.at(100,250) to get a reference to the pixel data for the pixel at 100,250. Then, assign pixel data to the pixel.

As for how to assign the pixel data in the form the matrix understands... the following is also from the above link:

If you are familiar with OpenCV CvMat ‘s type notation, CV _ 8U ... CV _ 32FC3, CV _ 64FC2 etc., then a primitive type can be defined as a type for which you can give a unique identifier in a form CV_{U|S|F}C . A universal OpenCV structure able to store a single instance of such primitive data type is Vec.

So, it sounds like an OpenCV Vec of type int and size 3 might be compatible. Something like:

image.at(i,j) = Vec<int,3>(r,g,b)

is hopefully fairly close to what you're looking for.

Please note that I haven't used OpenCV and I haven't tested this code; this is just what I've gleaned from the linked documentation.

于 2012-10-11T01:08:39.650 回答