示例#1
0
        /// <summary>
        /// Gets all license plate matches for their confidence for given image
        /// </summary>
        /// <param name="country">Country (US / EU)</param>
        /// <param name="imagePath">Image path</param>
        /// <returns>License plate matches for their confidence</returns>
        public Result GetPlateNumberCandidates(Country country, string imagePath)
        {
            var ass = Assembly.GetExecutingAssembly();
            var assemblyDirectory = Path.GetDirectoryName(ass.Location);

            if (assemblyDirectory == null)
            {
                throw new InvalidOperationException("Assembly Directory can't be null");
            }
            var configFile     = Path.Combine(assemblyDirectory, "openalpr", "openalpr.conf");
            var runtimeDataDir = Path.Combine(assemblyDirectory, "openalpr", "runtime_data");
            var foundCountry   = FindCountry(country);

            using (var alpr = new AlprNet(foundCountry, configFile, runtimeDataDir))
            {
                if (!alpr.IsLoaded())
                {
                    throw new Exception("Error initializing OpenALPR");
                }

                var results = alpr.Recognize(imagePath);
                var plates  = results.Plates.SelectMany(l => l.TopNPlates.Select(plate => new Result
                {
                    PlateNumber = plate.Characters,
                    Confidence  = plate.OverallConfidence
                })).ToList();

                return(plates.FirstOrDefault(p => p.Confidence >= 83f));
            }
        }
        /// <summary>
        /// Gets all license plate matches for their confidence for given image
        /// </summary>
        /// <param name="country">Country (US / EU)</param>
        /// <param name="imagePath">Image path</param>
        /// <returns>License plate matches for their confidence</returns>
        public List<Result> GetPlateNumberCandidates(Country country, string imagePath)
        {
            var ass = Assembly.GetExecutingAssembly();
            var assemblyDirectory = Path.GetDirectoryName(ass.Location);

            if (assemblyDirectory == null)
            {
                throw new Exception("Erro ao carregar assembly");
            }

            var configFile = Path.Combine(assemblyDirectory, "openalpr", "openalpr.conf");
            var runtimeDataDir = Path.Combine(assemblyDirectory, "openalpr", "runtime_data");

            using (var alpr = new AlprNet(country == Country.EU ? "eu" : "us", configFile, runtimeDataDir))
            {
                if (!alpr.IsLoaded())
                {
                    throw new Exception("Error initializing OpenALPR");
                }

                var results = alpr.Recognize(imagePath);
                return results.Plates.SelectMany(l => l.TopNPlates.Select(plate => new Result
                {
                    PlateNumber = plate.Characters,
                    Confidence = plate.OverallConfidence
                })).ToList();
            }

        }
示例#3
0
        private static void PerformAlpr(AlprNet alpr, byte[] buffer, bool benchmark, bool writeJson)
        {
            var sw      = Stopwatch.StartNew();
            var results = alpr.Recognize(buffer);

            sw.Stop();
            if (benchmark)
            {
                Console.WriteLine("Total Time to process image(s): {0} msec(s)", sw.ElapsedMilliseconds);
            }

            if (writeJson)
            {
                //Console.WriteLine(alpr.toJson());
            }
            else
            {
                var i = 0;
                foreach (var result in results.Plates)
                {
                    Console.WriteLine("Plate {0}: {1} result(s)", i++, result.TopNPlates.Count);
                    Console.WriteLine("  Processing Time: {0} msec(s)", result.ProcessingTimeMs);
                    foreach (var plate in result.TopNPlates)
                    {
                        Console.WriteLine("  - {0}\t Confidence: {1}\tMatches Template: {2}", plate.Characters,
                                          plate.OverallConfidence, plate.MatchesTemplate);
                    }
                }
            }
        }
示例#4
0
        private void processImageFile(Bitmap img)
        {
            resetControls();
            var    region           = checkAmerika.Checked ? "us" : "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    txtPlaka.Text = "Error initializing OpenALPR";
                    return;
                }
                var results = alpr.Recognize(img);

                var images = new List <Image>(results.Plates.Count());
                var i      = 1;
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);

                    txtPlaka.Text = EnBenzeyenPlakayiGetir(result.TopNPlates);
                }

                if (images.Any())
                {
                    picPlakaResmi.Image = combineImages(images);
                }
            }
        }
示例#5
0
        public List <string> Recognize(byte[] byteArr)
        {
            List <string> RecInfo = new List <string>();

            var alpr = new AlprNet("eu", @"C:\Users\Laurynas\Documents\Visual Studio 2015\Projects\ConsoleAlpr\ConsoleAlpr\bin\Debug\openalpr.conf", @"C:\Users\Laurynas\Documents\Visual Studio 2015\Projects\ConsoleAlpr\ConsoleAlpr\bin\Debug\runtime_data");

            if (!alpr.IsLoaded())
            {
                string fail = "OpenAlpr failed to load!";
                RecInfo.Add(fail);
                return(RecInfo);
            }

            var results = alpr.Recognize(byteArr);

            string platenumber;

            foreach (var result in results.Plates)
            {
                foreach (var plate in result.TopNPlates)
                {
                    platenumber = "Plate: " + plate.Characters + " Confidence: " + plate.OverallConfidence;
                    RecInfo.Add(platenumber);
                    RecInfo.Add(plate.Characters);
                    RecInfo.Add(plate.OverallConfidence.ToString());
                }
            }



            return(RecInfo);
        }
        public static void Main()
        {
            var alpr = new AlprNet(
                "eu",
                Environment.CurrentDirectory + @"\openalpr.conf",
                Environment.CurrentDirectory + @"\runtime_data");
            if (!alpr.IsLoaded())
            {
                Console.WriteLine("OpenAlpr failed to load!");
                return;
            }

            Console.WriteLine($"Version: {AlprNet.GetVersion()}");
            var results = alpr.Recognize(Environment.CurrentDirectory + @"\samples\niki_ivo.jpg");

            for (int index = 0; index < results.Plates.Count; index++)
            {
                var result = results.Plates[index];
                Console.WriteLine($"Plate {index}: {result.TopNPlates.Count} result(s)");
                Console.WriteLine($"  Processing Time: {result.ProcessingTimeMs} msec(s)");
                foreach (var plate in result.TopNPlates)
                {
                    Console.WriteLine(
                        $"  - {plate.Characters}\t Confidence: {plate.OverallConfidence}\tMatches Template: {plate.MatchesTemplate}");
                }
            }
        }
示例#7
0
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                // file is uploaded
                file.SaveAs(Server.MapPath("~/App_Data/images/") + (Guid.NewGuid().ToString()) + ".png");

                byte[] arr = new byte[1];
                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    arr = ms.GetBuffer();
                }


                var alpr = new AlprNet("us", "C:\\Users\\oabdel2\\Downloads\\openalpr-2.3.0-win-64bit\\openalpr_64\\openalpr.conf", "C:\\Users\\oabdel2\\Downloads\\openalpr-2.3.0-win-64bit\\openalpr_64\\runtime_data");
                if (!alpr.IsLoaded())
                {
                    Console.WriteLine("OpenAlpr failed to load!");
                }
                // Optionally apply pattern matching for a particular region
                alpr.DefaultRegion = "md";


                var results = alpr.Recognize(arr);

                string test = results.Plates.First().TopNPlates.First().ToString();
                int    a    = 1;
            }
            // after successfully uploading redirect the user
            return(View("Index"));
        }
        public static void Main()
        {
            var alpr = new AlprNet(
                "eu",
                Environment.CurrentDirectory + @"\openalpr.conf",
                Environment.CurrentDirectory + @"\runtime_data");

            if (!alpr.IsLoaded())
            {
                Console.WriteLine("OpenAlpr failed to load!");
                return;
            }

            Console.WriteLine($"Version: {AlprNet.GetVersion()}");
            var results = alpr.Recognize(Environment.CurrentDirectory + @"\samples\niki_ivo.jpg");

            for (int index = 0; index < results.Plates.Count; index++)
            {
                var result = results.Plates[index];
                Console.WriteLine($"Plate {index}: {result.TopNPlates.Count} result(s)");
                Console.WriteLine($"  Processing Time: {result.ProcessingTimeMs} msec(s)");
                foreach (var plate in result.TopNPlates)
                {
                    Console.WriteLine(
                        $"  - {plate.Characters}\t Confidence: {plate.OverallConfidence}\tMatches Template: {plate.MatchesTemplate}");
                }
            }
        }
示例#9
0
        public static AlprResultsNet Recognize(string imageFilePath, string country = "eu")
        {
            try
            {
                // Initialize OpenALPR Library
                var alpr = new AlprNet(country, GetMapPath(OpenALPRConfigPath), GetMapPath(OpenALPRRuntimeDataPath));
                if (!alpr.IsLoaded())
                {
                    // OpenALPR failed to load!
                    return(null);
                }

                //Recognize the image (if it exists)
                if (System.IO.File.Exists(imageFilePath))
                {
                    var results = alpr.Recognize(imageFilePath);
                    return(results);
                }
                return(null);
            }
            catch
            {
                return(null);
            }
        }
        public AlprPlateNet Recognize(Bitmap img)
        {
            if (img == null)
            {
                return(null);
            }
            var alpr = new AlprNet("eu", "openalpr.conf", "runtime_data");

            if (!alpr.IsLoaded())
            {
                Console.WriteLine("OpenAlpr failed to load!");
                return(null);
            }

            // Optionally apply pattern matching for a particular region
            //alpr.DefaultRegion = "eu";

            var results = alpr.Recognize(img);

            Regex bsx5So = new Regex(@"^\d{2}[A-Z]\d{5}$");     //format bien 5 so
            Regex bsx4So = new Regex(@"^\d{2}[A-Z]\d{4}$");     //format bien 4 so

            try
            {
                foreach (var result in results.Plates)
                {
                    // crop plate
                    List <Point> platePoints = result.PlatePoints;
                    Bitmap       cropedPlate = img.Clone(boundingRectangle(platePoints), img.PixelFormat);

                    foreach (var plate in result.TopNPlates)
                    {
                        if (bsx5So.IsMatch(plate.Characters) || bsx4So.IsMatch(plate.Characters))
                        {
                            // bỏ qua biển số rờ mooc
                            if (plate.Characters.Contains("R"))
                            {
                                return(null);
                            }

                            Utilities.BienSoXe = cropedPlate;
                            return(plate);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Loi lay bien so xe");
                log.Error(ex.Message);
                log.Error(ex.StackTrace);
            }
            return(null);
        }
        private void _processTimer_Tick(object sender, EventArgs e)
        {
            if (SourceMediaElement.Position.Seconds < 1)
            {
                return;
            }



            var w = SourceMediaElement.ActualWidth;
            var h = SourceMediaElement.ActualHeight;

            System.Drawing.Size dpi = new System.Drawing.Size(96, 96);

            RenderTargetBitmap bmp = new RenderTargetBitmap((int)w, (int)h, dpi.Width, dpi.Height, PixelFormats.Pbgra32);

            bmp.Render(SourceMediaElement);


            MemoryStream  stream  = new MemoryStream();
            BitmapEncoder encoder = new BmpBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bmp));
            encoder.Save(stream);

            Bitmap bitmap = new Bitmap(stream);

            // try to recognize image
            AlprResultsNet result = _process.Recognize(bitmap);

            foreach (var plate in result.Plates)
            {
                if (plate.BestPlate.Characters.Length >= 7)
                {
                    if (plate.BestPlate.OverallConfidence > Confidence)
                    {
                        ResultsList.Add(new ResultViewModel(plate.BestPlate.Characters, SourceMediaElement.Position, plate.BestPlate.OverallConfidence, true));
                        LastRecognizedPlate = plate.BestPlate.Characters;
                    }
                    else
                    {
                        ResultsList.Add(new ResultViewModel(plate.BestPlate.Characters, SourceMediaElement.Position, plate.BestPlate.OverallConfidence));
                    }


                    _lineTimer.Start();
                }

                SetFirstLines(plate);
                SetSecondLines(plate);
                SetThirdLines(plate);
                SetFourthLines(plate);
            }
        }
示例#12
0
        private void processImageFile(Image fileName)
        {
            resetControls();
            var    region           = "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    //lbxPlates.Items.Add("Error initializing OpenALPR");
                    return;
                }
                //picOriginal.ImageLocation = fileName;
                //picOriginal.Load();
                string xxx = DateTime.Now.Second + "" + DateTime.Now.Minute + ".png";
                fileName.Save(xxx, ImageFormat.Png);
                var results = alpr.Recognize(xxx);

                var images = new List <Image>(results.Plates.Count());
                var i      = 1;
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(xxx);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);
                    //textBox1.Text= EnBenzeyen(result.TopNPlates);
                    //lbxPlates.Items.Add("\t\t-- Plate #" + i++ + " --");
                    foreach (var plate in result.TopNPlates)
                    {
                        Console.WriteLine(string.Format(@"{0} {1}% {2}",
                                                        plate.Characters.PadRight(12),
                                                        plate.OverallConfidence.ToString("N1").PadLeft(8),
                                                        plate.MatchesTemplate.ToString().PadLeft(8)));
                        //lbxPlates.Items.Add(string.Format(@"{0} {1}% {2}",
                        //                                  plate.Characters.PadRight(12),
                        //                                  plate.OverallConfidence.ToString("N1").PadLeft(8),
                        //                                  plate.MatchesTemplate.ToString().PadLeft(8)));
                    }
                    //  listBox1.Invoke(new Action(()=>listBox1.Items.Add(string.Format(@"{0} {1}% {2}",
                    //  result.TopNPlates[0].Characters.PadRight(12),
                    //  result.TopNPlates[0].OverallConfidence.ToString("N1").PadLeft(8),
                    //   result.TopNPlates[0].MatchesTemplate.ToString().PadLeft(8)))));
                }

                if (images.Any())
                {
                    //picLicensePlate.Image = combineImages(images);
                }
            }
        }
        private void Regconize()
        {
            var alpr = new AlprNet("us", "openalpr.conf.defaults", "runtime_data");

            if (!alpr.IsLoaded())
            {
                Console.WriteLine("OpenAlpr failed to load!");
                return;
            }
            // Optionally apply pattern matching for a particular region
            alpr.DefaultRegion = "vn2";

            AlprResultsNet results = alpr.Recognize(GetBitmap(LicencePlate));
            int            i       = 0;

            foreach (var result in results.Plates)
            {
                Console.WriteLine("Plate {0}: {1} result(s)", i++, result.TopNPlates.Count);
                Console.WriteLine("  Processing Time: {0} msec(s)", result.ProcessingTimeMs);
                foreach (var plate in result.TopNPlates)
                {
                    Console.WriteLine("  - {0}\t Confidence: {1}\tMatches Template: {2}", plate.Characters,
                                      plate.OverallConfidence, plate.MatchesTemplate);
                }
            }


            //var alpr2 = new AlprNet("us", "openalpr.conf", "runtime_data");
            //if (!alpr2.IsLoaded())
            //{
            //    Console.WriteLine("OpenAlpr failed to load!");
            //    return;
            //}
            //// Optionally apply pattern matching for a particular region
            //alpr2.DefaultRegion = "vn";

            ////var results2 = alpr2.Recognize("123.jpg");
            //var results2 = alpr2.Recognize("77.jpg");
            //i = 0;
            //foreach (var result in results2.Plates)
            //{
            //    Console.WriteLine("Plate {0}: {1} result(s)", i++, result.TopNPlates.Count);
            //    Console.WriteLine("  Processing Time: {0} msec(s)", result.ProcessingTimeMs);
            //    foreach (var plate in result.TopNPlates)
            //    {
            //        Console.WriteLine("  - {0}\t Confidence: {1}\tMatches Template: {2}", plate.Characters,
            //                          plate.OverallConfidence, plate.MatchesTemplate);
            //    }
            //}
        }
        private void outputProcessImageFile()
        {
            Bitmap fotoc = (Bitmap)output_cam.Image.Clone();
            //var cregion = rbUSA.Checked ? "us" : "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet("eu", config_file, runtime_data_dir)) // ülke plakaları -- önceki hali: "eu"
            {
                if (!alpr.IsLoaded())
                {
                    platesListBox.Items.Add("Error initializing OpenALPR");
                    return;
                }

                var results = alpr.Recognize(fotoc);

                var images = new List <System.Drawing.Image>(results.Plates.Count());
                var i      = 1;
                foreach (var result in results.Plates)
                {
                    var crect    = boundingRectangle(result.PlatePoints);
                    var cimg     = fotoc;
                    var ccropped = cropImage(cimg, crect);
                    images.Add(ccropped);

                    platesListBox.Items.Add("\t\t-- Plate #" + i++ + " --");
                    foreach (var plate in result.TopNPlates)
                    {
                        platesListBox.Items.Add(string.Format(@"{0} {1}% {2}", plate.Characters.PadRight(12),
                                                              plate.OverallConfidence.ToString("N1").PadLeft(12),
                                                              plate.MatchesTemplate.ToString().PadLeft(12)));
                    }
                }

                if (images.Any())
                {
                    licensePlatePic.Image = combineImages(images);
                }

                if (platesListBox.Items.Count > 1)
                {
                    plate = platesListBox.Items[1].ToString();
                }
                else
                {
                    plate = "";
                }
            }
        }
示例#15
0
        // This method attempts to recognize plates periodically and sends them off for further processing
        private void processImage()
        {
            Mat m = new Mat();

            try
            {
                capture.Retrieve(m);
                var results = alpr.Recognize(m.Bitmap);
                foreach (var result in results.Plates)
                {
                    foreach (var plate in result.TopNPlates)
                    {
                        if (gbRegExEnabled == true)
                        {
                            if (plate.OverallConfidence > confidenceThreshold && !livePlates.Contains(plate.Characters) && Regex.IsMatch(plate.Characters, validationExpression))
                            {
                                livePlates.Add(plate.Characters);
                                Console.WriteLine(plate.Characters + "  " + livePlates.Count);
                                processPlate(plate.Characters);
                            }
                        }
                        else if (gbRegExEnabled == false)
                        {
                            if (plate.OverallConfidence > confidenceThreshold && !livePlates.Contains(plate.Characters))
                            {
                                livePlates.Add(plate.Characters);
                                Console.WriteLine(plate.Characters + "  " + livePlates.Count);
                                processPlate(plate.Characters);
                            }
                        }
                    }
                }
            } catch (NullReferenceException ex)
            {
                Console.WriteLine("Null Reference Exception in processImage method.");
            } catch (ArgumentNullException ex)
            {
                Console.WriteLine("ArgumentNullException in processImage method");
            } catch (System.AccessViolationException ex)
            {
                Console.WriteLine("AccessViolationException in processImage method");
            } finally
            {
                m.Dispose();
            }

            verifyPlates();
            populateListView();
        }
        private string processImageFileGiris(String fileName)
        {
            var    region           = "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            try
            {
                using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
                {
                    var results = alpr.Recognize(fileName);

                    var images = new List <Image>(results.Plates.Count());
                    //    var i = 1;
                    if (results.Plates.Count() > 0)
                    {
                        kamera1kilit = 1;

                        lbxPlates.Items.Clear();
                    }
                    foreach (var result in results.Plates)
                    {
                        var rect    = boundingRectangle(result.PlatePoints);
                        var img     = Image.FromFile(fileName);
                        var cropped = cropImage(img, rect);
                        //resimKutusu.Image = cropImage2(img);
                        img.Dispose();
                        images.Add(cropped);

                        foreach (var plate in result.TopNPlates)
                        {
                            lbxPlates.Items.Add(plate.Characters);
                        }
                    }

                    if (images.Any())
                    {
                        picLicensePlate.Image = combineImages(images);
                    }
                }

                return("");
            }
            catch
            {
                return("");
            }
        }
示例#17
0
        private void processImageFile(string fileName)
        {
            resetControls();
            var    region           = "vn";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    lbxPlates.Items.Add("Error initializing OpenALPR");
                    return;
                }
                picOriginal.ImageLocation = fileName;
                picOriginal.Load();
                picOriginal.SizeMode = PictureBoxSizeMode.StretchImage;

                var results = alpr.Recognize(fileName);

                var images = new List <Image>(results.Plates.Count());
                var i      = 1;
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);

                    lbxPlates.Items.Add("\t\t-- Plate #" + i++ + " --");
                    textBox1.Font = new Font(textBox1.Font.FontFamily, 20);
                    textBox1.Text = result.TopNPlates[0].Characters;
                    foreach (var plate in result.TopNPlates)
                    {
                        lbxPlates.Items.Add(string.Format(@"{0} {1}% {2}",
                                                          plate.Characters.PadRight(12),
                                                          plate.OverallConfidence.ToString("N1").PadLeft(8),
                                                          plate.MatchesTemplate.ToString().PadLeft(8)));
                    }
                }

                if (images.Any())
                {
                    picLicensePlate.Image = combineImages(images);
                }
            }
        }
示例#18
0
        private void processImageFile(string fileName)
        {
            resetControls();
            var    region           = "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    plakaText.Items.Add("Error initializing OpenALPR");
                    return;
                }
                aracPic.ImageLocation = fileName;
                aracPic.Load();

                var results = alpr.Recognize(fileName);

                var images = new List <Image>(results.Plates.Count());
                var i      = 1;
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);
                    string[] plakaList = result.TopNPlates.Select(x => x.Characters).ToArray();
                    plakaYaz.Text = plakaList[0].ToString();

                    plakaText.Items.Add("\t\t-- Plate #" + i++ + " --");
                    foreach (var plate in result.TopNPlates)
                    {
                        plakaText.Items.Add(string.Format(@"{0} {1}% {2}",
                                                          plate.Characters.PadRight(12),
                                                          plate.OverallConfidence.ToString("N1").PadLeft(8),
                                                          plate.MatchesTemplate.ToString().PadLeft(8)));
                    }
                }

                if (images.Any())
                {
                    plakaResim.Image = combineImages(images);
                }
            }
        }
示例#19
0
        private void processImageFile(string fileName)
        {
            var    region           = "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    //lbxPlates.Items.Add("Error initializing OpenALPR");
                    return;
                }
                //picOriginal.ImageLocation = fileName;
                //picOriginal.Load();

                var results = alpr.Recognize(fileName);

                var images = new List <Image>(results.Plates.Count());
                var i      = 1;
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);

                    //lbxPlates.Items.Add("\t\t-- Plate #" + i++ + " --");
                    foreach (var plate in result.TopNPlates)
                    {
                        /*lbxPlates.Items.Add(string.Format(@"{0} {1}% {2}",
                         *                                plate.Characters.PadRight(12),
                         *                                plate.OverallConfidence.ToString("N1").PadLeft(8),
                         *                                plate.MatchesTemplate.ToString().PadLeft(8)));*/
                        tb_license.Text = plate.Characters.PadRight(12);
                        break;
                    }
                }

                if (images.Any())
                {
                    pb_license.Image = combineImages(images);
                }
            }
        }
示例#20
0
        public static string processImageFile(string fileName)
        {
            string resultv2 = "";
            //resetControls();
            var    region           = "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    //resultv2 = "Error initializing OpenALPR";
                    return("Error initializing OpenALPR");
                }
                //pc_procesone.ImageLocation = fileName;
                //pc_procesone.Load();

                var results = alpr.Recognize(fileName);

                var images = new List <Image>(results.Plates.Count());
                // var i = 1;
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);

                    resultv2 = Convert.ToString(EnBenzeyenPlakayiGetir(result.TopNPlates).Trim());
                }

                //if (images.Any())
                //{
                //     = resultv2;
                //    //pc_prosstwo.Image = combineImages(images);
                //}
            }
            //return resultv3;
            return(resultv2);
        }
示例#21
0
        public string processImageFile(string fileName)
        {
            var    region           = "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                var results = alpr.Recognize(fileName);

                var images = new List <Image>(results.Plates.Count());
                //    var i = 1;
                if (results.Plates.Count() == 0)
                {
                    picOriginal.ImageLocation = fileName;
                    picOriginal.Load();
                }
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    picOriginal.Image = cropImage2(img);
                    img.Dispose();
                    images.Add(cropped);
                    foreach (var plate in result.TopNPlates)
                    {
                        lbxPlates.Items.Add(plate.Characters);
                        break;
                    }
                }

                if (images.Any())
                {
                    //   picLicensePlate.Image = combineImages(images); PLakayı kes
                }
            }

            return("");
        }
示例#22
0
        //public List<string> Recognize(byte[] byteArr)
        //{
        //    List<string> RecInfo = new List<string>();

        //    Bitmap Bit;
        //    Image img = byteArrayToImage(byteArr);

        //    CheckOrientation(img);
        //    Bit = resizeImageAspect(640, 480, img);
        //    byteArr = ConvertBitToJpeg(byteArr, Bit);

        //    recognizeProxy proxy = new recognize.recognizeProxy(client_id, api_key, clapi_key);
        //    // proxy.modeChange(RecognitionMode.multi);
        //    recognitionResponse response4 = proxy.recognize1(byteArr, RecognitionMode.single, false);

        //    string responseStatus = "Kažkas negerai";
        //    string responseMessage = "labai negerai";

        //    responseStatus = response4.status.ToString();
        //    responseMessage = response4.message;

        //    RecInfo.Add(responseStatus);
        //    RecInfo.Add(responseMessage);

        //    if (response4.objects != null)
        //    {
        //        foreach (var obj in response4.objects)
        //        {
        //            string id = obj.id;
        //            string name = obj.name;
        //            RecInfo.Add(id);
        //            RecInfo.Add(name);
        //        }
        //    }

        //    return RecInfo;
        //}


        public List <string> Recognize(byte[] byteArr)
        {
            List <string> RecInfo = new List <string>();

            Bitmap Bit;
            Image  img = byteArrayToImage(byteArr);

            CheckOrientation(img);
            Bit     = resizeImageAspect(640, 480, img);
            byteArr = ConvertBitToJpeg(byteArr, Bit);

            var alpr = new AlprNet("eu", @"C:\Users\Laurynas\Documents\Visual Studio 2015\Projects\ConsoleAlpr\ConsoleAlpr\bin\Debug\openalpr.conf", @"C:\Users\Laurynas\Documents\Visual Studio 2015\Projects\ConsoleAlpr\ConsoleAlpr\bin\Debug\runtime_data");


            if (!alpr.IsLoaded())
            {
                string fail = "OpenAlpr failed to load!";
                RecInfo.Add(fail);
                return(RecInfo);
            }

            var    results = alpr.Recognize(byteArr);
            int    i       = 0;
            string platenumber;

            foreach (var result in results.Plates)
            {
                foreach (var plate in result.TopNPlates)
                {
                    platenumber = "Plate: " + plate.Characters + "Confidence: " + plate.OverallConfidence;
                    RecInfo.Add(platenumber);
                }
            }



            return(RecInfo);
        }
示例#23
0
        private void processImageFile(string fileName)//resim seç butonuna tıklanınca seçilenn resmin yolu string filename olarak attım.
        {
            txtPlaka.Text = "";
            resetControls();                                                            // bütün resimler boşta.
            var    region           = radioButton2.Checked ? "us" : "eu";
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf"); //yol oluşturma asıl burada başlıyor.assembly burada uri örneği oluşturuyor.
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    txtPlaka.Text = "Error initializing OpenALPR";
                    return;
                }
                picOriginResim.ImageLocation = fileName;                 // seçtiğim yoldaki resmi ana ekrana alıyorum
                picOriginResim.Load();                                   //resmi yükleme yapıyor.

                var results = alpr.Recognize(fileName);                  //tanımayı yapıyor.

                var images = new List <Image>(results.Plates.Count());   // plaka sayısını atıyor.
                var i      = 1;
                foreach (var result in results.Plates)                   //Resim düzenlemesi yapıyor.//düzenlenen resmi de diğer picboxa atıcak.
                {
                    var rect    = boundingRectangle(result.PlatePoints); // resmi çerçeveleyecek.
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);            //Buralar bulduğu plaka sayısına göre döngüye giriyor.

                    txtPlaka.Text = EnBenzeyenPlakayiGetir(result.TopNPlates);
                }

                if (images.Any())
                {
                    picPlakaResmi.Image = combineImages(images);                               // oluşturulan resmi picplakaresmine attım.
                }
            }
        }
示例#24
0
        private void processImageFile(string fileName)
        {
            resetControls();
            var    region      = checkAmerika.Checked ? "us" : "eu";
            String config_file = Path.Combine(AssemblyDirectory, "openalpr.conf");

            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    txtPlaka.Text = "Kütüphane Yüklenemedi";
                    return;
                }
                picOriginResim.ImageLocation = fileName;
                picOriginResim.Load();

                var results = alpr.Recognize(fileName);

                var images = new List <Image>(results.Plates.Count());
                var i      = 1;
                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);

                    txtPlaka.Text = EnBenzeyenPlakayiGetir(result.TopNPlates);
                }

                if (images.Any())
                {
                    picPlakaResmi.Image = combineImages(images);
                }
            }
        }
        private string processImageFile(string fileName)
        {
            string platenumber = null;
            var    alpr        = new AlprNet(region, config_file, runtime_data_dir);

            if (!alpr.IsLoaded())
            {
                return(platenumber);
            }

            var results = alpr.Recognize(fileName);

            var images = new List <Image>(results.Plates.Count());

            foreach (var result in results.Plates)
            {
                foreach (var plate in result.TopNPlates)
                {
                    /*
                     * if ((plate.Characters[0] >= '0' && plate.Characters[0] <= '9') &&
                     *  (plate.Characters[1] >= '0' && plate.Characters[1] <= '9') &&
                     *  (plate.Characters[2] >= '0' && plate.Characters[2] <= '9') &&
                     *  (plate.Characters[3] >= 'A' && plate.Characters[0] <= 'a' &&
                     *  plate.Characters[3] <= 'z' && plate.Characters[0] <= 'Z') &&
                     *  (plate.Characters[4] <= 'A' && plate.Characters[4] <= 'a' &&
                     *  plate.Characters[4] <= 'z' && plate.Characters[4] <= 'Z') &&
                     *  (plate.Characters[5] <= 'A' && plate.Characters[5] <= 'a' &&
                     *  plate.Characters[5] <= 'z' && plate.Characters[5] <= 'Z'))
                     * {*/
                    platenumber = plate.Characters.ToString();
                    break;
                    //}
                }
            }
            return(platenumber);
        }
示例#26
0
        private void processImageFile(string fileName)
        {
            resetControls();

            //Bölge ayarı yap (Avrupa için "eu", Amerika için "us")
            var region = "eu";

            //OpenALPR ayar dosyalarını yükle
            String config_file      = Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");

            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    MessageBox.Show("OpenALPR yüklenemedi!");
                    return;
                }

                //Fotoğraf yükleme
                fotoOrjinal.ImageLocation = fileName;
                fotoOrjinal.Load();

                //Resimleri klasöre kopyalama kodu. Erişim hatası veriyor.
                try
                {
                    var path = Path.Combine(
                        System.AppDomain.CurrentDomain.BaseDirectory,
                        "plakalar");
                    File.Copy(path, fileName);
                }
                catch
                {
                    MessageBox.Show("Erişim Hatası. Plaka fotoğrafı kaydedilemedi.");
                }

                //Fotoğraf ALPR kütüphanesi ile işlenir
                var results = alpr.Recognize(fileName);

                var images = new List <Image>(results.Plates.Count());

                foreach (var result in results.Plates)
                {
                    var rect    = boundingRectangle(result.PlatePoints);
                    var img     = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);

                    lblPlaka.Text       = "";
                    lblSahibi.Text      = "";
                    lblEklenme.Text     = "";
                    lblSonKullanim.Text = "";
                    lblSonuc.Text       = "Gecemez";

                    //En iyi tahmini gösterir
                    string plaka = result.BestPlate.Characters;
                    lblPlaka.Text = plaka;

                    //Okunan plaka veritabanında aranır. Yoksa MessageBox ile hata mesajı verilir
                    try
                    {
                        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=PlakaTanima.accdb"); con.Open();
                        OleDbCommand    cmd = new OleDbCommand("Select Sahibi, Durum, Eklenme_Tarihi, Son_Kullanim from Plakalar where Plaka='" + lblPlaka.Text + "'", con);
                        OleDbDataReader dr  = cmd.ExecuteReader();
                        while (dr.Read())
                        {
                            lblSahibi.Text      = dr["Sahibi"].ToString();
                            lblEklenme.Text     = dr["Eklenme_Tarihi"].ToString();
                            lblSonKullanim.Text = dr["Son_Kullanim"].ToString();
                            lblSonuc.Text       = dr["Durum"].ToString();
                        }
                        ;
                        con.Close();

                        //Plaka veritabanında yoksa hata mesajı verir
                        if (lblSahibi.Text == "")
                        {
                            MessageBox.Show("Plaka Bulunamadı!");
                            lblSonuc.Text = "Gecemez";
                        }
                        else
                        {
                            //Plaka veritabanında varsa en son okunduğu zaman güncellenir
                            con.Open();
                            cmd = new OleDbCommand("UPDATE Plakalar SET Son_Kullanim = @Son_Kullanim WHERE Plaka = @Plaka", con);
                            cmd.Parameters.Add("@Son_Kullanim", System.DateTime.Now.ToString());
                            cmd.Parameters.Add("@Plaka", lblPlaka.Text);
                            cmd.ExecuteNonQuery();
                            cmd.Dispose();
                            con.Close();
                            con.Dispose();
                        }
                        //Sonuc labelinin rengini kontrol eder
                        if (lblSonuc.Text == "Gecer")
                        {
                            lblSonuc.ForeColor = System.Drawing.Color.Green;
                        }
                        else
                        {
                            lblSonuc.ForeColor = System.Drawing.Color.Red;
                        }

                        con.Close();
                    }
                    catch
                    {
                        MessageBox.Show("Veritabanı Hatası!");
                    }
                }

                //Fotoğraf birleştrime
                if (images.Any())
                {
                    fotoPlaka.Image = combineImages(images);
                }
            }
        }
            private void ExitExaminer()
            {
                AlprNet alpr = new AlprNet("us", "openalpr.conf", "runtime_dir");

                alpr.TopN = 1;
                HashSet <string> recognized = new HashSet <string>();
                Stopwatch        bar        = null;

                while (true)
                {
                    Bitmap bitmap;
                    lock (_lock)
                    {
                        if (_kill)
                        {
                            break;
                        }
                    }
                    if (bar != null && bar.IsRunning)
                    {
                        if (bar.ElapsedMilliseconds < 10000)
                        {
                            continue;
                        }
                        else
                        {
                            bar.Stop();
                            _framesQueue.TryDequeue(out bitmap);
                            _WriteLog("Bar closed", _name);
                        }
                    }
                    if (_framesQueue.TryDequeue(out bitmap))
                    {
                        bool           left    = false;
                        AlprResultsNet results = alpr.Recognize(bitmap);
                        if (results.Plates.Count != 0)
                        {
                            AlprPlateNet plate = results.Plates[0].BestPlate;
                            if (recognized.Add(plate.Characters))
                            {
                                _WriteLog(plate.Characters, _name);
                                try
                                {
                                    Api <HistoryLast> data = ("http://api.ipark.altervista.org/history/" + plate.Characters + "/last").SetQueryParams(new { token = _token }).GetJsonAsync <Api <HistoryLast> >().Result;
                                    if (data.meta.code == 200)
                                    {
                                        if (data.response.payment == null)
                                        {
                                            _WriteLog(plate.Characters + " has not paid yet", _name, LogType.WARNING);
                                            recognized.Remove(recognized.Last());
                                        }
                                        else
                                        {
                                            Api <Registered> internalData = ("http://api.ipark.altervista.org/history/register/exit/" + data.response.plate).SetQueryParams(new { token = _token }).PutJsonAsync(null).ReceiveJson <Api <Registered> >().Result;
                                            if (internalData.meta.code == 200)
                                            {
                                                _UpdatePie(UpdateType.SUB);
                                                _LogResult(internalData.response, _name);
                                                left = true;
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    _WriteLog(exception.ToString(), _name, LogType.ERROR);
                                }
                            }
                        }
                        if (left)
                        {
                            recognized.Clear();
                            bar = new Stopwatch();
                            bar.Start();
                            _WriteLog("Bar raised", _name);
                        }
                    }
                }
            }
示例#28
0
        private void processImageFile(Emgu.CV.Image <Bgr, Byte> framepic)
        {
            using (var alpr = new AlprNet("eu", config_file, runtime_data_dir)) {
                if (!alpr.IsLoaded())
                {
                    txtPlaka.Text = "Yüklenirken hata oldu.Tekrar deneyin";
                    return;
                }

                Image <Bgr, byte> resultx = null;
                resultx = framepic.Copy();
                var  results = alpr.Recognize(framepic.Bitmap);
                bool bulundu = false;

                var images = new List <Image>(results.Plates.Count());

                foreach (var result in results.Plates)
                {
                    var rect = boundingRectangle(result.PlatePoints);
                    Image <Bgr, Byte> img     = framepic;
                    Image <Bgr, Byte> cropped = cropImage(img.Bitmap, rect);
                    images.Add(cropped.Bitmap);

                    //Plakanın etrafına kırmızı dikdörtgen çiziyor

                    Point p = new Point(result.PlatePoints[0].X - 4, result.PlatePoints[0].Y - 25);
                    p.Offset(0, cropped.Size.Height);
                    resultx.Draw(new Rectangle(p, cropped.Size), new Bgr(12, 12, 214), 3);
                    resultx.ROI = new Rectangle(p, cropped.Size);
                    // picOriginResim.Image = resultx;  //if içinden aldım
                    try
                    {
                        cropped.CopyTo(resultx);
                    }
                    catch (Exception e)
                    {
                        continue;
                    }

                    resultx.ROI = Rectangle.Empty;

                    String t = GetMatchedPlate(result.TopNPlates);
                    picOriginResim.Image = resultx;
                    Regex regex = new Regex(@"^(0[0-9]|[1-7][0-9]|8[01])(([A-Z])(\d{4,5})|([A-Z]{2})(\d{3,4})|([A-Z]{3})(\d{2,3}))$");

                    Match match = regex.Match(t.Replace(" ", ""));
                    if (match.Success)
                    {
                        txtPlaka.Text        = t;
                        picOriginResim.Image = resultx;
                        bulundu = true;
                    }
                }

                if (images.Any())
                {
                    picPlakaResmi.Image  = combineImages(images);
                    picOriginResim.Image = resultx;
                }

                if (!bulundu)
                {
                    picOriginResim.Image = framepic;
                }
            }
        }
示例#29
0
        private void processImageFile(string fileName)
        {
            resetControls();
            var region = rbUSA.Checked ? "us" : "eu";
            String config_file =  Path.Combine(AssemblyDirectory, "openalpr.conf");
            String runtime_data_dir = Path.Combine(AssemblyDirectory, "runtime_data");
            using (var alpr = new AlprNet(region, config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    lbxPlates.Items.Add("Error initializing OpenALPR");
                    return;
                }
                picOriginal.ImageLocation = fileName;
                picOriginal.Load();

                var results = alpr.Recognize(fileName);

                var images = new List<Image>(results.Plates.Count());
                var i = 1;
                foreach (var result in results.Plates)
                {
                    var rect = boundingRectangle(result.PlatePoints);
                    var img = Image.FromFile(fileName);
                    var cropped = cropImage(img, rect);
                    images.Add(cropped);

                    lbxPlates.Items.Add("\t\t-- Plate #" + i++ + " --");
                    foreach (var plate in result.TopNPlates)
                    {
                        lbxPlates.Items.Add(string.Format(@"{0} {1}% {2}",
                                                          plate.Characters.PadRight(12),
                                                          plate.OverallConfidence.ToString("N1").PadLeft(8),
                                                          plate.MatchesTemplate.ToString().PadLeft(8)));
                    }
                }

                if (images.Any())
                {
                    picLicensePlate.Image = combineImages(images);
                }
            }
        }
示例#30
0
        public async Task OnPost()
        {
            var hasErrors = false;

            if ((Files?.Count() ?? 0) == 0 || (Files?.Count() ?? 0) > 10)
            {
                ModelState.AddModelError(nameof(Files), "Minim 1, maxim 10 imagini!");
                hasErrors = true;
            }

            var badFiles = Files.Where(f => !f.ContentType.StartsWith("image"));

            if (badFiles.Any())
            {
                ModelState.AddModelError(nameof(Files), $"Următoarele fișiere nu sunt valide: {string.Join(',', badFiles.Select(f => f.FileName))} - toate fișierele trebuie să fie imagini.");
                hasErrors = true;
            }

            if (HidePlates == null)
            {
                ModelState.AddModelError(nameof(HidePlates), "Alege un tip de procesare");
                hasErrors = true;
            }

            if (hasErrors)
            {
                return;
            }

            SessionId = Guid.NewGuid();
            var tasks = Files.Select(async file =>
            {
                using var input = new MemoryStream();
                file.OpenReadStream().CopyTo(input);
                using var bitmap = new Bitmap(input);

                if (HidePlates ?? false)
                {
                    using var alpr = new AlprNet("eu", "openalpr.conf", "RuntimeData");
                    if (!alpr.IsLoaded())
                    {
                        ModelState.AddModelError(nameof(Files), "A intervenit o eroare, te rugăm să încerci mai târziu.");
                        return;
                    }

                    NormalizeOrientation(bitmap);
                    using var ms = new MemoryStream();
                    bitmap.Save(ms, ImageFormat.Jpeg);

                    input.Seek(0, SeekOrigin.Begin);
                    var results = alpr.Recognize(input.ToArray());
                    foreach (var result in results.Plates)
                    {
                        using var graphics = Graphics.FromImage(bitmap);
                        int x             = result.PlatePoints.Min(p => p.X), y = result.PlatePoints.Max(p => p.Y),
                        height            = Math.Abs(y - result.PlatePoints.Min(p => p.Y)), width = Math.Abs(result.PlatePoints.Max(p => p.X) - x);
                        using var crop    = bitmap.Clone(new Rectangle(x, y, width, height), bitmap.PixelFormat);
                        using var blurred = Blur(crop, new Rectangle(0, 0, crop.Width, crop.Height), 10);
                        using var myBrush = new TextureBrush(blurred);
                        graphics.FillPolygon(myBrush, result.PlatePoints.ToArray());
                    }
                }

                if (file.Length > _2MB)
                {
                    var scale                = Math.Sqrt(_2MB / file.Length);
                    var scaleWidth           = (int)(bitmap.Width * scale);
                    var scaleHeight          = (int)(bitmap.Height * scale);
                    using var bmp            = new Bitmap(scaleWidth, scaleHeight);
                    using var graph          = Graphics.FromImage(bmp);
                    graph.InterpolationMode  = InterpolationMode.High;
                    graph.CompositingQuality = CompositingQuality.HighQuality;
                    graph.SmoothingMode      = SmoothingMode.AntiAlias;
                    graph.FillRectangle(new SolidBrush(Color.Black), new RectangleF(0, 0, scaleWidth, scaleHeight));
                    graph.DrawImage(bitmap, 0, 0, scaleWidth, scaleHeight);
                    foreach (var id in bitmap.PropertyIdList)
                    {
                        bmp.SetPropertyItem(bitmap.GetPropertyItem(id));
                    }
                    await SaveBitmap(bmp, file.FileName, file.ContentType);
                }
                else
                {
                    await SaveBitmap(bitmap, file.FileName, file.ContentType);
                }
            });

            try
            {
                await Task.WhenAll(tasks);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "error");
                ModelState.AddModelError(nameof(Files), $"A intervenit o eroare, te rugăm să încerci mai târziu: {ex.Message}");
            }
        }
示例#31
0
        private static void PerformAlpr(AlprNet alpr, byte[] buffer, bool benchmark, bool writeJson)
        {
            var sw = Stopwatch.StartNew();
            var results = alpr.Recognize(buffer);
            sw.Stop();
            if (benchmark)
            {
                Console.WriteLine("Total Time to process image(s): {0} msec(s)", sw.ElapsedMilliseconds);
            }

            if (writeJson)
            {
                //Console.WriteLine(alpr.toJson());
            }
            else
            {
                var i = 0;
                foreach (var result in results.Plates)
                {
                    Console.WriteLine("Plate {0}: {1} result(s)", i++, result.TopNPlates.Count);
                    Console.WriteLine("  Processing Time: {0} msec(s)", result.ProcessingTimeMs);
                    foreach (var plate in result.TopNPlates)
                    {
                        Console.WriteLine("  - {0}\t Confidence: {1}\tMatches Template: {2}", plate.Characters,
                                          plate.OverallConfidence, plate.MatchesTemplate);
                    }
                }
            }
        }
示例#32
0
        private Job ProcessImage(string fileName)
        {
            AlprResultsNet result;
            Job            job = new Job();

            var extension = Path.GetExtension(fileName);

            if (!validExtensions.Contains(extension))
            {
                logger.Information($"Invalid file extension of file {fileName}, moving to error directory.");

                MoveFile(fileName, plateDectectionErrorPath, true);
            }

            logger.Information($"Processing file {fileName}");

            try
            {
                result = alpr.Recognize(fileName);

                job = new Job
                {
                    FileName                = fileName,
                    ImageHeight             = result.ImageHeight,
                    ImageWidth              = result.ImageWidth,
                    Result                  = result.Json,
                    TotalProcessingTimeInMs = result.TotalProcessingTimeMs,
                    ImageData               = File.ReadAllBytes(fileName),
                    Rectangles              = result.RegionsOfInterest.Select(r => new Rectangle {
                        X = r.X, Y = r.X, Width = r.Width, Height = r.Height
                    }).ToList(),
                    State            = JobState.Succeeded,
                    DetectionResults = result.Plates.Select(dp => new DetectionResult
                    {
                        Region             = dp.Region,
                        RegionConfidence   = dp.RegionConfidence,
                        RequestedTopN      = dp.RequestedTopN,
                        ProcessingTimeInMs = dp.ProcessingTimeMs,
                        DetectedPoints     = dp.PlatePoints.Select(p => new DetectedPoint {
                            X = p.X, Y = p.Y
                        }).ToList(),
                        DetectedPlates = dp.TopNPlates.Select(x => new DetectedPlate
                        {
                            OverallConfidence = x.OverallConfidence,
                            MatchesTemplate   = x.MatchesTemplate,
                            Characters        = x.Characters
                        }).ToList()
                    }).ToList()
                };

                MoveFile(fileName, plateDectectionProcessedPath, true);

                logger.Information($"Processed file {fileName}");
            }
            catch (Exception ex)
            {
                job = new Job
                {
                    FileName  = fileName,
                    ImageData = File.Exists(fileName) ? File.ReadAllBytes(fileName) : null,
                    State     = JobState.Failed
                };

                logger.Error(ex, $"Failed to process file {fileName}");
            }

            return(job);
        }
示例#33
0
        private void processImageFile(Bitmap image)
        {
            using (var alpr = new AlprNet("eu", config_file, runtime_data_dir))
            {
                if (!alpr.IsLoaded())
                {
                    return;
                }
                var results = alpr.Recognize(image);
                if (results.Plates.Count() > 0)
                {
                    var images = new List <Image>(results.Plates.Count());
                    foreach (var result in results.Plates)
                    {
                        var minX = result.PlatePoints.Min(p => p.X);
                        var minY = result.PlatePoints.Min(p => p.Y);
                        var maxX = result.PlatePoints.Max(p => p.X);
                        var maxY = result.PlatePoints.Max(p => p.Y);

                        if (minX < 0)
                        {
                            minX = 0;
                        }
                        if (minY < 0)
                        {
                            minY = 0;
                        }
                        if (maxX < minX)
                        {
                            maxX = minX + 10;
                        }
                        if (maxY < minY)
                        {
                            maxY = minY + 10;
                        }
                        if (maxX > image.Width)
                        {
                            maxX = image.Width;
                        }
                        if (maxY > image.Height)
                        {
                            maxY = image.Height;
                        }


                        var rect    = new Rectangle(new Point(minX, minY), new Size(maxX - minX, maxY - minY));
                        var cropped = cropImage(image, rect);
                        images.Add(cropped);
                        numberCar = EnBenzeyenPlakayiGetir(result.TopNPlates).Trim();
                    }
                    CvInvoke.PutText(mt1, numberCar, new System.Drawing.Point(10, (mt1.Height - 40)), FontFace.HersheyDuplex, 1.3, new Bgr(0, 255, 255).MCvScalar);
                    CvInvoke.PutText(mt1, DateTime.Now.ToString(" dd.MM.yyyy HH:mm:ss"), new System.Drawing.Point(10, (mt1.Height - 25)), FontFace.HersheyDuplex, 0.5, new Bgr(0, 255, 255).MCvScalar);
                    pictureBox3.Image = mt1.Bitmap;
                    if (images.Any())
                    {
                        pictureBox2.Image = combineImages(images);
                    }
                }
                else
                {
                    return;
                }
            }
            if (numberCar.Length >= 8)
            {
                camera_in.Stop();
                camera_in.ImageGrabbed -= camera_process;
                timeStop = true;
            }
        }
示例#34
0
        public Boolean RecognizeNumber(string path)
        {
            try
            {
                double maxVehicle = Convert.ToDouble(ConfigurationManager.AppSettings["MaxVehicle"]);
                int    maxResult  = Convert.ToInt32(ConfigurationManager.AppSettings["MaxResult"]);


                string confPath    = AppDomain.CurrentDomain.BaseDirectory + @"\openalpr.conf";
                string runtimePath = AppDomain.CurrentDomain.BaseDirectory + @"\runtime_date";

                AlprNet alpr = new AlprNet("eu", confPath, runtimePath);

                if (!alpr.IsLoaded())
                {
                    throw new System.Exception("Error loading openalpr library");
                }

                alpr.DetectRegion = true;
                alpr.TopN         = maxResult;

                AlprResultsNet results = alpr.Recognize(path);

                if (images != null)
                {
                    images = null;
                }

                if (vehicleResult != null)
                {
                    vehicleResult = null;
                }

                images        = new List <Image>(results.Plates.Count);
                vehicleResult = new List <VehicleResult>();



                Int16 count     = 1;
                Int16 listIndex = 0;

                if (results.Plates.Count > 0)
                {
                    foreach (AlprPlateResultNet result in results.Plates)
                    {
                        if (count > maxVehicle)
                        {
                            break;
                        }

                        Rectangle rect    = BoundingRectangle(result.PlatePoints);
                        Image     img     = Image.FromFile(path);
                        Image     cropped = CropImage(img, rect);
                        cropped = ResizeImage(cropped);
                        images.Add(cropped);

                        string filePath = ConfigurationManager.AppSettings["CSVPath"];


                        foreach (AlprPlateNet plate in result.TopNPlates)
                        {
                            vehicleResult.Add(new VehicleResult(plate.Characters, listIndex, count--));

                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true))
                            {
                                sw.WriteLine(string.Format(string.Join(",", plate.Characters, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"))));
                            }

                            //Console.WriteLine(plate.Characters);

                            listIndex++;
                        }

                        count++;
                    }

                    return(true);
                }
                else
                {
                    return(false);
                }
                //System.IO.File.Delete(path);
            }
            catch (Exception ex) {
                throw ex;
            }

            return(false);
        }