** 1、 隐藏功能通过控件的高度调节实现,在if下通过state选择合适高度实现隐藏展开;
** 2、 委托实现重画与移除;所有委托在areatool的构造函数中,防止每次绘制挂载一次而多次执行;
** 3、通过列表存储相关工具,使用foreach对所有选择的工具进行执行;
** 4、FlowLayoutPanel 中设置属性滚动条和超出范围切割;
** 5、显示面积结果通过issetting状态标志进行控制;
// Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HalconDotNet;
using System.IO;
namespace vision
{
public partial class Form1 : Form
{
int camnum = 2;
int CurrentCam = 1;
string path = Application.StartupPath;
string curpath;
int curindex = 0;
List<string> allim;//图片列表
HObject curimage;
public Form1()
{
InitializeComponent();
HOperatorSet.GenEmptyObj(out curimage);
}
private void button1_Click(object sender, EventArgs e)
{
if (CurrentCam > 1)
{
CurrentCam--;
label1.Text = "相机" + CurrentCam.ToString();
curpath = path + @"\CCD" + CurrentCam.ToString();
getallim();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (CurrentCam < camnum)
{
CurrentCam++;
label1.Text = "相机" + CurrentCam.ToString();
curpath = path + @"\CCD" + CurrentCam.ToString();
getallim();
}
}
private void Form1_Load(object sender, EventArgs e)
{
curpath = path + @"\CCD1";
allim = new List<string>();
curpath = path + @"\CCD" + CurrentCam.ToString();
getallim();
alltool = new List<ImageTool>();//所有工具列表;变量实例化
}
void getallim()
{
//获取当前文件夹下bmp的数量和路径
allim.Clear();
DirectoryInfo Dir = new DirectoryInfo(curpath);
foreach (FileInfo FI in Dir.GetFiles())
{
// 这里写文件格式
if (System.IO.Path.GetExtension(FI.Name) == ".bmp")
{
allim.Add(FI.DirectoryName + @"\" + FI.Name);
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (curindex - 1 > 0)
{
HOperatorSet.ReadImage(out curimage, allim[curindex - 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex--;
button4.Enabled = true;
}
else if (curindex - 1 == 0)
{
HOperatorSet.ReadImage(out curimage, allim[curindex - 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex--;
button3.Enabled = false;
}
else
{
}
if ( curimage != null)//将所有工具的效果作用在新换的图片上;
{
foreach (ImageTool t in alltool)
{
t.image = curimage;
t.method();
t.dispresult();
}
}
}
private void button4_Click(object sender, EventArgs e)
{
if (curindex + 1 < allim.Count - 1)
{
HOperatorSet.ReadImage(out curimage, allim[curindex + 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex++;
button3.Enabled = true;
}
else if (curindex + 1 == allim.Count - 1)
{
HOperatorSet.ReadImage(out curimage, allim[curindex + 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex++;
button4.Enabled = false;
}
else
{
}
if ( curimage != null)
{
foreach (ImageTool t in alltool)
{
t.image = curimage;
t.method();
t.dispresult();
}
}
}
//ImageTool mytool;
List<ImageTool> alltool;//所有工具列表;变量声明
private void button5_Click(object sender, EventArgs e)
{
hWindowControl1.Focus();
areatool areat = new areatool();
areat.hwin = hWindowControl1.HalconWindow;
areat.image = curimage;
areat.pannel = flowLayoutPanel1;
areat.draw();
areat.init();
areat.method();
alltool.Add(areat);//点击一次向所有工具列表中添加一次工具
areat.temp = alltool;//将临时工具列表更新
flowLayoutPanel1.Controls.Add(areat.con);
}
}
}
// areacon.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace vision
{
public partial class areacon : UserControl
{
public areacon()
{
InitializeComponent();
}
//委托
public delegate void SetChangeHandler();
public event SetChangeHandler SetChangeEvent;
public delegate void redrawHandler();
public event redrawHandler redrawEvent;
public delegate void RemoveHandler();
public event RemoveHandler RemoveEvent;
int lowthresh, highthresh, larea, harea;
public int Lowthresh
{
set { lowthresh = value; trackBar1.Value = value; }
get { return trackBar1.Value; }
}
public int Highthresh
{
set { highthresh = value; trackBar2.Value = value; }
get { return trackBar2.Value; }
}
public int Larea
{
set { larea = value; textBox1.Text = value.ToString(); }
get { return Convert.ToInt32(textBox1.Text); }
}
public int Harea
{
set { harea = value; textBox2.Text = value.ToString(); }
get { return Convert.ToInt32(textBox2.Text); }
}
public int areaval
{
set { label6.Text = value.ToString(); }
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
SetChangeEvent();
}
private void trackBar2_Scroll(object sender, EventArgs e)
{
SetChangeEvent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SetChangeEvent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
SetChangeEvent();
}
bool state = true;
private void button2_Click(object sender, EventArgs e)
{
if (state)//改变高度实现隐藏展开
{
this.Height = 40;
state = !state;
}
else
{
this.Height = 189;
state = !state;
}
}
private void button1_Click(object sender, EventArgs e)//重画
{
button3.Enabled = false;
redrawEvent();
button3.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)//移除
{
RemoveEvent();
}
}
}
// ImageTool.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HalconDotNet;
namespace vision
{
class ImageTool
{
public HWindow hwin;
public HObject image;
public virtual void draw()
{ }
public virtual void init()
{ }
public virtual void method()
{ }
public virtual void dispresult()
{ }
public virtual void afterdraw()
{ }
}
}
// areatool.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HalconDotNet;
using System.Windows.Forms;
namespace vision
{
class areatool:ImageTool
{
public HObject imreduce, result;
HTuple r1, c1, r2, c2, r, c, area;
HObject roi;
public areacon con;
public FlowLayoutPanel pannel;
double lowthresh, hightresh, larea, harea;
public bool logicresult;
public List<ImageTool> temp;//临时全部工具列表
public areatool()
{
con = new areacon();//委托
con.SetChangeEvent += new areacon.SetChangeHandler(afterdraw);
con.redrawEvent += new areacon.redrawHandler(draw);
con.RemoveEvent += new areacon.RemoveHandler(remove);
}
public void remove()
{
pannel.Controls.Remove(con);//面板中去除
temp.Remove(this);//临时列表中移除
}
public override void draw()
{
HOperatorSet.SetColor(hwin, "red");
HOperatorSet.GenEmptyObj(out roi);
HOperatorSet.DrawRectangle1(hwin, out r1, out c1, out r2, out c2);
HOperatorSet.GenRectangle1(out roi, r1, c1, r2, c2);
afterdraw();
}
public override void init()
{
HOperatorSet.GenEmptyObj(out roi);
HOperatorSet.GenRectangle1(out roi, r1, c1, r2, c2);
HOperatorSet.GenEmptyObj(out imreduce);
HOperatorSet.GenEmptyObj(out result);
}
public override void method()
{
HOperatorSet.ReduceDomain(image, roi, out imreduce);
HOperatorSet.Threshold(imreduce, out result, lowthresh, hightresh);
HOperatorSet.AreaCenter(result, out area, out r, out c);
if (area > larea && area < harea)
{
logicresult = true;
}
else
{
logicresult = false;
}
}
public bool issetting = true;//面积更新标志位
public override void dispresult()
{
if (logicresult)
{
HOperatorSet.SetColor(hwin, "green");
HOperatorSet.DispObj(result, hwin);
}
else
{
HOperatorSet.SetColor(hwin, "red");
HOperatorSet.DispObj(result, hwin);
}
if (issetting)
{
con.areaval = area;
}
}
public override void afterdraw()
{
HOperatorSet.DispObj(image, hwin);
lowthresh = con.Lowthresh;
hightresh = con.Highthresh;
larea = con.Larea;
harea = con.Harea;
method();
con.areaval = area;
dispresult();
}
public void disp_message(HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem,
HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box)
{
// Local iconic variables
// Local control variables
HTuple hv_Red = null, hv_Green = null, hv_Blue = null;
HTuple hv_Row1Part = null, hv_Column1Part = null, hv_Row2Part = null;
HTuple hv_Column2Part = null, hv_RowWin = null, hv_ColumnWin = null;
HTuple hv_WidthWin = null, hv_HeightWin = null, hv_MaxAscent = null;
HTuple hv_MaxDescent = null, hv_MaxWidth = null, hv_MaxHeight = null;
HTuple hv_R1 = new HTuple(), hv_C1 = new HTuple(), hv_FactorRow = new HTuple();
HTuple hv_FactorColumn = new HTuple(), hv_UseShadow = null;
HTuple hv_ShadowColor = null, hv_Exception = new HTuple();
HTuple hv_Width = new HTuple(), hv_Index = new HTuple();
HTuple hv_Ascent = new HTuple(), hv_Descent = new HTuple();
HTuple hv_W = new HTuple(), hv_H = new HTuple(), hv_FrameHeight = new HTuple();
HTuple hv_FrameWidth = new HTuple(), hv_R2 = new HTuple();
HTuple hv_C2 = new HTuple(), hv_DrawMode = new HTuple();
HTuple hv_CurrentColor = new HTuple();
HTuple hv_Box_COPY_INP_TMP = hv_Box.Clone();
HTuple hv_Color_COPY_INP_TMP = hv_Color.Clone();
HTuple hv_Column_COPY_INP_TMP = hv_Column.Clone();
HTuple hv_Row_COPY_INP_TMP = hv_Row.Clone();
HTuple hv_String_COPY_INP_TMP = hv_String.Clone();
// Initialize local and output iconic variables
//This procedure displays text in a graphics window.
//
//Input parameters:
//WindowHandle: The WindowHandle of the graphics window, where
// the message should be displayed
//String: A tuple of strings containing the text message to be displayed
//CoordSystem: If set to 'window', the text position is given
// with respect to the window coordinate system.
// If set to 'image', image coordinates are used.
// (This may be useful in zoomed images.)
//Row: The row coordinate of the desired text position
// If set to -1, a default value of 12 is used.
//Column: The column coordinate of the desired text position
// If set to -1, a default value of 12 is used.
//Color: defines the color of the text as string.
// If set to [], '' or 'auto' the currently set color is used.
// If a tuple of strings is passed, the colors are used cyclically
// for each new textline.
//Box: If Box[0] is set to 'true', the text is written within an orange box.
// If set to' false', no box is displayed.
// If set to a color string (e.g. 'white', '#FF00CC', etc.),
// the text is written in a box of that color.
// An optional second value for Box (Box[1]) controls if a shadow is displayed:
// 'true' -> display a shadow in a default color
// 'false' -> display no shadow (same as if no second value is given)
// otherwise -> use given string as color string for the shadow color
//
//Prepare window
HOperatorSet.GetRgb(hv_WindowHandle, out hv_Red, out hv_Green, out hv_Blue);
HOperatorSet.GetPart(hv_WindowHandle, out hv_Row1Part, out hv_Column1Part, out hv_Row2Part,
out hv_Column2Part);
HOperatorSet.GetWindowExtents(hv_WindowHandle, out hv_RowWin, out hv_ColumnWin,
out hv_WidthWin, out hv_HeightWin);
HOperatorSet.SetPart(hv_WindowHandle, 0, 0, hv_HeightWin - 1, hv_WidthWin - 1);
//
//default settings
if ((int)(new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(-1))) != 0)
{
hv_Row_COPY_INP_TMP = 12;
}
if ((int)(new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(-1))) != 0)
{
hv_Column_COPY_INP_TMP = 12;
}
if ((int)(new HTuple(hv_Color_COPY_INP_TMP.TupleEqual(new HTuple()))) != 0)
{
hv_Color_COPY_INP_TMP = "";
}
//
hv_String_COPY_INP_TMP = ((("" + hv_String_COPY_INP_TMP) + "")).TupleSplit("\n");
//
//Estimate extentions of text depending on font size.
HOperatorSet.GetFontExtents(hv_WindowHandle, out hv_MaxAscent, out hv_MaxDescent,
out hv_MaxWidth, out hv_MaxHeight);
if ((int)(new HTuple(hv_CoordSystem.TupleEqual("window"))) != 0)
{
hv_R1 = hv_Row_COPY_INP_TMP.Clone();
hv_C1 = hv_Column_COPY_INP_TMP.Clone();
}
else
{
//Transform image to window coordinates
hv_FactorRow = (1.0 * hv_HeightWin) / ((hv_Row2Part - hv_Row1Part) + 1);
hv_FactorColumn = (1.0 * hv_WidthWin) / ((hv_Column2Part - hv_Column1Part) + 1);
hv_R1 = ((hv_Row_COPY_INP_TMP - hv_Row1Part) + 0.5) * hv_FactorRow;
hv_C1 = ((hv_Column_COPY_INP_TMP - hv_Column1Part) + 0.5) * hv_FactorColumn;
}
//
//Display text box depending on text size
hv_UseShadow = 1;
hv_ShadowColor = "gray";
if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(0))).TupleEqual("true"))) != 0)
{
if (hv_Box_COPY_INP_TMP == null)
hv_Box_COPY_INP_TMP = new HTuple();
hv_Box_COPY_INP_TMP[0] = "#fce9d4";
hv_ShadowColor = "#f28d26";
}
if ((int)(new HTuple((new HTuple(hv_Box_COPY_INP_TMP.TupleLength())).TupleGreater(
1))) != 0)
{
if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(1))).TupleEqual("true"))) != 0)
{
//Use default ShadowColor set above
}
else if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(1))).TupleEqual(
"false"))) != 0)
{
hv_UseShadow = 0;
}
else
{
hv_ShadowColor = hv_Box_COPY_INP_TMP[1];
//Valid color?
try
{
HOperatorSet.SetColor(hv_WindowHandle, hv_Box_COPY_INP_TMP.TupleSelect(
1));
}
// catch (Exception)
catch (HalconException HDevExpDefaultException1)
{
HDevExpDefaultException1.ToHTuple(out hv_Exception);
hv_Exception = "Wrong value of control parameter Box[1] (must be a 'true', 'false', or a valid color string)";
throw new HalconException(hv_Exception);
}
}
}
if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(0))).TupleNotEqual("false"))) != 0)
{
//Valid color?
try
{
HOperatorSet.SetColor(hv_WindowHandle, hv_Box_COPY_INP_TMP.TupleSelect(0));
}
// catch (Exception)
catch (HalconException HDevExpDefaultException1)
{
HDevExpDefaultException1.ToHTuple(out hv_Exception);
hv_Exception = "Wrong value of control parameter Box[0] (must be a 'true', 'false', or a valid color string)";
throw new HalconException(hv_Exception);
}
//Calculate box extents
hv_String_COPY_INP_TMP = (" " + hv_String_COPY_INP_TMP) + " ";
hv_Width = new HTuple();
for (hv_Index = 0; (int)hv_Index <= (int)((new HTuple(hv_String_COPY_INP_TMP.TupleLength()
)) - 1); hv_Index = (int)hv_Index + 1)
{
HOperatorSet.GetStringExtents(hv_WindowHandle, hv_String_COPY_INP_TMP.TupleSelect(
hv_Index), out hv_Ascent, out hv_Descent, out hv_W, out hv_H);
hv_Width = hv_Width.TupleConcat(hv_W);
}
hv_FrameHeight = hv_MaxHeight * (new HTuple(hv_String_COPY_INP_TMP.TupleLength()
));
hv_FrameWidth = (((new HTuple(0)).TupleConcat(hv_Width))).TupleMax();
hv_R2 = hv_R1 + hv_FrameHeight;
hv_C2 = hv_C1 + hv_FrameWidth;
//Display rectangles
HOperatorSet.GetDraw(hv_WindowHandle, out hv_DrawMode);
HOperatorSet.SetDraw(hv_WindowHandle, "fill");
//Set shadow color
HOperatorSet.SetColor(hv_WindowHandle, hv_ShadowColor);
if ((int)(hv_UseShadow) != 0)
{
HOperatorSet.DispRectangle1(hv_WindowHandle, hv_R1 + 1, hv_C1 + 1, hv_R2 + 1, hv_C2 + 1);
}
//Set box color
HOperatorSet.SetColor(hv_WindowHandle, hv_Box_COPY_INP_TMP.TupleSelect(0));
HOperatorSet.DispRectangle1(hv_WindowHandle, hv_R1, hv_C1, hv_R2, hv_C2);
HOperatorSet.SetDraw(hv_WindowHandle, hv_DrawMode);
}
//Write text.
for (hv_Index = 0; (int)hv_Index <= (int)((new HTuple(hv_String_COPY_INP_TMP.TupleLength()
)) - 1); hv_Index = (int)hv_Index + 1)
{
hv_CurrentColor = hv_Color_COPY_INP_TMP.TupleSelect(hv_Index % (new HTuple(hv_Color_COPY_INP_TMP.TupleLength()
)));
if ((int)((new HTuple(hv_CurrentColor.TupleNotEqual(""))).TupleAnd(new HTuple(hv_CurrentColor.TupleNotEqual(
"auto")))) != 0)
{
HOperatorSet.SetColor(hv_WindowHandle, hv_CurrentColor);
}
else
{
HOperatorSet.SetRgb(hv_WindowHandle, hv_Red, hv_Green, hv_Blue);
}
hv_Row_COPY_INP_TMP = hv_R1 + (hv_MaxHeight * hv_Index);
HOperatorSet.SetTposition(hv_WindowHandle, hv_Row_COPY_INP_TMP, hv_C1);
HOperatorSet.WriteString(hv_WindowHandle, hv_String_COPY_INP_TMP.TupleSelect(
hv_Index));
}
//Reset changed window settings
HOperatorSet.SetRgb(hv_WindowHandle, hv_Red, hv_Green, hv_Blue);
HOperatorSet.SetPart(hv_WindowHandle, hv_Row1Part, hv_Column1Part, hv_Row2Part,
hv_Column2Part);
return;
}
}
}
** 1、将工具序列化进行保存,反序列化进行加载 ;( [Serializabie] [NonSerialized] 关键字)htuple需转换为int或double等,在进行序列化 ;存储在.dat文件中;
** 2、 委托的加载与取消加载 ;
// C# 序列化与反序列化意义详解
// 总结:
// 1、序列化基本是指把一个对象保存到文件或流中,比如可以把文件序列化以保存到Xml中,或一个磁盘文件中
// 2、序列化以某种存储形式使自定义对象持久化;
// 3、将对象从一个地方传递到另一个地方。
// 4、将类的值转化为一个一般的(即连续的)字节流,然后就可以将该流写到磁盘文件或任何其他流化目标上。
// 5、序列是指将对象的实例状态存储到存储媒体的过程。
// 6、在此过程中,先将对象的公共字段以及类的名称(包括类的程序集)转换为字节流,然后再把字节流写入数据流。在随后对对象进行反序列化时,将创建出与原对象完全相同的副本。
// 7、用处非常大,用于数据传输,对象存贮等。
// 序列化与反序列化例子:
using System;
using System.Collections.Generic;
using System.IO; //文件操作相关
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary; //包含 BinaryFormatter类,该类可用于以二进制格式将对象序列化和反序列化。
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Program P = new Program();
P.SerializeStudent();
P.DeSerializeStudent();
}
public void SerializeStudent()
{
Student c = new Student();
c.Id = 0;
c.Name = "liang";
c.Sex = "女";
c.Qq = "676596050";
c.Homepage = "http://www.zrrj.net";
//创建二进制文件temp.dat
FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
//将Student实例对象序列化给fileStream流:其含义是这时候的Student对象已经存储到temp.dat文件中
b.Serialize(fileStream, c);
fileStream.Flush();
fileStream.Close();
fileStream.Dispose();
}
public void DeSerializeStudent()
{
Student c = new Student();
//下面三个属性输出时没有更改,因为反序列化实例化了一个新的Student
c.Id = 1;
c.Qq = "676596051";
c.Homepage = "http://www.zrrj.net";
FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
BinaryFormatter b = new BinaryFormatter();
//将temp.dat 的文件流反序列化为Student
c = b.Deserialize(fileStream) as Student;
c.Name = "liang";
c.Sex = "男";
Console.Write("编号:" + c.Id + "\n姓名:" + c.Name + "\n性别:" + c.Sex + "\nQQ:" + c.Qq + "\n主页:" + c.Homepage);
Console.ReadLine();
//释放文件流资源
fileStream.Flush();
fileStream.Close();
fileStream.Dispose();
}
/// <summary>
/// 创建6个可读可写的属性
/// </summary>
[Serializable]
public class Student
{
//编号
private int id;
//姓名
private string name;
//性别
private string sex;
//QQ
private string qq;
//主页
private string homepage;
public int Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Sex
{
get { return sex; }
set { sex = value; }
}
public string Qq
{
get { return qq; }
set { qq = value; }
}
public string Homepage
{
get { return homepage; }
set { homepage = value; }
}
}
}
}
// Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HalconDotNet;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;//包含 BinaryFormatter类,该类可用于以二进制格式将对象序列化和反序列化。
namespace vision
{
public partial class Form1 : Form
{
int camnum = 2;
int CurrentCam = 1;
string path = Application.StartupPath;
string curpath;
int curindex = 0;
List<string> allim;
HObject curimage;
public Form1()
{
InitializeComponent();
HOperatorSet.GenEmptyObj(out curimage);
}
private void button1_Click(object sender, EventArgs e)
{
if (CurrentCam > 1)
{
CurrentCam--;
label1.Text = "相机" + CurrentCam.ToString();
curpath = path + @"\CCD" + CurrentCam.ToString();
getallim();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (CurrentCam < camnum)
{
CurrentCam++;
label1.Text = "相机" + CurrentCam.ToString();
curpath = path + @"\CCD" + CurrentCam.ToString();
getallim();
}
}
private void Form1_Load(object sender, EventArgs e)
{
curpath = path + @"\CCD1";
allim = new List<string>();
curpath = path + @"\CCD" + CurrentCam.ToString();
getallim();
}
void getallim()
{
//获取当前文件夹下bmp的数量和路径
allim.Clear();
DirectoryInfo Dir = new DirectoryInfo(curpath);
foreach (FileInfo FI in Dir.GetFiles())
{
// 这里写文件格式
if (System.IO.Path.GetExtension(FI.Name) == ".bmp")
{
allim.Add(FI.DirectoryName + @"\" + FI.Name);
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (curindex - 1 > 0)
{
HOperatorSet.ReadImage(out curimage, allim[curindex - 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex--;
button4.Enabled = true;
}
else if (curindex - 1 == 0)
{
HOperatorSet.ReadImage(out curimage, allim[curindex - 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex--;
button3.Enabled = false;
}
else
{
}
if (curimage != null)
{
foreach (ImageTool t in toollist)
{
t.image = curimage;
t.method();
t.dispresult();
}
}
}
private void button4_Click(object sender, EventArgs e)
{
if (curindex + 1 < allim.Count - 1)
{
HOperatorSet.ReadImage(out curimage, allim[curindex + 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex++;
button3.Enabled = true;
}
else if (curindex + 1 == allim.Count - 1)
{
HOperatorSet.ReadImage(out curimage, allim[curindex + 1]);
HTuple width, height;
HOperatorSet.GetImageSize(curimage, out width, out height);
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
hWindowControl1.HalconWindow.DispObj(curimage);
curindex++;
button4.Enabled = false;
}
else
{
}
if (curimage != null)
{
foreach (ImageTool t in toollist)
{
t.image = curimage;
t.method();
t.dispresult();
}
}
}
List<ImageTool> toollist = new List<ImageTool>();
private void button5_Click(object sender, EventArgs e)
{
hWindowControl1.Focus();
areatool areat = new areatool();
areat.hwin = hWindowControl1.HalconWindow;
areat.image = curimage;
areat.pannel = flowLayoutPanel1;
areat.issetting = true;//决定按下工具一后执行afterdraw是否改变面积显示值
areat.draw();
areat.init();
areat.method();
toollist.Add(areat);//将新建的工具添加到工具列表中
flowLayoutPanel1.Controls.Add(areat.con);//将控件添加到面板容器中
areat.temp = toollist;//同步到临时工具列表
}
private void button6_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(path + @"\" + CurrentCam + ".dat", FileMode.Create, FileAccess.Write);//创建FileStream对象;创建二进制文件
BinaryFormatter bf = new BinaryFormatter();//将imagetool和areatool实例对象序列化给fileStream流:其含义是这时候的实例对象已经存储到.dat文件中
//BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, toollist);//释放文件资源
fs.Close();
}
private void button7_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(path + @"\" + CurrentCam + ".dat", FileMode.Open, FileAccess.Read);//创建FileStream对象;读取二进制文件
BinaryFormatter bf = new BinaryFormatter();
toollist = (List<ImageTool>)bf.Deserialize(fs);//反序列化
fs.Close();//释放资源
foreach (ImageTool t in toollist)//遍历工具效果
{
t.init();
t.image = curimage;
t.temp = toollist;
t.hwin = hWindowControl1.HalconWindow;
t.pannel = flowLayoutPanel1;
t.issetting = true;//决定加载出来的工具执行afterdraw是否将结果显示;加载后在工具父类中默认修改为零,未进行置一则不改变显示;
t.recon();//重新加载反序列化的数据;
flowLayoutPanel1.Controls.Add(t.con1);//将控件加到面板容器
}
}
}
}
// areacon.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace vision
{
public partial class areacon : UserControl
{
public areacon()
{
InitializeComponent();
}
public delegate void SetChangeHandler();
public event SetChangeHandler SetChangeEvent;
public delegate void redrawHandler();
public event redrawHandler redrawEvent;
public delegate void RemoveHandler();
public event RemoveHandler RemoveEvent;
public bool state = true;
int lowthresh, highthresh, larea, harea;
public int Lowthresh
{
set { lowthresh = value; trackBar1.Value = value; }
get { return trackBar1.Value; }
}
public int Highthresh
{
set { highthresh = value; trackBar2.Value = value; }
get { return trackBar2.Value; }
}
public int Larea
{
set { larea = value; textBox1.Text = value.ToString(); }
get { return Convert.ToInt32(textBox1.Text); }
}
public int Harea
{
set { harea = value; textBox2.Text = value.ToString(); }
get { return Convert.ToInt32(textBox2.Text); }
}
public int areaval
{
set { label6.Text = value.ToString(); }
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
SetChangeEvent();
}
private void trackBar2_Scroll(object sender, EventArgs e)
{
SetChangeEvent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SetChangeEvent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
SetChangeEvent();
}
private void button1_Click(object sender, EventArgs e)//重画
{
button3.Enabled = false;
redrawEvent();
button3.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)//折叠
{
if (state)
{
this.Height = 40;
state = !state;
}
else
{
this.Height = 189;
state = !state;
}
}
private void button3_Click(object sender, EventArgs e)//移除
{
RemoveEvent();
}
public void setval(double threshl,double threshh,double areal,double areah)//反序列化数据格式转换
{
trackBar1.Scroll -= new EventHandler(trackBar1_Scroll);
trackBar2.Scroll -= new EventHandler(trackBar2_Scroll);
textBox1.TextChanged -= new EventHandler(textBox1_TextChanged);
textBox2.TextChanged -= new EventHandler(textBox2_TextChanged);
trackBar1.Value = Convert.ToInt32(threshl);
trackBar2.Value = Convert.ToInt32(threshh);
textBox1.Text = areal.ToString();
textBox2.Text = areah.ToString();
trackBar1.Scroll += new EventHandler(trackBar1_Scroll);
trackBar2.Scroll += new EventHandler(trackBar2_Scroll);
textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
textBox2.TextChanged += new EventHandler(textBox2_TextChanged);
}
}
}
// ImageTool.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HalconDotNet;
using System.Windows.Forms;
namespace vision
{
[Serializable]//序列化类
class ImageTool
{
[NonSerialized]//不需要序列化的数据标记出来
public HWindow hwin;
[NonSerialized]
public HObject image;
[NonSerialized]
public bool issetting=false;
[NonSerialized]
public FlowLayoutPanel pannel;
[NonSerialized]
public UserControl con1;
[NonSerialized]
public List<ImageTool> temp;
public virtual void draw()
{ }
public virtual void init()
{ }
public virtual void method()
{ }
public virtual void dispresult()
{ }
public virtual void afterdraw()
{ }
public virtual void recon()
{ }
}
}
// areatool.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HalconDotNet;
using System.Windows.Forms;
namespace vision
{
[Serializable]//序列化类
class areatool:ImageTool
{
[NonSerialized]//不需要序列化的数据标记出来
public HObject imreduce, result;
[NonSerialized]
HTuple r1, c1, r2, c2, r, c, area;//halcon中的元组不能再C#中进行序列化
[NonSerialized]
HObject roi;
[NonSerialized]
public areacon con;
double lowthresh, hightresh, larea, harea,row1,col1,row2,col2;
[NonSerialized]
public bool logicresult;
public areatool()
{
con = new areacon();
con.SetChangeEvent += new areacon.SetChangeHandler(afterdraw);
con.redrawEvent += new areacon.redrawHandler(this.draw);
con.RemoveEvent += new areacon.RemoveHandler(remove);
con1 = con;
}
public override void draw()
{
HOperatorSet.SetColor(hwin, "red");
HOperatorSet.GenEmptyObj(out roi);
HOperatorSet.DrawRectangle1(hwin, out r1, out c1, out r2, out c2);
HOperatorSet.GenRectangle1(out roi, r1, c1, r2, c2);
row1=r1.D;
col1=c1.D;
row2 = r2.D;
col2 = c2.D;
afterdraw();
}
private void remove()
{
// HOperatorSet.ClearMetrologyModel(MetrologyHandle);
pannel.Controls.Remove(con);//移除面板中控件
temp.Remove(this);//临时工具列表中控件移除
}
public override void init()
{
HOperatorSet.GenEmptyObj(out roi);
HOperatorSet.GenRectangle1(out roi, row1, col1, row2, col2);
HOperatorSet.GenEmptyObj(out imreduce);
HOperatorSet.GenEmptyObj(out result);
}
public override void method()
{
HOperatorSet.ReduceDomain(image, roi, out imreduce);
HOperatorSet.Threshold(imreduce, out result, lowthresh, hightresh);
HOperatorSet.AreaCenter(result, out area, out r, out c);
if (area > larea && area < harea)
{
logicresult = true;
}
else
{
logicresult = false;
}
}
public override void dispresult()
{
if (logicresult)
{
HOperatorSet.SetColor(hwin, "green");
HOperatorSet.DispObj(result, hwin);
}
else
{
HOperatorSet.SetColor(hwin, "red");
HOperatorSet.DispObj(result, hwin);
}
if (issetting)
{
con.areaval = area;
}
}
public override void afterdraw()
{
HOperatorSet.DispObj(image, hwin);
lowthresh = con.Lowthresh;
hightresh = con.Highthresh;
larea = con.Larea;
harea = con.Harea;
method();
con.areaval = area;
dispresult();
}
public override void recon()//委托挂载是在构造函数中执行,再次加载需再次挂载;并将数据转换为合适的格式
{
con = new areacon();
con.setval(lowthresh, hightresh, larea, harea);
con.SetChangeEvent += new areacon.SetChangeHandler(afterdraw);
con.redrawEvent += new areacon.redrawHandler(this.draw);
con.RemoveEvent += new areacon.RemoveHandler(remove);
con1 = con;
}
public void disp_message(HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem,
HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box)
{
// Local iconic variables
// Local control variables
HTuple hv_Red = null, hv_Green = null, hv_Blue = null;
HTuple hv_Row1Part = null, hv_Column1Part = null, hv_Row2Part = null;
HTuple hv_Column2Part = null, hv_RowWin = null, hv_ColumnWin = null;
HTuple hv_WidthWin = null, hv_HeightWin = null, hv_MaxAscent = null;
HTuple hv_MaxDescent = null, hv_MaxWidth = null, hv_MaxHeight = null;
HTuple hv_R1 = new HTuple(), hv_C1 = new HTuple(), hv_FactorRow = new HTuple();
HTuple hv_FactorColumn = new HTuple(), hv_UseShadow = null;
HTuple hv_ShadowColor = null, hv_Exception = new HTuple();
HTuple hv_Width = new HTuple(), hv_Index = new HTuple();
HTuple hv_Ascent = new HTuple(), hv_Descent = new HTuple();
HTuple hv_W = new HTuple(), hv_H = new HTuple(), hv_FrameHeight = new HTuple();
HTuple hv_FrameWidth = new HTuple(), hv_R2 = new HTuple();
HTuple hv_C2 = new HTuple(), hv_DrawMode = new HTuple();
HTuple hv_CurrentColor = new HTuple();
HTuple hv_Box_COPY_INP_TMP = hv_Box.Clone();
HTuple hv_Color_COPY_INP_TMP = hv_Color.Clone();
HTuple hv_Column_COPY_INP_TMP = hv_Column.Clone();
HTuple hv_Row_COPY_INP_TMP = hv_Row.Clone();
HTuple hv_String_COPY_INP_TMP = hv_String.Clone();
// Initialize local and output iconic variables
//This procedure displays text in a graphics window.
//
//Input parameters:
//WindowHandle: The WindowHandle of the graphics window, where
// the message should be displayed
//String: A tuple of strings containing the text message to be displayed
//CoordSystem: If set to 'window', the text position is given
// with respect to the window coordinate system.
// If set to 'image', image coordinates are used.
// (This may be useful in zoomed images.)
//Row: The row coordinate of the desired text position
// If set to -1, a default value of 12 is used.
//Column: The column coordinate of the desired text position
// If set to -1, a default value of 12 is used.
//Color: defines the color of the text as string.
// If set to [], '' or 'auto' the currently set color is used.
// If a tuple of strings is passed, the colors are used cyclically
// for each new textline.
//Box: If Box[0] is set to 'true', the text is written within an orange box.
// If set to' false', no box is displayed.
// If set to a color string (e.g. 'white', '#FF00CC', etc.),
// the text is written in a box of that color.
// An optional second value for Box (Box[1]) controls if a shadow is displayed:
// 'true' -> display a shadow in a default color
// 'false' -> display no shadow (same as if no second value is given)
// otherwise -> use given string as color string for the shadow color
//
//Prepare window
HOperatorSet.GetRgb(hv_WindowHandle, out hv_Red, out hv_Green, out hv_Blue);
HOperatorSet.GetPart(hv_WindowHandle, out hv_Row1Part, out hv_Column1Part, out hv_Row2Part,
out hv_Column2Part);
HOperatorSet.GetWindowExtents(hv_WindowHandle, out hv_RowWin, out hv_ColumnWin,
out hv_WidthWin, out hv_HeightWin);
HOperatorSet.SetPart(hv_WindowHandle, 0, 0, hv_HeightWin - 1, hv_WidthWin - 1);
//
//default settings
if ((int)(new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(-1))) != 0)
{
hv_Row_COPY_INP_TMP = 12;
}
if ((int)(new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(-1))) != 0)
{
hv_Column_COPY_INP_TMP = 12;
}
if ((int)(new HTuple(hv_Color_COPY_INP_TMP.TupleEqual(new HTuple()))) != 0)
{
hv_Color_COPY_INP_TMP = "";
}
//
hv_String_COPY_INP_TMP = ((("" + hv_String_COPY_INP_TMP) + "")).TupleSplit("\n");
//
//Estimate extentions of text depending on font size.
HOperatorSet.GetFontExtents(hv_WindowHandle, out hv_MaxAscent, out hv_MaxDescent,
out hv_MaxWidth, out hv_MaxHeight);
if ((int)(new HTuple(hv_CoordSystem.TupleEqual("window"))) != 0)
{
hv_R1 = hv_Row_COPY_INP_TMP.Clone();
hv_C1 = hv_Column_COPY_INP_TMP.Clone();
}
else
{
//Transform image to window coordinates
hv_FactorRow = (1.0 * hv_HeightWin) / ((hv_Row2Part - hv_Row1Part) + 1);
hv_FactorColumn = (1.0 * hv_WidthWin) / ((hv_Column2Part - hv_Column1Part) + 1);
hv_R1 = ((hv_Row_COPY_INP_TMP - hv_Row1Part) + 0.5) * hv_FactorRow;
hv_C1 = ((hv_Column_COPY_INP_TMP - hv_Column1Part) + 0.5) * hv_FactorColumn;
}
//
//Display text box depending on text size
hv_UseShadow = 1;
hv_ShadowColor = "gray";
if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(0))).TupleEqual("true"))) != 0)
{
if (hv_Box_COPY_INP_TMP == null)
hv_Box_COPY_INP_TMP = new HTuple();
hv_Box_COPY_INP_TMP[0] = "#fce9d4";
hv_ShadowColor = "#f28d26";
}
if ((int)(new HTuple((new HTuple(hv_Box_COPY_INP_TMP.TupleLength())).TupleGreater(
1))) != 0)
{
if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(1))).TupleEqual("true"))) != 0)
{
//Use default ShadowColor set above
}
else if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(1))).TupleEqual(
"false"))) != 0)
{
hv_UseShadow = 0;
}
else
{
hv_ShadowColor = hv_Box_COPY_INP_TMP[1];
//Valid color?
try
{
HOperatorSet.SetColor(hv_WindowHandle, hv_Box_COPY_INP_TMP.TupleSelect(
1));
}
// catch (Exception)
catch (HalconException HDevExpDefaultException1)
{
HDevExpDefaultException1.ToHTuple(out hv_Exception);
hv_Exception = "Wrong value of control parameter Box[1] (must be a 'true', 'false', or a valid color string)";
throw new HalconException(hv_Exception);
}
}
}
if ((int)(new HTuple(((hv_Box_COPY_INP_TMP.TupleSelect(0))).TupleNotEqual("false"))) != 0)
{
//Valid color?
try
{
HOperatorSet.SetColor(hv_WindowHandle, hv_Box_COPY_INP_TMP.TupleSelect(0));
}
// catch (Exception)
catch (HalconException HDevExpDefaultException1)
{
HDevExpDefaultException1.ToHTuple(out hv_Exception);
hv_Exception = "Wrong value of control parameter Box[0] (must be a 'true', 'false', or a valid color string)";
throw new HalconException(hv_Exception);
}
//Calculate box extents
hv_String_COPY_INP_TMP = (" " + hv_String_COPY_INP_TMP) + " ";
hv_Width = new HTuple();
for (hv_Index = 0; (int)hv_Index <= (int)((new HTuple(hv_String_COPY_INP_TMP.TupleLength()
)) - 1); hv_Index = (int)hv_Index + 1)
{
HOperatorSet.GetStringExtents(hv_WindowHandle, hv_String_COPY_INP_TMP.TupleSelect(
hv_Index), out hv_Ascent, out hv_Descent, out hv_W, out hv_H);
hv_Width = hv_Width.TupleConcat(hv_W);
}
hv_FrameHeight = hv_MaxHeight * (new HTuple(hv_String_COPY_INP_TMP.TupleLength()
));
hv_FrameWidth = (((new HTuple(0)).TupleConcat(hv_Width))).TupleMax();
hv_R2 = hv_R1 + hv_FrameHeight;
hv_C2 = hv_C1 + hv_FrameWidth;
//Display rectangles
HOperatorSet.GetDraw(hv_WindowHandle, out hv_DrawMode);
HOperatorSet.SetDraw(hv_WindowHandle, "fill");
//Set shadow color
HOperatorSet.SetColor(hv_WindowHandle, hv_ShadowColor);
if ((int)(hv_UseShadow) != 0)
{
HOperatorSet.DispRectangle1(hv_WindowHandle, hv_R1 + 1, hv_C1 + 1, hv_R2 + 1, hv_C2 + 1);
}
//Set box color
HOperatorSet.SetColor(hv_WindowHandle, hv_Box_COPY_INP_TMP.TupleSelect(0));
HOperatorSet.DispRectangle1(hv_WindowHandle, hv_R1, hv_C1, hv_R2, hv_C2);
HOperatorSet.SetDraw(hv_WindowHandle, hv_DrawMode);
}
//Write text.
for (hv_Index = 0; (int)hv_Index <= (int)((new HTuple(hv_String_COPY_INP_TMP.TupleLength()
)) - 1); hv_Index = (int)hv_Index + 1)
{
hv_CurrentColor = hv_Color_COPY_INP_TMP.TupleSelect(hv_Index % (new HTuple(hv_Color_COPY_INP_TMP.TupleLength()
)));
if ((int)((new HTuple(hv_CurrentColor.TupleNotEqual(""))).TupleAnd(new HTuple(hv_CurrentColor.TupleNotEqual(
"auto")))) != 0)
{
HOperatorSet.SetColor(hv_WindowHandle, hv_CurrentColor);
}
else
{
HOperatorSet.SetRgb(hv_WindowHandle, hv_Red, hv_Green, hv_Blue);
}
hv_Row_COPY_INP_TMP = hv_R1 + (hv_MaxHeight * hv_Index);
HOperatorSet.SetTposition(hv_WindowHandle, hv_Row_COPY_INP_TMP, hv_C1);
HOperatorSet.WriteString(hv_WindowHandle, hv_String_COPY_INP_TMP.TupleSelect(
hv_Index));
}
//Reset changed window settings
HOperatorSet.SetRgb(hv_WindowHandle, hv_Red, hv_Green, hv_Blue);
HOperatorSet.SetPart(hv_WindowHandle, hv_Row1Part, hv_Column1Part, hv_Row2Part,
hv_Column2Part);
return;
}
}
}