简体   繁体   中英

Printing pixel values to screen from an opencv image

I keep trying to print values of pixels to screen using printf in OpenCV in C but I just get garbage values. How do I print IPL_DEPTH_8U (8 bit unsigned integer) images to screen and IPL_DEPTH_32F (32 bit floating point) images to screen? Bellow is the code I am using. Is it wrong? It could be correct, but I just get pixel values I do not anticipate:

these are single channel images btw:

for (y = 0; y < img->height; y++){
   uchar *ptr = (uchar*)(img->imageData + y * img->widthStep);
   for (x = 0; x < img->width; x++){
       printf("%u, ", ptr[x]);
   }
   printf("\n");
}

That is for IPL_DEPTH_8U images, and I suspect that is working fine. for 32 float images I change the pointer to float * and the specifier in printf to '%f', and that doesn't seem to work. What is wrong?

Are these the correct pointers and specifiers? Also, what are the pointers and specifiers supposed to be for 16 bit signed integers and 32 bit signed floats too?

Thanks. I just started using this website and you guys are awesome!

You can use cvGet2D() doing:

CvScalar val = cvGet2D(img, y, x);

You have to pull out the values you want to print from CvScalar . Since it is basically double[4] , I don't think it will be a problem.

Check out this OpenCV FAQ. In particular, look at the "How to access matrix elements?" section.

Here is a small sample I wrote for properly printing float IplImage structures:

void fillIplImage(IplImage* srcdst)
{
    for(int row = 0; row < srcdst->height; row++)
    {
        for(int col = 0; col < srcdst->width; col++)
        {
            ((float*)(srcdst->imageData + srcdst->widthStep*row))[col] = (float)col;
        }
    }
}

void printIplImage(const IplImage* src)
{
    for(int row = 0; row < src->height; row++)
    {
        for(int col = 0; col < src->width; col++)
        {
            printf("%f, ", ((float*)(src->imageData + src->widthStep*row))[col]);
        }
        printf("\n");
    }
}

int main(int argc, char** argv)
{
    CvSize sz = {10, 10};
    IplImage* test = cvCreateImage(sz, IPL_DEPTH_32F, 1);

    fillIplImage(test);
    printIplImage(test);

    cvReleaseImage(&test);
    return 0;
}

There is also the CV_MAT_ELEM( matrix, elemtype, row, col ) macro that will work only for single-channel images, but it essentially is a short-hand for all the pointer arithmetic.

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