示例#1
0
        //创建存放结果集的文件夹与文件
        private void CreatFile()
        {
            //启动加载xml  在debug下 xml
            Plate_SVM.Load(Application.StartupPath + @"\MyTestChar.xml");
            Plate_Car_SVM.Load(Application.StartupPath + @"\MyTestCar.xml");

            String DirectoryPath = @"C:\test-results";

            if (!Directory.Exists(DirectoryPath))
            {
                Directory.CreateDirectory(DirectoryPath);
            }

            if (File.Exists(DirectoryPath + @"\No14866mresults.txt"))
            {
                File.Delete(DirectoryPath + @"\No14866mresults.txt");
                FileStream fs = new FileStream(DirectoryPath + @"\No14866mresults.txt", FileMode.Create, FileAccess.ReadWrite);//创建写入文件
                file = new StreamWriter(fs);
            }
            else
            {
                FileStream fs = new FileStream(DirectoryPath + @"\No14866mresults.txt", FileMode.Create, FileAccess.ReadWrite);//创建写入文件
                file = new StreamWriter(fs);
            }
        }
示例#2
0
        //保存车牌XML
        private void SavaCarSVM_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();

            saveDlg.Filter = "XML文件|*.xml";

            DialogResult dlgResult = saveDlg.ShowDialog();

            if (dlgResult == DialogResult.OK)
            {
                Plate_Car_SVM.Save(saveDlg.FileName);
                this.txtinfo.AppendText("保存-训练数据XML成功 \r\n ");
            }
        }
示例#3
0
        /// <summary>
        ///  颜色法 筛选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbtnlFilter_Click(object sender, EventArgs e)
        {
            if (this.srcImg == null)
            {
                return;
            }
            if (this.srcImg.Empty())
            {
                return;
            }
            rectList.Clear();
            PicMatrois.Clear();
            tsColorChangeText_TextChanged(sender, e);
            int   minWidth  = int.Parse(this.txtMinWidth.Text);
            int   minHeight = int.Parse(this.txtMinHeight.Text);
            int   maxWidth  = int.Parse(this.txtMaxWidth.Text);
            int   maxHeight = int.Parse(this.txtMaxHeight.Text);
            float WhScale   = float.Parse(this.txtWHScale.Text);

            this.panSegmentList.Controls.Clear();
            this.panChars.Controls.Clear();

            // rects 集合
            foreach (var item in this.rectList)
            {
                if (
                    item.Width >= minWidth &&
                    item.Width <= maxWidth &&
                    item.Height >= minHeight &&
                    item.Height <= maxHeight &&
                    item.Width / item.Height > 0.8 &&
                    item.Width / item.Height < WhScale
                    )
                {
                    //SubMat  对矩形区域进行截取
                    Mat matRoi = this.srcImg.SubMat(item);

                    PlateCar plateCar = Plate_Car_SVM.TestCar(matRoi);
                    if (PlateCar.车牌 == plateCar)
                    {
                        PicMatrois.Add(matRoi);
                    }
                    this.GenerateROI(matRoi, this.panSegmentList);
                }
            }
        }
示例#4
0
        //车牌训练
        private void Car_svm_Click(object sender, EventArgs e)
        {
            if (this.samplePath == "")
            {
                return;
            }

            List <PlateCarInfo> plateSamples = new List <PlateCarInfo>();

            string[] subDirectories = Directory.GetDirectories(this.samplePath);
            for (int index = 0; index < subDirectories.Length; index++)
            {
                string subDirectory   = subDirectories[index];
                string shortDirectory = subDirectory.Substring(subDirectory.LastIndexOf(@"\") + 1);

                PlateCar categorycar = (PlateCar)Enum.Parse(typeof(PlateCar), shortDirectory);

                string[] fileNames = Directory.GetFiles(subDirectory, "*.jpg");

                for (int i = 0; i < fileNames.Length; i++)
                {
                    string fileName = fileNames[i];
                    this.txtinfo.AppendText(string.Format("{0}  类型:{1}\r\n", fileName, categorycar));

                    Mat matPlate = Cv2.ImRead(fileName);

                    PlateCarInfo plateCarInfo = new PlateCarInfo();
                    plateCarInfo.PlateMatCar = matPlate;
                    plateCarInfo.CategoryCar = categorycar;

                    plateSamples.Add(plateCarInfo);
                }
            }

            //将样本的元数据转化为SVM的样品数据和标签数据
            Mat trainData  = new Mat();
            Mat trainLabel = new Mat(plateSamples.Count, 1, MatType.CV_32SC1);

            for (int index = 0; index < plateSamples.Count; index++)
            {
                PlateCarInfo plateCarInfo = plateSamples[index];
                float[]      hog          = Plate_Car_SVM.GetHogCar(plateCarInfo.PlateMatCar);

                if (index == 0)
                {
                    trainData = Mat.Zeros(plateSamples.Count, hog.Length, MatType.CV_32FC1);
                }

                for (int colIndex = 0; colIndex < hog.Length; colIndex++)
                {
                    trainData.Set <float>(index, colIndex, hog[colIndex]);
                }

                trainLabel.Set <int>(index, 0, (int)plateCarInfo.CategoryCar);

                this.txtinfo.AppendText(hog.Length.ToString() + "\r\n");
            }

            Plate_Car_SVM.Train(trainData, trainLabel);

            this.txtinfo.AppendText("训练已完成\r\n");
        }
示例#5
0
        /// <summary>
        /// 颜色交换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripComboBox1_TextChanged(object sender, EventArgs e)
        {
            // 颜色法
            this.HSVEvenimg      = my_Method.ColorMethod(this.frameClone, 5, 50, 255, this.HSVEvenimg);
            this.picColorM.Image = this.HSVEvenimg.ToBitmap();
            //        this.GenerateROI(this.HSVEvenimg, this.panelColor, false);

            // 颜色区域
            Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(11, 2));

            // 定义点的二维数组
            OpenCvSharp.Point[][] contours    = null;
            HierarchyIndex[]      hierarchies = null;

            contours = my_Method.ColorRange(element, contours, hierarchies, frameClone, this.HSVEvenimg, 5);

            string s = this.lblText.Text.Trim();

            //图像显示识别结果

            if (this.lblText.Text.Trim() != null && this.lblText.Text.Trim() != "")
            {
                String rest = this.lblText.Text.Trim();
                if ((int)rest[0] < 127)
                {
                    rest = rest.Remove(0, 1);
                }
                if (my_Method.bluenum > my_Method.greennum)
                {
                    if (rest.Length > 7)
                    {
                        rest.Remove(7);
                    }
                }
                if (my_Method.bluenum > my_Method.greennum)
                {
                    if (rest.Length > 8)
                    {
                        rest.Remove(8);
                    }
                }
                Regex reg = new Regex("[\u4e00-\u9fa5]+");
                foreach (Match Chinese in reg.Matches(rest))
                {
                    int indexof = rest.IndexOf(Chinese.Value);
                    rest = rest.Remove(indexof, 1);
                    int has = Form_Main.hashRes.Count;
                    if (Form_Main.hashRes.ContainsKey(Chinese.Value))
                    {
                        rest = rest.Insert(indexof, Form_Main.hashRes[Chinese.Value].ToString());
                    }
                }
                my_Method.matWithFlag.PutText("result:   " + rest, new OpenCvSharp.Point(50, 100), HersheyFonts.HersheyTriplex, 0.8, Scalar.Yellow, 2);
            }

            // 显示查找的轮廓
            this.picMatWithFlag.Image = my_Method.matWithFlag.ToBitmap();

            this.rectList.Clear();

            for (int i = 0; i < contours.Length; i++)
            {
                // 轮廓的最小矩形
                Rect rect = Cv2.BoundingRect(contours[i]);
                this.rectList.Add(rect); // 添加到集合
            }

            // 遍历找到的矩形  然后截取出来
            foreach (var item in this.rectList)
            {
                if (item.Width >= 40 &&
                    item.Width <= 2000 &&
                    item.Height >= 20 &&
                    item.Height <= 2000 &&
                    item.Width / item.Height > 0.8 &&
                    item.Width / item.Height < 5)
                {
                    //SubMat  对矩形区域进行截取
                    matRoi = this.frameClone.SubMat(item);

                    if (Plate_Car_SVM.TestCar(matRoi) == PlateCar.车牌)
                    {
                        // 显示截取的矩形
                        this.picRect.Image = matRoi.ToBitmap();

                        // 进行分割
                        List <Mat> ListMat = my_Method.carCharSplit(matRoi);

                        List <PlateCategory> category = Plate_SVM.TestList(ListMat);

                        TextBox tx = new TextBox();
                        for (int index = 0; index < category.Count; index++)
                        {
                            if (category[index] == 0)
                            {
                                tx.AppendText(string.Format("{0}", ""));
                            }
                            else
                            {
                                tx.AppendText(string.Format("{0}", category[index]));
                            }
                        }

                        string res = tx.Text.Replace("_", "");

                        Console.WriteLine(res.Length + "   : 第一个");

                        for (int i = 0; i < res.Length; i++)
                        {
                            // 判断第一个是不是汉字 不是就删除
                            // 不是汉字
                            if ((int)res[0] < 127 && res.Length > 1 && res != null && res != "")
                            {
                                res = res.Substring(1);
                                // 显示识别结果
                                this.lblText.Text = res;
                            }
                            else
                            {
                                // 显示识别结果
                                this.lblText.Text = res;
                            }
                        }


                        GC.Collect();
                    }
                }
            }
        }
示例#6
0
        //图片处理
        private void ProImg()
        {
            int    FsIndex   = 0;
            string imagePath = @"C:\test-imgs";

            if (!Directory.Exists(imagePath))
            {
                MessageBox.Show("图片测试文件夹路径需为:C: test-imgs");
                return;
            }
            string[]      subDirecotries = Directory.GetDirectories(imagePath);
            DirectoryInfo di             = new DirectoryInfo(imagePath);

            if (subDirecotries.Length == 0)
            {
                FileInfo[] FileList = di.GetFiles();
                ArrayList  FAL      = new ArrayList();
                //筛选图片
                foreach (FileInfo Files in FileList)
                {
                    String FilesName = (Files.Name).ToUpper();
                    if (FilesName.EndsWith(".JPG") || FilesName.EndsWith(".PNG") || FilesName.EndsWith(".BMP"))
                    {
                        FAL.Add(Files);
                    }
                }
                //清空数组
                Array.Clear(FileList, 0, FileList.Length);
                //重新赋值
                FileList = (FileInfo[])(FAL.ToArray(typeof(FileInfo)));
                //根据文件名排序
                Array.Sort(FileList, new FileNameSort());
                //把文件名存进数组
                for (int i = 0; i < FileList.Length; i++)
                {
                    fileNames.Add(FileList[i].FullName);
                }
                //--------------获取图片处理所需的参数和阈值----------------------
                //加载Datatable数据表
                LoadDT();
                //模糊
                int blurSize = int.Parse(this.blurSize.Text);
                // 边缘
                int cannyThreshold1 = int.Parse(this.canny1.Text);
                int cannyThreshold2 = int.Parse(this.canny2.Text);

                // 膨胀的 element
                int ksizex = int.Parse(this.txDaliteX.Text);
                int ksizey = int.Parse(this.txDaliteY.Text);

                int   minWidth  = int.Parse(this.txtMinWidth.Text);
                int   minHeight = int.Parse(this.txtMinHeight.Text);
                int   maxWidth  = int.Parse(this.txtMaxWidth.Text);
                int   maxHeight = int.Parse(this.txtMaxHeight.Text);
                float WhScale   = float.Parse(this.txtWHScale.Text);

                for (int index = 0; index < fileNames.Count; index++)
                {
                    dtMatANDRect.Clear();
                    //清空PicMatrois图片结果集
                    PicMatrois = new List <Mat>();
                    //rectList.Clear();
                    int MatIndex = 0;
                    FileNameAndMat.Clear();
                    string fileName = fileNames[index];
                    //调用识别方法
                    // 读取原图
                    this.srcImg = Cv2.ImRead(fileName);
                    // 归一化
                    if (srcImg.Cols > 2000)
                    {
                        Cv2.Resize(srcImg, srcImg, new OpenCvSharp.Size(srcImg.Cols * 0.3, srcImg.Rows * 0.3));
                    }
                    //原图变化
                    this.picSrc.Image = this.srcImg.ToBitmap();
                    //获取HSV均衡图
                    this.HSVEvenimg = my_Method.ColorMethod(this.srcImg, blurSize, cannyThreshold1, cannyThreshold2, this.HSVEvenimg);

                    // 膨胀的 element
                    Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(ksizex, ksizey));


                    // 定义点的二维数组,颜色法筛选开始
                    if (this.srcImg == null)
                    {
                        return;
                    }
                    if (this.srcImg.Empty())
                    {
                        return;
                    }

                    Point[][]        contours    = null;
                    HierarchyIndex[] hierarchies = null;

                    contours = my_Method.ColorRange(element, contours, hierarchies, this.srcImg, this.HSVEvenimg, 3);

                    for (int i = 0; i < contours.Length; i++)
                    {
                        // 轮廓的最小矩形
                        Rect rect = Cv2.BoundingRect(contours[i]);
                        if (rect.Width >= minWidth &&
                            rect.Width <= maxWidth &&
                            rect.Height >= minHeight &&
                            rect.Height <= maxHeight &&
                            rect.Width / rect.Height > 0.8 &&
                            rect.Width / rect.Height < WhScale
                            )
                        {
                            Mat      matRoi   = this.srcImg.SubMat(rect);
                            PlateCar plateCar = Plate_Car_SVM.TestCar(matRoi);
                            if (PlateCar.车牌 == plateCar)
                            {
                                MatIndex++;
                                FileNameAndMat.Add(MatIndex, matRoi);
                                Console.WriteLine(dtMatANDRect.Columns.Count);
                                dtMatANDRect.Rows.Add(MatIndex, rect.X, rect.Y);
                            }
                        }
                    }
                    //判断颜色法是否筛选出符合要求的车牌,如果有添加进集合,结束筛选,开始下张图片
                    if (MatIndex != 0)
                    {
                        DataView dv = dtMatANDRect.DefaultView;
                        dv.Sort = "X ASC";
                        //dtMatANDRect.Clear();
                        dtMatANDRect = dv.ToTable();
                        for (int i = 0; i < dtMatANDRect.Rows.Count; i++)
                        {
                            int Mindex = int.Parse(dtMatANDRect.Rows[i]["MatIndex"].ToString());
                            Console.WriteLine(dtMatANDRect.Rows[i]["X"]);
                            if (FileNameAndMat.ContainsKey(Mindex))
                            {
                                Mat resMat;
                                FileNameAndMat.TryGetValue(Mindex, out resMat);
                                PicMatrois.Add(resMat);
                            }
                        }
                    }
                    //如果没,调用Sobel法
                    else
                    {
                        //调用Sobel法
                        this.SobelMethod();
                        if (this.srcImg == null)
                        {
                            return;
                        }
                        if (this.srcImg.Empty())
                        {
                            return;
                        }

                        //找轮廓
                        Point[][]        contours_sobel = null;
                        HierarchyIndex[] hierarchyIndex = null;

                        Cv2.FindContours(threshold_Erode, out contours_sobel, out hierarchyIndex,
                                         RetrievalModes.External, ContourApproximationModes.ApproxSimple);
                        // Sobel法筛选。对轮廓求最小外接矩形,然后验证,不满足条件的淘汰。
                        this.panSegment_Sobel.Controls.Clear();
                        int   minWidth_sobel  = int.Parse(this.txtMInWidth_sobel.Text);
                        int   minHeight_sobel = int.Parse(this.txtMInHeight_sobel.Text);
                        int   maxWidth_sobel  = int.Parse(this.txtMaxWidth_sobel.Text);
                        int   maxHeight_sobel = int.Parse(this.txtMaxHeight_sobel.Text);
                        float WhScale_sobel   = float.Parse(this.txtWHScale_sobel.Text);

                        //List<Mat> SobelMat = new List<Mat>();

                        for (int i = 0; i < contours_sobel.Length; i++)
                        {
                            Rect rect = Cv2.BoundingRect(contours_sobel[i]);

                            if (rect.Width >= minWidth_sobel &&
                                rect.Width <= maxWidth_sobel &&
                                rect.Height >= minHeight_sobel &&
                                rect.Height <= maxHeight_sobel &&
                                rect.Width / rect.Height >= 0.8 &&
                                rect.Width / rect.Height <= WhScale_sobel)
                            {
                                Mat      matROI   = this.srcImg.SubMat(rect);
                                PlateCar plateCar = Plate_Car_SVM.TestCar(matROI);
                                if (PlateCar.车牌 == plateCar)
                                {
                                    MatIndex++;
                                    FileNameAndMat.Add(MatIndex, matROI);
                                    dtMatANDRect.Rows.Add(MatIndex, rect.X, rect.Y);
                                }
                            }
                        }
                        if (MatIndex != 0)
                        {
                            DataView dv = dtMatANDRect.DefaultView;
                            dv.Sort = "X ASC";
                            //dtMatANDRect.Clear();
                            dtMatANDRect = dv.ToTable();
                            for (int i = 0; i < dtMatANDRect.Rows.Count; i++)
                            {
                                int Mindex = int.Parse(dtMatANDRect.Rows[i]["MatIndex"].ToString());
                                if (FileNameAndMat.ContainsKey(Mindex))
                                {
                                    Mat resMat;
                                    FileNameAndMat.TryGetValue(Mindex, out resMat);
                                    PicMatrois.Add(resMat);
                                }
                            }
                        }
                    }
                    // 图片名称 和 得到的矩形存在Map中
                    FileNameAndResult.Add(fileNames[index], PicMatrois);
                }

                //当一张图片有多张车牌时用于判断
                String FileName = null;
                foreach (KeyValuePair <String, List <Mat> > fvr in FileNameAndResult)
                {
                    string     fileName = fvr.Key;
                    List <Mat> listChar = fvr.Value;

                    string shortFileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1);

                    foreach (Mat value in listChar)
                    {
                        String res = this.CharsSplit(value);
                        //Console.WriteLine(this.CharsSplit(value));
                        /////////////////////////////////////////////////////  效率  shortFileName 存的值
                        if (res != null && res != "" && res.Length > 4)
                        {
                            if (shortFileName == FileName)
                            {
                                file.Write("\r\n" + res);
                            }
                            else
                            {
                                FsIndex++;
                                if (FsIndex == 1)
                                {
                                    file.Write(shortFileName + "\r\n" + res);
                                }
                                else
                                {
                                    file.Write("\r\n" + shortFileName + "\r\n" + res);
                                }
                            }
                            Console.WriteLine("=========================" + res);
                            FileName = shortFileName;
                        }
                    }
                }
                file.Close();
                PicMatrois.Clear();
            }
        }