2017年5月22日 星期一

顯示滑鼠指定位置的灰階值 Grey value (Cognex)

因專案需求,要顯示滑鼠指定位置的Grey Value,一開始想得很簡單,忽略了Cognex display控制項的Pan & Zoom會讓圖片位置與大小比例改變,導致滑鼠指不到對的位置上,花了一些時間把忽略的因素考慮進去後,得到以下程式碼:

程式概要說明:
1. 採用Cognex 的Display控制項的Mouse_Move事件
2. ICogImage.GetPixel(int x, int y) 可以直接取得指定XY位置的灰階值
3. zoomImgHeight , zoomImgWidth 是image經過zoom的實際寬高
4. blankWidth , blankHeight 是指當image和display比例不同時,在Display控制項周圍留白(藍底)的寬高
5. scaleWidth , scaleHeight 是縮放過後的image與實際image的寬高比例
6. scalePointX , scalePointY 是指MouseMove的XY經過比例換算後的位置(考慮留白區)
7. realPointX , realPointY 是指scalePointXY經過Display的Pan的偏移後的真實滑鼠指在image的位置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
private void cogRecordDisplay_MouseMove(object sender , MouseEventArgs e)
{
    decimal zoomImgHeight = (decimal)cogRecordDisplay.Image.Height * (decimal)cogRecordDisplay.Zoom;
    decimal zoomImgWidth = (decimal)cogRecordDisplay.Image.Width * (decimal)cogRecordDisplay.Zoom;

    decimal blankWidth = ((decimal)cogRecordDisplay.Width - zoomImgWidth) / 2;
    decimal blankHeight = ((decimal)cogRecordDisplay.Height - zoomImgHeight) / 2;

    decimal scaleWidth = (decimal)cogRecordDisplay.Image.Width / zoomImgWidth;
    decimal scaleHeight = (decimal)cogRecordDisplay.Image.Height / zoomImgHeight;

    decimal scalePointX = Math.Round((e.X - blankWidth) * scaleWidth , MidpointRounding.AwayFromZero);
    decimal scalePointY = Math.Round((e.Y - blankHeight) * scaleHeight , MidpointRounding.AwayFromZero);

    decimal realPointX = scalePointX - (decimal)cogRecordDisplay.PanX;
    decimal realPointY = scalePointY - (decimal)cogRecordDisplay.PanY;
    tsslGreyValue.Text = ((CogImage8Grey)cogRecordDisplay.Image).GetPixel(Convert.ToInt32(realPointX) , Convert.ToInt32(realPointY)).ToString();
}

沒有留言: