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图像用于坐标和灰度在图像上的显示,所以转换为RGB
if(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;
else
x_show=x_coordinate;
if(y_coordinate<=pic_width/2)
y_show=y_coordinate+55;
else
y_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(MSG* pMsg)
{
if (GetDlgItem(IDC_BORDER3)->GetSafeHwnd() == pMsg->hwnd && pMsg->message == WM_MOUSEMOVE)
{
OnMouseMove(MK_LBUTTON, pMsg->pt);
return TRUE;
}
return CDialogEx::PreTranslateMessage(pMsg);
}