Ask Your Question
0

Get HSV and RGB values of an image

asked 2018-02-16 01:40:03 -0500

im trying to get RGB values of an image. which i can get Min(R-G-B),Med(R-G-B),Max(R-G-B) also i want to get the HSV of RGB with same format HSVMIN(R-G-B), HSVMED(R-G-B), HSVMAX(R-G-B).

edit retag flag offensive close merge delete

Comments

please note, that opencv is using bgr, not rgb.

berak gravatar imageberak ( 2018-02-16 04:33:01 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2018-02-16 04:28:45 -0500

updated 2018-02-16 04:29:18 -0500

Something like this should do the trick:

Mat img = imread("/path/to/actual/image.png");
Mat imgHSV;
cvtColor(img, imgHSV, COLOR_BGR2HSV);

vector<Mat> channels, channelsHSV;
split(img, channels);
split(ingHSV, channelsHSV);

double minR, maxR, minG, maxG, minB, maxB;
minMaxLoc(channels[0], &minB, &maxB);
minMaxLoc(channels[1], &minG, &maxG);
minMaxLoc(channels[2], &minR, &maxR);

double minH, maxH, minS, maxS, minV, maxV;
minMaxLoc(channelsHSV[0], &minH, &maxH);
minMaxLoc(channelsHSV[1], &minS, &maxS);
minMaxLoc(channelsHSV[2], &minV, &maxV);

That code will give you all values except the median. Calculating the median needs some extra block of code, but you can base your code on top of the following snippet

namespace cv {
    // calculates the median value of a single channel
    // based on https://github.com/arnaudgelas/OpenCVExamples/blob/master/cvMat/Statistics/Median/Median.cpp
    double median( cv::Mat channel )
    {
        double m = (channel.rows*channel.cols) / 2;
        int bin = 0;
        double med = -1.0;

        int histSize = 256;
        float range[] = { 0, 256 };
        const float* histRange = { range };
        bool uniform = true;
        bool accumulate = false;
        cv::Mat hist;
        cv::calcHist( &channel, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange, uniform, accumulate );

        for ( int i = 0; i < histSize && med < 0.0; ++i )
        {
            bin += cvRound( hist.at< float >( i ) );
            if ( bin > m && med < 0.0 )
                med = i;
        }

        return med;
    }
}

which was originally posted here: https://gist.github.com/heisters/9cd6...

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2018-02-16 01:40:03 -0500

Seen: 787 times

Last updated: Feb 16 '18