Ask Your Question

png to grayscale conversion offset by 1 in pixel intensity

asked 2017-02-11 04:28:31 -0500

I am running opencv in ubuntu 14.04
Here I am reading a png file and displaying it , printing value of b,g,r channel at pixel and converting to gray scale (file not changed on disk only in memory).
My code in C

/* usage: prog image assuming filename is  image-1.png*/
using namespace cv;

int main( int argc, char** argv )
{   char strimgfile[100];
    int i,j,cn,filenumber=1;
    Mat image;
    Mat gray_image;
    Vec3b intensity;
    unsigned int b,g,r;

    sprintf(strimgfile,"%s%d.png",argv[1],filenumber);//adding number and png extension to program argument which is filename prefix
    printf("\nthe file that will be read _%s_\n",strimgfile);
    image = imread( strimgfile, 1 );
    if( argc != 2 || ! )
        printf( "\n No image data \n " );
        return -1;
    intensity =<Vec3b>(100, 100);
    printf("\nThis image has %d rows %d columns and channels=%d\n",image.rows,image.cols,cn);
    cvtColor(image, gray_image, CV_BGR2GRAY );
    printf("\nChannels in gray image=%d\n",gray_image.channels());
    printf("\nValue at that pixel in gray image is %u\n",(int)<uchar>(100,100));
    namedWindow( strimgfile, CV_WINDOW_AUTOSIZE );
    imshow( strimgfile, image );

    return 0;

I compile it using

$ g++ code.c -o bincode  -I /usr/include/opencv -I /usr/include/opencv2/imgproc/  -lm `pkg-config --libs --cflags opencv` -ldl

My output is

the file that will be read _image-1.png_


This image has 240 rows 352 columns and channels=3

Channels in gray image=1

Value at that pixel in gray image is 38

QUE) 45+41+31=117 so its one third is 39 . why do I get 38 ?
QUE)Also please suggest me compilation options or code changes for better performance .I am sure , i am using too many resources for this simple task .


edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2017-02-11 04:35:01 -0500

LBerger gravatar image

updated 2017-02-11 05:09:36 -0500

"Why do I get 38 ?" because CV_BGR2GRAY formula conversion is here

opencv use Blue Green Red format

31 * 0.299+0.587 * 41 + 0.114 * 45 = 38.466

"please suggest me compilation options" I use cmake on all platform : windows (VS2013-2015, Mingw 64), raspberry and ubuntu...

and opencv version is necessary to help you more...

edit flag offensive delete link more


That formula clears my doubt .

opencvbeginner gravatar imageopencvbeginner ( 2017-02-11 05:05:33 -0500 )edit

Question Tools

1 follower


Asked: 2017-02-11 04:28:31 -0500

Seen: 299 times

Last updated: Feb 11 '17