FrmAOICheck.cs 15.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

using AccAOI.camera;
using AOI;
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TSA_V.Common;
using TSA_V.DeviceLibrary;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization.Formatters.Binary;

namespace TSA_V
{
    public partial class FrmAOICheck : FrmBase
    {
        private List<ResultBean> ResultList = new List<ResultBean>(); 
        private    AOI.AoiProject CurrProject = null;
        private DateTime showTime = DateTime.Now;
        private DateTime endTime = DateTime.Now;
        private bool IsCheck = false;
        private bool IsUpdate = false;
        /// <summary>
        /// 检测结果,0=未知,1=OK,2=NG
        /// </summary>
        private int  CheckResult =0;
        private int waitSeconds = 0;
        public FrmAOICheck(AoiProject currAoi )
        {
            InitializeComponent();
            CurrProject = currAoi;
            updateMName = new List<string>();
        }
        private void FrmCamera_Load(object sender, EventArgs e)
        {
            FormStatus(false);

            btnUpdateImg.Visible = false;
            timer1.Start();
            lblCurrWorkTime.Visible = true;
            //默认显示程序配置的 图片

            if (CurrProject == null)
            {
                this.Close();
                return;
            }
            lblCurrWorkTime.Text = ResourceCulture.GetString("{0}秒后自动检测", "{0}秒后自动检测", waitSeconds.ToString());
            修正ToolStripMenuItem.Text = ResourceCulture.GetString("FrmAOICheck_btnUpdateImg_Text", "修正");
            //  this.picResult.Image = CurrProject.standardImage;
        }

        private void FormStatus(bool open)
        {
        }
        private bool isAutoClose = false;
        private void UpdateTextResult(Label label, int result)
        {
            if (result.Equals(0))
            {
                label.ForeColor = Color.Orange;
                label.Text = "?";
            }
            else if (result.Equals(1))
            {
                label.Text = "OK";
                label.ForeColor = Color.Green;
            }
            else if (result.Equals(2))
            {
                label.Text = "NG";
                label.ForeColor = Color.Red;
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (IsUpdate)
            {

            }
            else
            {
                btnRun.Visible = !IsCheck; 
            }
           
            TimeSpan span = DateTime.Now - showTime;
            if (!IsCheck)
            { 
                int times = waitSeconds - (int)(span.TotalSeconds);
                if (times > 0)
                { 
                    if (times <= 1)
                    {
                        lblCurrWorkTime.Text = ResourceCulture.GetString("开始自动检测", "开始自动检测") + "......";
                    }else
                    {
                        lblCurrWorkTime.Text = ResourceCulture.GetString("{0}秒后自动检测", "{0}秒后自动检测", times.ToString());
                    }
                    lblCurrWorkTime.Visible = true;
                }
                else
                {
                    lblCurrWorkTime.Text = ResourceCulture.GetString("开始自动检测", "开始自动检测");
                    lblCurrWorkTime.Visible = true;
                    CheckResult = AoiCheck();
                    MesUtil.SetAOIResult(CheckResult);
                    UpdateTextResult(lblResult, CheckResult);
                    if (CheckResult.Equals(1))
                    {
                        isAutoClose = true;
                    }
                    else
                    {
                        isAutoClose = false;
                    }
                }
            }
            else
            {
                lblCurrWorkTime.Text = ResourceCulture.GetString("请点击完成按钮结束检测", "请点击完成按钮结束检测", 0);
                lblCurrWorkTime.Visible = true;
                if (isAutoClose)
                {
                    TimeSpan closeSpan = DateTime.Now - endTime;
                    int times = 3 - (int)(closeSpan.TotalSeconds);
                    if (times < 0)
                    {
                        lblCurrWorkTime.Text = ResourceCulture.GetString("{0}秒后自动完成", "{0}秒后自动完成", 0);
                        lblCurrWorkTime.Visible = true;
                        this.Close();
                    }
                    else
                    {
                        lblCurrWorkTime.Text = ResourceCulture.GetString("{0}秒后自动完成", "{0}秒后自动完成", times.ToString());
                        lblCurrWorkTime.Visible = true;
                    }
                }
            }
        }

        private int AoiCheck()
        {
            GC.Collect(0, GCCollectionMode.Forced);
            //GC.Collect();
            IsCheck = true;
            btnRun.Visible = false;
            lblError.Visible = false;
            lblInfo.Visible = false;
            int result = 2;
            try
            {
                if (CurrProject == null)
                {
                    return 0;
                }
                chbAllShow.Enabled = false;
                
                string camera = ConfigAppSettings.GetValue(Setting_Init.CameraName);
                if (camera == "")
                {
                    camera = AccAOI.camera.CameraManager.hikNameList.ToArray().FirstOrDefault();
                }
                DateTime startTime = DateTime.Now;
                LogUtil.info("AOICheck : 开始获取图片");
                Image currImage = CameraManager.GetCamerImage(camera);

                if (currImage == null)
                {
                    string file = @"G:\test.bmp";
                    if (File.Exists(file))
                    { 
                        //从本地加载图片 
                        Bitmap aa = new Bitmap(file);
                        currImage = ImageManager.DeepClone(aa);
                    }
                }

                if (currImage != null)
                {
                    TimeSpan span1 = DateTime.Now - startTime;
                    LogUtil.info($"AOICheck : 图片获取完成, {Math.Round( span1.TotalMilliseconds,1)}ms, 开始check");
                    //Bitmap bitmap = new Bitmap(currImage);
                    Image outImage = null;
                    List<ResultBean> resultBean = CurrProject.CheckAll(currImage, out outImage);
                    span1 = DateTime.Now - startTime;
                    LogUtil.info($"AOICheck : check完成, {Math.Round(span1.TotalMilliseconds, 1)}ms");
                    currImage.Dispose();
                    ResultList = resultBean;
                    if (outImage != null)
                    {
                        //this.picResult.SelectNone();
                        //picResult.SizeMode = Acc.ImageBox.ImageBoxSizeMode.Fit;
                        this.picResult.Image = outImage;
                        //picResult.SizeMode = Acc.ImageBox.ImageBoxSizeMode.Normal;
                        // pictureBox1.Image = outImage;

                    }
                    else
                    {
                        this.picResult.Image = currImage;
                    }
                    result = 1;
                    endTime = DateTime.Now;
                    string ngList = "NG:\r\n";
                    listErrorView.Items.Clear();
                    foreach (ResultBean bean in resultBean)
                    {
                        if (bean.result.Equals(false))
                        {
                            ngList += bean.MethodName + "\r\n";
                            result = 2;
                            //  break;
                            listErrorView.Items.Add(GetShowName(bean));
                        }else if (chbAllShow.Checked)
                        {

                            listErrorView.Items.Add(GetShowName(bean));
                        }
                    }
                    if (listErrorView.Items.Count > 0)
                    {
                        listErrorView.Items[0].Selected = true ;
                    }

                    chbAllShow.Enabled = true;
                    if (result.Equals(1))
                    {
                        lblError.Visible = false ;
                        lblInfo.Text = AccAOI.ControlUtil.GetResultsStr(resultBean);
                        lblInfo.Visible = true;
                        LogUtil.info("AOI检测OK:" + lblInfo.Text);
                    }
                    else
                    {
                        lblInfo.Visible = false;
                        lblError.Text = ngList;
                        lblError.Visible = true;
                        LogUtil.info("AOI检测NG:" + ngList);
                    }
                }
                else
                {
                    lblError.Text = ResourceCulture.GetString("获取相机图片失败", "获取相机图片失败");
                    lblError.Visible = true;
                    LogUtil.error("AOI检测:获取相机图片失败:" + CameraManager.ErrorMsg);
                    return 0;
                }
                chbAllShow.Enabled = true  ;
            }
            catch (Exception ex)
            {
                lblError.Text = ResourceCulture.GetString("执行检测失败", "执行检测失败");
                lblError.Visible = true;
                LogUtil.error("检测出错:" + ex.ToString());
            }
            return result;
        }
        private string GetShowName(ResultBean bean)
        {
            return (bean.result ? "✔ " : "✘ ") + bean.MethodName;
        }
        private string GetNameByText(string str)
        {
            string name= str.Substring(2, str.Length - 2);
            return name;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            CheckResult = AoiCheck();
            MesUtil.SetAOIResult(CheckResult);
            UpdateTextResult(lblResult, CheckResult); 
            if (CheckResult.Equals(1))
            {
                isAutoClose = true;
            }
            else
            {
                isAutoClose = false;
            }
        }

        private void FrmCameraAOI_Shown(object sender, EventArgs e)
        {
            showTime = DateTime.Now;
        }

        private void btnExit_Click_1(object sender, EventArgs e)
        {
            timer1.Stop();
            this.Close();
        }
        private ResultBean selectResultBean = null;
        private void listErrorView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listErrorView.SelectedItems != null && listErrorView.SelectedItems.Count > 0)
            {
                string selName = GetNameByText(listErrorView.SelectedItems[0].Text) ;
                List<ResultBean> beans = (from m in ResultList where m.MethodName.Equals(selName) select m).ToList<ResultBean>();
                if (beans.Count > 0)
                {
                    ResultBean bean = beans[0];
                    picStand.Image = bean.standardRoiImage;
                    picCurr.Image = ImageManager.DeepClone( bean.currentRoiImage);
                    picResult.SelectionRegion = bean.roiPath;

                   //如果结果NG,可以修正
                   if(!bean.result && (!updateMName.Contains(bean.MethodName)))
                    {
                        selectResultBean = bean;
                        //btnUpdateImg.Visible = true;

                        listErrorView.ContextMenuStrip = this.contextMenuStrip1;
                    }
                    else
                    {
                        listErrorView.ContextMenuStrip = null;
                        btnUpdateImg.Visible = false;
                    }
                    //Graphics g = picResult.CreateGraphics();
                    //g.DrawPath(new Pen(Color.Orange), bean.roiPath);
                    //g.Dispose();
                }
            }
        }

        private void chbAllShow_CheckedChanged(object sender, EventArgs e)
        {
            if (ResultList.Count <= 0)
            {
                return;
            }
            listErrorView.Items.Clear();
            foreach (ResultBean bean in ResultList)
            {
                if (bean.result.Equals(false))
                {
                    listErrorView.Items.Add(GetShowName(bean));
                }
                else if (chbAllShow.Checked)
                { 
                    listErrorView.Items.Add(GetShowName(bean));
                }
            }
            if (listErrorView.Items.Count > 0)
            {
                listErrorView.Items[0].Selected = true;
            }
            listErrorView_SelectedIndexChanged(null, null);
        }
        private string getSaveImagePath(string aoiFileName, ResultBean selectResultBean)
        {
            string path = Path.GetDirectoryName(aoiFileName);
            string fileName = Path.GetFileNameWithoutExtension(aoiFileName);
            System.Drawing.PointF[] pts = selectResultBean.roiPath.PathPoints;
            string pPath = "";
            for (int i = 0; i < pts.Length; i++)
            {
                pPath += (int)pts[i].X + "-" + (int)pts[i].Y + "_";
            }

            return Path.Combine(path, fileName + @"\" + pPath + @"\");
        }

        private List<string> updateMName = new List<string>();
        private void btnUpdateImg_Click(object sender, EventArgs e)
        {
            if (selectResultBean == null)
            {
                return;
            }
            if (picCurr.Image == null)
            {
                return;
            }
            try
            {

                DialogResult result = MessageBox.Show(ResourceCulture.GetString("SureUpdateMethod", "确定修正{0}?",
                    new string[] { selectResultBean.MethodName }), ResourceCulture.GetString("提示"),
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if(result != DialogResult.Yes)
                {
                    return;
                }
                using (Image image = ImageManager.DeepClone(selectResultBean.currentRoiImage))
                { 

                    string savePath = getSaveImagePath(BoardManager.CurrBoard.GetAoiFileName(), selectResultBean);
                    if (!Directory.Exists(savePath))
                    {
                        Directory .CreateDirectory(savePath);
                    }
                    string imageName = DateTime.Now.ToString("yy-MM-dd-HH-mm-ss-") + DateTime.Now.Millisecond + ".bmp"; 

                    image.Save(savePath + imageName, ImageFormat.Bmp);

                    IsUpdate = true;
                    btnRun.Visible = true;
                    btnUpdateImg.Visible = false;
                    listErrorView.ContextMenuStrip=null;
                    updateMName.Add(selectResultBean.MethodName);
                    LogUtil.info($" {BoardManager.CurrBoard} 修正 {selectResultBean.MethodName} 成功,图片保存到:" + savePath + imageName);
                }
            }
            catch (Exception ex)
            { 
                LogUtil.error($" {BoardManager.CurrBoard} 修正 {selectResultBean.MethodName}出错:" + ex.ToString());
            } 
        }

        private void 修正ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnUpdateImg_Click(null,null); 
        }
    }
}