运行时使用鼠标左键点图像上任意点,即可显示该点rgb图像各通道的值及该图像对应的灰度图象的灰度值
//PixelValueMonitor.h #include "cv.h" #include "highgui.h" class PixelValueMonitor{ public: PixelValueMonitor(IplImage* img); ~PixelValueMonitor(); static void mouse_callback(int trigerEvent,int x,int y,int flags,void* param); void run(); IplImage* m_img; IplImage* m_grayImage; char* m_windowName; bool m_destroyWindow; };
//PixelValueMonitor.cpp #include "PixelValueMonitor.h" PixelValueMonitor::PixelValueMonitor(IplImage *img){ m_img=cvCreateImage(cvSize(img->width,img->height),img->depth,img->nChannels); cvCopy(img,m_img); m_grayImage=cvCreateImage(cvSize(img->width,img->height),IPL_DEPTH_8U,1); cvCvtColor(m_img,m_grayImage,CV_RGB2GRAY); m_windowName="window for pixel monitoring"; m_destroyWindow=false; } PixelValueMonitor::~PixelValueMonitor(){ cvReleaseImage(&m_img); cvReleaseImage(&m_grayImage); } void PixelValueMonitor::mouse_callback(int trigerEvent, int x, int y, int flags, void *param){ PixelValueMonitor* instance=(PixelValueMonitor*)param; if(trigerEvent==CV_EVENT_LBUTTONDOWN){ unsigned char* ptrRGB=(unsigned char*)(instance->m_img->imageData+y*instance->m_img->widthStep); unsigned char* ptrGray=(unsigned char*)(instance->m_grayImage->imageData+y*instance->m_grayImage->widthStep); //printf("x:\t%d\ny:\t%d\n",x,y); printf("R:\t%d\n",*(ptrRGB+3*x+2)); printf("G:\t%d\n",*(ptrRGB+3*x+1)); printf("B:\t%d\n",*(ptrRGB+3*x)); printf("GRAY:\t%d\n",*(ptrGray+x)); } else if(trigerEvent==CV_EVENT_RBUTTONDOWN){ instance->m_destroyWindow=true; } } void PixelValueMonitor::run(){ cvNamedWindow(m_windowName); cvSetMouseCallback(m_windowName,mouse_callback,(void*)this); cvShowImage(m_windowName,m_img); while(1){ if(cvWaitKey(2)==27 || m_destroyWindow) break; } cvDestroyWindow(m_windowName); }
//main.cpp #include "PixelValueMonitor.h" #include "cv.h" #include "highgui.h" int main(int argc,char** argv){ IplImage* img=cvLoadImage("data/videoImage.jpg",1); /*IplImage* img=cvCreateImage(cvSize(800,600),IPL_DEPTH_8U,3); cvSet(img,cvScalar(255,255,255));*/ PixelValueMonitor monitor(img); monitor.run(); return 0; }