简体   繁体   中英

RGB to Grayscale (cant show full image)

i have a simple code using C++ (combined with OpenCV) Here the code (main)

int main(int argc, char** argv)
{

    IplImage* image_input = cvLoadImage("test.jpg", CV_LOAD_IMAGE_UNCHANGED);
    IplImage* image_output =cvCreateImage(cvGetSize(image_input),
                 IPL_DEPTH_8U,image_input->nChannels);

    unsigned char *h_out = (unsigned char*)image_output->imageData;
    unsigned char *h_in =  (unsigned char*)image_input->imageData;

    int width     = image_input->width;
    int height    = image_input->height;

    h_grayscale ( h_in , h_out ) ;
    cvShowImage("Original", image_input);
    cvShowImage("CPU", image_output);
    cvReleaseImage(&image_input);
    cvReleaseImage(&image_output);
    waitKey(0);
}

and this is the function for grayscale

void h_grayscale( unsigned char* h_in, unsigned char* h_out){
    for (unsigned int i=0; i< width*height; i++){
        unsigned int index = i*3;
        double temp = 0.3*h_in[index]+0.6*h_in[index+1]+0.1*h_in[index+2];
        h_out[i] = (unsigned char)temp;
    }
}

but the results of the image split into 3 parts with a grayscale image 结果

please tell me whats wrong with my code?? T_T thx

You need to edit your code to create only one channel output image, since it is a grayscale image:

IplImage* image_output =cvCreateImage(cvGetSize(image_input), IPL_DEPTH_8U, 1);

Also, by "a simple code using C++ (with OpenCV)" I imagine something like this:

int main()
{
    Mat image_input = imread("test.jpg");
    Mat image_output;

    cvtColor(image_input, image_output, CV_BGR2GRAY);

    imshow("Original", image_input);
    imshow("CPU", image_output);
    waitKey(0);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM