MFC中用OpenCV显示图像,并跟踪鼠标显示图像的坐标与像素

来源:互联网 发布:办公软件视频教程下载 编辑:程序博客网 时间:2024/05/19 00:13
void COptics::OnTimer(UINT_PTR nIDEvent){CRect rect;CPoint pt;//获取鼠标坐标::GetCursorPos(&pt);//获取图像显示的控件AfxGetMainWnd()->GetDlgItem(IDC_BORDER3)->GetWindowRect(&rect);//判断鼠标是否在控件范围内if(rect.PtInRect(pt)){//判断是否加载图像if(new_image.rows!=0){Mat gray_img;Mat simg=new_image.clone();//simg图像用于坐标和灰度在图像上的显示,所以转换为RGBif(simg.channels()==1){cvtColor(simg,simg,CV_GRAY2RGB);}//gray_img灰度图像用于查找对应点的灰度cvtColor(simg,gray_img,CV_RGB2GRAY);//计算控件与图像的比例int c_width=rect.Width();int c_height=rect.Height();int pic_width=new_image.cols;int pic_height=new_image.rows;float x_coordinate=((pt.x-rect.left)*pic_width)/c_width;float y_coordinate=((pt.y-rect.top)*pic_height)/c_height;//查找鼠标点的灰度值uchar* p;  p = gray_img.ptr<uchar>((int)(y_coordinate));  uchar ch=p[(int)(x_coordinate)];  //坐标灰度值显示CString str;String tstr;str.Format("%0.2f,%0.2f,%d",x_coordinate,y_coordinate,ch);tstr=str.GetBuffer(0);//数值显示在图像内int x_show;int y_show;if(x_coordinate>=pic_width/2)x_show=x_coordinate-str.GetLength()*18;elsex_show=x_coordinate;if(y_coordinate<=pic_width/2)y_show=y_coordinate+55;elsey_show=y_coordinate;//在图像上显示鼠标坐标与对应点的灰度putText(simg,tstr,Point(x_show,y_show),2,1,Scalar(255,0,0),5,8);//显示带坐标点的图像renderScene(simg);}}else{//鼠标不在控件内,则显示不带坐标灰度的原图像renderScene(new_image);}CDialogEx::OnTimer(nIDEvent);}
//图像显示
void COptics::renderScene(Mat timg){ CDC *pDC=AfxGetMainWnd()->GetDlgItem(IDC_BORDER3)->GetDC();HDC hDC=pDC->GetSafeHdc();//putText(new_image,"Edge Detection",Point(10,50),5,3,Scalar(255,0,0),3);IplImage img=timg;CvvImage cimg;cimg.CopyOf(&img);CRect rect;AfxGetMainWnd()->GetDlgItem(IDC_BORDER3)->GetClientRect(&rect); /*int tlx=rect.TopLeft().x;int tly=rect.TopLeft().y;int brx=tlx+mat.cols-1;int bry=tly+mat.rows-1;CRect drawRect;drawRect.SetRect(tlx,tly,brx,bry);*/cimg.DrawToHDC(hDC,&rect);ReleaseDC(pDC);}

//由于pic控件不捕获ONMOUSEMOVE指令,需在PreTranslateMessage截取信息
BOOL COpticalDlg::PreTranslateMessage(MSGpMsg){if (GetDlgItem(IDC_BORDER3)->GetSafeHwnd() == pMsg->hwnd && pMsg->message == WM_MOUSEMOVE)      {           OnMouseMove(MK_LBUTTONpMsg->pt);           return TRUE;       }return CDialogEx::PreTranslateMessage(pMsg);}

                                             
0 0
原创粉丝点击