FrmCodeDecode.cs 23.6 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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646

using CodeLibrary;
using HalconDotNet; 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace CodeLibrary
{
    public partial class FrmCodeDecode : FrmBase
    {
        private Stopwatch stopwatch = new Stopwatch();

        //   private List<string> baslerNameList = new List<string>();
        //  private List<string> hikNameList = new List<string>();
        public FrmCodeDecode()
        {
            InitializeComponent();
        }
        private string selCamera = CodeResourceControl.GetString(CodeResourceControl.selCamera, "请先选择相机");
        private string selImage = CodeResourceControl.GetString(CodeResourceControl.selImage, "请先选择图片");
        private string title = CodeResourceControl.GetString(CodeResourceControl.title, "提示");
        private string imageIsNull = CodeResourceControl.GetString(CodeResourceControl.imageIsNull, "获取二维码图片为空");
        private string sureDelete = CodeResourceControl.GetString(CodeResourceControl.sureDelete, "确定删除文件:");
        private void FrmMain_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            cmbCount.Items.Clear(); cmbCount.Items.Add(-1);
            for (int i = 1; i <= 300; i++)
            {
                cmbCount.Items.Add(i);
            }
            cmbCount.SelectedIndex = 0;
            cmbCount.SelectedIndex = 0;
            LoadCamera();

            cmbCodeType.DataSource = HDCodeLearnHelper.codeTypeList;
            if (HDCodeLearnHelper.codeTypeList.Count > 0)
            {
                cmbCodeType.SelectedIndex = 0;
            }
            else
            {
                cmbCodeType.Items.Add("QR Code");
                cmbCodeType.SelectedIndex = 0;
            }
        }
        private void ClearPicImg()
        {
            try
            {
                if (pictureBox1.Image != null)
                {
                    pictureBox1.Image.Dispose();
                    pictureBox1.Image = null;
                }
                if (HDCodeLearnHelper.DefaultImage != null)
                {
                    HDCodeLearnHelper.DefaultImage.Dispose();
                    HDCodeLearnHelper.DefaultImage = null;
                }

            }
            catch (Exception ex)
            {
                HDLogUtil.error("ClearPicImg error : " + ex.ToString());
            }
        }
        private void LoadCamera()
        { 
            cmbCamera.Items.Clear();
            Camera.Type = CameraType.HIK;
            Camera._cam.Load();
            if (Camera._cam.Name == null)
                return;
            foreach (string str in Camera._cam.Name)
            {
                cmbCamera.Items.Add(str);
            }
             
            if (cmbCamera.Items.Count > 0)
            {
                cmbCamera.SelectedIndex = 0;
            }
        }
        private void btnSelImage_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
            openDialog.Title = selImage;
            openDialog.Filter = "(*.jpg;*.png;*.bmp;*.hobj)|*.jpg;*.png;*.bmp;*.hobj";
            //    openDialog.Filter = "All Supported Images (*.bmp;*.dib;*.rle;*.gif;*.jpg;*.png)|*.bmp;*.dib;*.rle;*.gif;*.jpg;*.png|Bitmaps (*.bmp;*.dib;*.rle)|*.bmp;*.dib;*.rle|Graphics Interchange Format (*.gif)|*.gif|Joint Photographic Experts (*.jpg)|*.jpg|Portable Network Graphics (*.png)|*.png|All Files (*.*)|*.*";
            //openDialog.DefaultExt = "png";
            System.Windows.Forms.DialogResult result = openDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            txtPath.Text = openDialog.FileName;
            string filename = txtPath.Text;
            if (string.IsNullOrEmpty(filename))
            {
                MessageBox.Show(imageIsNull);
            }
            ClearPicImg();
            if (openDialog.FileName.EndsWith(".hobj"))
            {
                HObject hObject = null;
                HOperatorSet.GenEmptyObj(out hObject);
                hObject.ReadObject(openDialog.FileName);
                if (hObject != null)
                {
                    HDCodeLearnHelper.DefaultImage = hObject;
                    ShowImage(hObject);
                }
                else
                {
                    MessageBox.Show("读取文件失败:" + openDialog.FileName);
                }
            }
            else
            {
              
                //读取图片内容
                Image img = (Image)Image.FromFile(filename).Clone();
                pictureBox1.Image = img;
                Bitmap bitmap = new Bitmap(pictureBox1.Image);
                HObject hoimg;
                HDCodeHelper.Bitmap2HObjectBpp24(bitmap,out hoimg);
                HDCodeLearnHelper.DefaultImage = hoimg;
                ShowImage(hoimg);
            }
        }

        private void btnErZhi_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null || txtPath.Text.Equals(""))
            {
                MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Bitmap map = new Bitmap(pictureBox1.Image);
            Bitmap newMap = ImageHelper.ConvertTo1Bpp1(map);
            pictureBox1.Image = newMap;
        }
        private void btnGray_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null || txtPath.Text.Equals(""))
            {
                MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Bitmap map = new Bitmap(pictureBox1.Image);
            Bitmap newMap = ImageHelper.ToGray(map);
            pictureBox1.Image = newMap;
        }


        private void ShowCode(List<CodeInfo> list)
        {
            if (list.Count > 0)
            {
                txtResult.Text += "\r\n code list:";
                foreach (CodeInfo code in list)
                {
                    txtResult.Text += "\r\n" + "" + code.CodeType + " (X:" + code.X + ",Y:" + code.Y + ") " + code.CodeStr;
                    txtResult.Text += "\r\n" + "" + code.CodeType + " (X:" + code.X + ",Y:" + code.Y + ") " + code.GetCodeStr();
                }
            }
            else
            {
                txtResult.Text += "\r\n no code ";
            }
        }

        private void btnbarCode_Click(object sender, EventArgs e)
        { 
            if (HDCodeLearnHelper.DefaultImage == null)
            {
                MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            int count = cmbCount.SelectedIndex;
            txtResult.Text = "";
            stopwatch.Restart();
            HDCodeHelper.HalconWindow = this.hWindowControl1.HalconWindow;
          
            if (chbZxing.Checked)
            {
                if (pictureBox1.Image == null)
                {
                    MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Bitmap map = new Bitmap(pictureBox1.Image);
                zxingDecode(map, "barcode");
            }
            else
            {
                List<CodeInfo> result = HDCodeHelper.DecodeBarCode(HDCodeLearnHelper.DefaultImage);
                ShowCode(result);
                txtResult.Text += "\r\n elapsed time:" + stopwatch.Elapsed.ToString();
            }
        }
        public void ShowImage(HObject ho_Image)
        {
            HTuple width, height;
            HOperatorSet.GetImageSize(ho_Image, out width, out height);

            int dWidth = (int)width.D;
            int dHeight = (int)height.D;
            this.hWindowControl1.HalconWindow.SetPart(0, 0, dHeight, dWidth);
            HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);        
        }

        private void btnLearn_Click(object sender, EventArgs e)
        {
            FrmCodeLearn frm = new FrmCodeLearn();
            frm.ShowDialog();
        }

        private void btnDCode_Click(object sender, EventArgs e)
        {  
            int count = cmbCount.SelectedIndex;
            txtResult.Text = "";
            stopwatch.Restart();

            //  Bitmap map = new Bitmap(pictureBox1.Image);
            //HObject ho_image = HDCodeHelper.Bitmap2HObjectBpp24(map);

            txtResult.Text += "\r\n elapsed time:" + stopwatch.Elapsed.ToString();
            //hWindowControl1.HalconWindow.SetPart(0, 0, map.Height, map.Width);
            //HOperatorSet.DispObj(ho_image, hWindowControl1.HalconWindow);
            //ShowImage(ho_image);
            HDCodeHelper.HalconWindow = this.hWindowControl1.HalconWindow;
            string codeParamPath = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
            if (chbUseParam.Checked.Equals(false))
            {
                codeParamPath = "";
            }
            if (chbZxing.Checked)
            {
                if (HDCodeLearnHelper.DefaultBitmap != null) {

                    List<CodeInfo> codeList = eyemDecode.Decoder(ref HDCodeLearnHelper.DefaultBitmap);
                    HDCodeLearnHelper.DefaultBitmap.Dispose();
                    ShowCode(codeList);
                    return;
                }
                

                if (pictureBox1.Image == null)
                {
                    MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Bitmap map = new Bitmap(pictureBox1.Image);
                zxingDecode(map, cmbCodeType.Text);
            }
            else
            {
                if (HDCodeLearnHelper.DefaultImage == null)
                {
                    MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List<CodeInfo> codeList = new List<CodeInfo>();
                if (cmbCodeType.Text.ToLower().Equals("barcode"))
                {
                    codeList = HDCodeHelper.DecodeBarCode(HDCodeLearnHelper.DefaultImage);
                }
                else
                {
                    codeList = HDCodeHelper.DecodeCode(HDCodeLearnHelper.DefaultImage, count, codeParamPath, cmbCodeType.Text);
                }
                ShowCode(codeList);
                txtResult.Text += "\r\n elapsed time:" + stopwatch.Elapsed.ToString();
            }
        }
        private void zxingDecode(Bitmap map, string type)
        {
            /*
            List<string> results = ZXingCodeHelper.DeCodes(map, type);

            txtResult.Text = " zxing decode:";
            foreach (string code in results)
            {
                txtResult.Text += "\r\n" + "\r\n" + code;
            }
            txtResult.Text += "\r\n \r\n elapsed time:" + stopwatch.Elapsed.ToString();
            */
            List<CodeInfo> codeList = new List<CodeInfo>(); ;
            //for (int i = 0; i < 1000; i++)
            //{
                Bitmap b = (Bitmap)pictureBox1.Image.Clone();
                codeList = eyemDecode.Decoder(ref b);
                b.Dispose();
                Thread.Sleep(10);
            //}
            ShowCode(codeList);

        }
        private void btnClearLog_Click(object sender, EventArgs e)
        {
            HDLogUtil.ClearLog();
            txtResult.Text = "";
        }
        private HObject GetCameraBitmap(out Bitmap bitmap)
        {
            bitmap = null;
            try
            {
                int index = cmbCamera.SelectedIndex;
                string camerName = cmbCamera.Text;
                if (index < 0)
                {
                    MessageBox.Show(selCamera);
                    return null;
                }
                HObject map;
                map = Camera._cam.CaptureOnImage(camerName,out bitmap);
                if (  map == null)
                {
                    Camera._cam.Close(camerName);
                    map = Camera._cam.CaptureOnImage(camerName, out bitmap);
                }
                return map;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return null;
        }
        private void btnCameraImage_Click(object sender, EventArgs e)
        {
            try
            {
                if (!chbZxing.Checked)
                {
                    HObject bitmap = GetCameraBitmap(out Bitmap b);
                    if (bitmap != null)
                    {
                        HDLogUtil.info("从相机【" + cmbCamera.Text + "】获取到一张图片");
                        ClearPicImg();
                        //pictureBox1.Image = (Image)bitmap.Clone();
                        //HObject hoImage = HDCodeHelper.Bitmap2HObjectBpp24(bitmap);
                        HDCodeLearnHelper.DefaultImage = bitmap;
                        HDCodeLearnHelper.DefaultBitmap = b;
                        ShowImage(bitmap);
                    }
                }
                else
                {
                    int index = cmbCamera.SelectedIndex;
                    string camerName = cmbCamera.Text;
                    if (index < 0)
                    {
                        MessageBox.Show(selCamera);
                        return;
                    }
                    Bitmap bitmap = Camera._cam.GrabOneImage(camerName);
                    if (bitmap != null)
                    {
                        HDLogUtil.info("从相机【" + cmbCamera.Text + "】获取到一张图片");
                        ClearPicImg();
                        pictureBox1.Image = (Image)bitmap.Clone();
                        ////HObject hoImage = HDCodeHelper.Bitmap2HObjectBpp24(bitmap);
                        //HDCodeLearnHelper.DefaultImage = bitmap;
                        //ShowImage(bitmap);
                    }
                }
            }
            catch (Exception ex)
            {
                HDLogUtil.error(ex.ToString());
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLigth_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null || txtPath.Text.Equals(""))
            {
                MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Bitmap map = new Bitmap(pictureBox1.Image);
            Bitmap newMap = ImageHelper.KiLighten(map, 10);
            pictureBox1.Image = newMap;
        }

        private void btnAn_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null || txtPath.Text.Equals(""))
            {
                MessageBox.Show(selImage, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Bitmap map = new Bitmap(pictureBox1.Image);
            Bitmap newMap = ImageHelper.KiLighten(map, -10);
            pictureBox1.Image = newMap;
        }

        private void cmbCodeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCodeType.SelectedIndex >= 0)
            {
                txtParamPath.Text = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
            }
        }
        private System.Timers.Timer testTimer = new System.Timers.Timer();
        private int testCount = 0;
        private void button1_Click(object sender, EventArgs e)
        {
            if (testTimer.Enabled)
            {
                HDLogUtil.info("停止扫码测试");
                testTimer.Stop();
            }
            else
            {
                HDLogUtil.info("开始扫码测试");
                testCount = 0;
                testTimer.Interval = 1000;
                testTimer.Elapsed += TestTimer_Elapsed;
                testTimer.AutoReset = true;
                testTimer.Start();
            }
        }

        private void TestTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (pictureBox1.Image == null)
                {

                    return;
                }
                int count = cmbCount.SelectedIndex;
                txtResult.Text = "";
                stopwatch.Restart();
                testCount++;
                Bitmap map = new Bitmap(pictureBox1.Image);
                HObject ho_image;
                HDCodeHelper.Bitmap2HObjectBpp24(map,out ho_image);

                txtResult.Text += "\r\n elapsed time:" + stopwatch.Elapsed.ToString();
                hWindowControl1.HalconWindow.SetPart(0, 0, map.Height, map.Width);
                HOperatorSet.DispObj(ho_image, hWindowControl1.HalconWindow);
                ShowImage(ho_image);
                HDCodeHelper.HalconWindow = this.hWindowControl1.HalconWindow;
                string codeParamPath = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
                if (chbUseParam.Checked.Equals(false))
                {
                    codeParamPath = "";
                }
                List<CodeInfo> codeList = new List<CodeInfo>();
                if (cmbCodeType.Text.ToLower().Equals("barcode"))
                {
                    codeList = HDCodeHelper.DecodeBarCode(ho_image);
                }
                else
                {
                    codeList = HDCodeHelper.DecodeCode(ho_image, count, codeParamPath, cmbCodeType.Text);
                }
                ShowCode(codeList);

                txtResult.Text += "\r\n elapsed time:" + stopwatch.Elapsed.ToString();
                HDLogUtil.info("第【" + testCount + "】次扫码测试结束");
            }
            catch (Exception ex)
            {
                HDLogUtil.error(ex.ToString());
            }
        }

        private void FrmCodeDecode_FormClosing(object sender, FormClosingEventArgs e)
        {
            Camera._cam.CloseAll();
        }

        private void btnScanTest_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            Task.Factory.StartNew(delegate
            {
                //ScanTest();
                ScanDemo(100);
            });
        }
        private void ScanTest()
        {
            for (int index = 1; index <= 200; index++)
            {
                try
                {
                    label5.Text = "扫码测试_" + index;
                    int name = (index % 3) + 1;
                    string filename = @"F:\test\" + name + ".hobj";
                    if (!File.Exists(filename))
                    {
                        continue;
                    }
                    ClearPicImg();
                    if (filename.EndsWith(".hobj"))
                    {
                        HObject hObject = null;
                        HOperatorSet.GenEmptyObj(out hObject);
                        hObject.ReadObject(filename);
                        if (hObject != null)
                        {
                            HDCodeLearnHelper.DefaultImage = hObject;
                            ShowImage(hObject);
                        }
                        else
                        {
                            MessageBox.Show("读取文件失败:" + filename);
                        }
                    }
                    else
                    {

                        //读取图片内容
                        Image img = (Image)Image.FromFile(filename).Clone();
                        pictureBox1.Image = img;
                        Bitmap bitmap = new Bitmap(pictureBox1.Image);
                        HObject hoimg;
                        HDCodeHelper.Bitmap2HObjectBpp24(bitmap, out hoimg);
                        HDCodeLearnHelper.DefaultImage = hoimg;
                        ShowImage(hoimg);
                    }

                    btnDCode_Click(null, null);

                    Thread.Sleep(100);
                }
                catch (Exception ex)
                {
                    HDLogUtil.error("ScanTest[" + index + "]出错:" + ex.ToString());
                }
            }
            this.Enabled = true;
            this.Cursor = Cursors.Default;
        }

        private void ScanDemo(int whileCount = 1)
        {
            string camerName = cmbCamera.Text;
            if (cmbCamera.SelectedIndex < 0)
            {
                //MessageBox.Show(selCamera);
                txtResult.Text = selCamera;
                return;
            }
            int count = cmbCount.SelectedIndex;
            List<string> codeTypeList = new List<string>(HDCodeLearnHelper.codeTypeList);

            Task task = null;
            for (int index = 1; index <= whileCount; index++)
            {
                 
                     //task = Task.Factory.StartNew(delegate {

                    label5.Text = "扫码测试_" + index;
                HObject ho_Image = null;
                try
                    {
                    ho_Image = Camera._cam.CaptureOnImage(camerName );
                    if (  ho_Image != null)
                    {
                            //ClearPicImg(); 
                            // ShowImage(ho_Image);
                            HDLogUtil.info(" 相机【" + camerName + "】获取图片完成,开始扫码");
                            List<CodeInfo> cc = new List<CodeInfo>();
                            string r = "ScanDemo[" + index + "]\r\n";
                            foreach (string codeType in codeTypeList)
                            {
                                //判断是否是一维码
                                if (codeType.ToLower().Equals("barcode"))
                                {
                                    cc = HDCodeHelper.DecodeBarCode(ho_Image);
                                }
                                else
                                {
                                    string codeParamPath = HDCodeHelper.GetCodeParamFilePath(codeType);
                                    cc = HDCodeHelper.DecodeCode(ho_Image, count, codeParamPath, codeType);
                                }

                                foreach (CodeInfo c in cc)
                                {
                                    r += (c.CodeStr) + "##";
                                }
                            }
                            //MessageBox.Show(r);
                            txtResult.Text = r;
                        }


                    }
                    catch (Exception ex)
                    {
                        HDLogUtil.error("ScanDemo[" + index + "]出错:" + ex.ToString());
                    }
                    finally
                {
                    if (ho_Image != null)
                    {
                        ho_Image.Dispose();
                        ho_Image = null;
                    }
                }
                 
                 //});
                 //task.Wait();
                //GC.Collect();
                //Thread.Sleep(100);
                //task.Dispose();
                Thread.Sleep(5);
            }
            this.Enabled = true;
            this.Cursor = Cursors.Default;
        }
        private void btnCopyN_Click(object sender, EventArgs e)
        {
            string text = cmbCamera.Text;
            Clipboard.SetDataObject(text);
        }
    }
}