7/1/12

OpenCV Utility: Reading Image Pixels Value

This is a utility to read the pixel value of an image at the specified location. When the user's mouse clicks on the image, it reads the corresponding pixel and displays the RGB value. Useful for debugging.
Listing 1: readpixel.c
  1. #include "cv.h"
  2. #include "highgui.h"
  3. void
  4. mouseHandler(int event, int x, int y, int flags, void* param)
  5. {
  6.     IplImage* img0, * img1;
  7.     CvFont    font;
  8.     uchar*    ptr;
  9.     char      label[20];
  10.     img0 = (IplImage*) param;
  11.     img1 = cvCloneImage(img0);
  12.     cvInitFont(&font, CV_FONT_HERSHEY_PLAIN, .8, .8, 0, 1, 8);
  13.     if (event == CV_EVENT_LBUTTONDOWN)
  14.     {
  15.         /* read pixel */
  16.         ptr = cvPtr2D(img1, y, x, NULL);
  17.         /*
  18.          * display the BGR value
  19.          */
  20.         sprintf(label, "(%d, %d, %d)", ptr[0], ptr[1], ptr[2]);
  21.         cvRectangle(
  22.             img1,
  23.             cvPoint(x, y - 12),
  24.             cvPoint(x + 100, y + 4),
  25.             CV_RGB(255, 0, 0),
  26.             CV_FILLED,
  27.             8, 0
  28.         );
  29.         cvPutText(
  30.             img1,
  31.             label,
  32.             cvPoint(x, y),
  33.             &font,
  34.             CV_RGB(255, 255, 0)
  35.         );
  36.         cvShowImage("img", img1);
  37.     }
  38. }
  39. int
  40. main(int argc, char** argv)
  41. {
  42.     IplImage* img;
  43.     /* usage: <prog_name> <image> */
  44.     if (argc != 2) {
  45.         printf("Usage: %s <image>\n", argv[0]);
  46.         return 1;
  47.     }
  48.     /* load image */
  49.     img = cvLoadImage(argv[1], 1);
  50.     /* always check */
  51.     assert(img);
  52.     /* create a window and install mouse handler */
  53.     cvNamedWindow("img", 1);
  54.     cvSetMouseCallback("img", mouseHandler, (void*)img);
  55.     cvShowImage("img", img);
  56.     cvWaitKey(0);
  57.     /* be tidy */
  58.     cvDestroyAllWindows();
  59.     cvReleaseImage(&img);
  60.     return 0;
  61. }

Bài đăng phổ biến