3

I converted my image from rgb to YUV. Now I want to find the average values of luma channel alone. Could you please help me by telling how I can achieve this? Moreover, is there a way to determine how many channels an image consists of?

Bart
  • 19,692
  • 7
  • 68
  • 77
Lakshmi Narayanan
  • 5,220
  • 13
  • 50
  • 92

2 Answers2

16

You can do this:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdio.h>

using namespace cv;

int main(void)
{
    vector<Mat> channels;
    Mat img = imread("Documents/forest.jpg");
    split(img, channels);
    Scalar m = mean(channels[0]);
    printf("%f\n", m[0]);

    return 0;
}
lightalchemist
  • 10,031
  • 4
  • 47
  • 55
  • std::vector rgbChannels(3); cv::split(inputImage, rgbChannels); isn't this the format? Moreover, what should be the data type of m? Am facing problems there. could you please help me.? – Lakshmi Narayanan Jan 16 '13 at 02:15
  • Hi, apologies, I've been using Python too much recently that I forgotten about types haha. I've edited the code example. Hope this helps. – lightalchemist Jan 16 '13 at 03:04
  • thanks for the edit. :). could you please temme why you gave it as 'm[0]'? – Lakshmi Narayanan Jan 16 '13 at 04:33
  • 1
    Because the function mean(...) returns a cv::Scalar. If you have given it the entire Mat object instead of one of its channel, then each entry of m would have contained the mean for the corresponding channel. Since in this case the code only pass in 1 channel, only the first returned value in m is valid. – lightalchemist Jan 16 '13 at 06:33
3

Image.channels() will give you the number of channels in any image. Please refer to the OpenCV documentation.

multiple channels can be accessed as follows:

        img.at<Vec3b>(i,j)[0] //Y
        img.at<Vec3b>(i,j)[1] //U
        img.at<Vec3b>(i,j)[2] //V
Abhishek Thakur
  • 16,337
  • 15
  • 66
  • 97