基于C#和Halcon实现的鼠标控制图片缩放、拖动以及ROI绘制
确保你已经安装了Halcon开发环境,并在C#项目中引用了Halcon的DLL文件。
HWindowControl。private void hWindowControl1_HMouseWheel(object sender, HMouseEventArgs e)
{
double zoomFactor = e.Delta > 0 ? 1.1 : 0.9;
HOperatorSet.GetMposition(hWindowControl1.HalconWindow, out int row, out int col, out _);
HOperatorSet.GetPart(hWindowControl1.HalconWindow, out int row1, out int col1, out int row2, out int col2);
int h = row2 - row1;
int w = col2 - col1;
if (h * w < 32000 * 32000 || zoomFactor == 1.1)
{
double r1 = row1 + ((1 - (1.0 / zoomFactor)) * (row - row1));
double c1 = col1 + ((1 - (1.0 / zoomFactor)) * (col - col1));
double r2 = r1 + (h / zoomFactor);
double c2 = c1 + (w / zoomFactor);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, r1, c1, r2, c2);
hWindowControl1.HalconWindow.ClearWindow();
hWindowControl1.HalconWindow.DispObj(image);
}
}private bool isDragging = false;
private Point dragStartPos;
private void hWindowControl1_HMouseDown(object sender, HMouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragging = true;
dragStartPos = new Point(e.X, e.Y);
}
}
private void hWindowControl1_HMouseMove(object sender, HMouseEventArgs e)
{
if (isDragging)
{
int deltaX = e.X - dragStartPos.X;
int deltaY = e.Y - dragStartPos.Y;
hWindowControl1.HalconWindow.GetPart(out int row1, out int col1, out int row2, out int col2);
hWindowControl1.HalconWindow.SetPart(row1 - deltaY, col1 - deltaX, row2 - deltaY, col2 - deltaX);
hWindowControl1.HalconWindow.DispObj(image);
dragStartPos = new Point(e.X, e.Y);
}
}
private void hWindowControl1_HMouseUp(object sender, HMouseEventArgs e)
{
isDragging = false;
}private HObject selectedRegion;
private void btnSelectROI_Click(object sender, EventArgs e)
{
hWindowControl1.HalconWindow.DrawRectangle1(out double row1, out double col1, out double row2, out double col2);
HOperatorSet.GenRectangle1(out selectedRegion, row1, col1, row2, col2);
hWindowControl1.HalconWindow.SetColor("red");
hWindowControl1.HalconWindow.DispObj(selectedRegion);
}在窗体的构造函数中注册上述事件:
public MainForm()
{
InitializeComponent();
hWindowControl1.HMouseWheel += hWindowControl1_HMouseWheel;
hWindowControl1.HMouseDown += hWindowControl1_HMouseDown;
hWindowControl1.HMouseMove += hWindowControl1_HMouseMove;
hWindowControl1.HMouseUp += hWindowControl1_HMouseUp;
}在窗体中添加一个按钮,用于加载图片:
private void btnLoadImage_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "所有图像文件 (*.bmp;*.pcx;*.png;*.jpg;*.gif;*.tif;*.ico;*.dxf;*.cgm;*.cdr;*.wmf;*.eps;*.emf)|*.bmp;*.pcx;*.png;*.jpg;*.gif;*.tif;*.ico;*.dxf;*.cgm;*.cdr;*.wmf;*.eps;*.emf";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
HOperatorSet.ReadImage(out HObject image, openFileDialog.FileName);
hWindowControl1.HalconWindow.DispObj(image);
}
}运行程序后,你可以通过鼠标滚轮实现图片的缩放,按住鼠标左键拖动图片,以及通过按钮绘制ROI区域。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。