Samitha Chathuranga
Samitha Chathuranga

Reputation: 1749

Is there a direct way to get a unique value representing RGB color in opencv C++

My image is a RGB image. I want to get a unique value (such as a unicode value) to represent the RGB color value of a certain pixel. For example If the pixels red channel=23, Green channel=200,Blue channel=45 this RGB color could be represented by 232765. I wish if there is a direct opencv c++ function to get such a value from a pixel. And note that this unique value should be unique for that RGB value. I want something like this and I know this is not correct.

uniqueColorForPixel_i_j=(matImage.at<Vec3b>(i,j)).getUniqueColor();

I hope something could be done if we can get the Scalar value of a pixel. And as in the way RNG can generate a random Scalar RGB value from number, can we get the inverse...

Upvotes: 1

Views: 1964

Answers (1)

Miki
Miki

Reputation: 41775

Just a small sample code to show how to pass directly a Vec3b to the function, and an alternative way to shift-and approach.

The code is based on this answer.

UPDATE

I added also a simple struct BGR, that will handle more easily the conversion between Vec3b and unsigned.

UPDATE 2

The code in your question:

uniqueColorForPixel_i_j=(matImage.at<Vec3b>(i,j)).getUniqueColor();

doesn't work because you're trying to call the method getUniqueColor() on a Vec3b which hasn't this method. You should instead pass the Vec3b as the argument of unsigned getUniqueColor(const Vec3b& v);.

The code should clarify this:

#include <opencv2\opencv.hpp>
using namespace cv;

unsigned getUniqueColor_v1(const Vec3b& v)
{
    return ((v[2] & 0xff) << 16) + ((v[1] & 0xff) << 8) + (v[0] & 0xff);
}

unsigned getUniqueColor_v2(const Vec3b& v)
{
    return 0x00ffffff & *((unsigned*)(v.val));
}

struct BGR
{
    Vec3b v;
    unsigned u;

    BGR(const Vec3b& v_) : v(v_){
        u = ((v[2] & 0xff) << 16) + ((v[1] & 0xff) << 8) + (v[0] & 0xff);
    }

    BGR(unsigned u_) : u(u_) {
        v[0] = uchar(u & 0xff);
        v[1] = uchar((u >> 8) & 0xff);
        v[2] = uchar((u >> 16) & 0xff);
    }
};

int main()
{
    Vec3b v(45, 200, 23);

    unsigned col1 = getUniqueColor_v1(v);
    unsigned col2 = getUniqueColor_v2(v);
    unsigned col3 = BGR(v).u;

    // col1 == col2 == col3
    //
    // hex: 0x0017c82d
    // dec: 1558573

    Vec3b v2 = BGR(col3).v;
    // v2 == v



    //////////////////////////////
    // Taking values from a mat
    //////////////////////////////

    // Just 2 10x10 green mats
    Mat mat1(10, 10, CV_8UC3);
    mat1.setTo(Vec3b(0, 255, 0));

    Mat3b mat2(10, 10, Vec3b(0, 255, 0));

    int row = 2;
    int col = 3;

    unsigned u1 = getUniqueColor_v1(mat1.at<Vec3b>(row, col));
    unsigned u2 = BGR(mat1.at<Vec3b>(row, col)).u;

    unsigned u3 = getUniqueColor_v1(mat2(row, col));
    unsigned u4 = BGR(mat2(row, col)).u;

    // u1 == u2 == u3 == u4

    return 0;
}

Upvotes: 1

Related Questions