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}"); } } }
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 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")); }
/// <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)); } }
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); }
/// <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(); } }
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); } } }
private void Form1_Load(object sender, EventArgs e) { resetControls(); if (!alpr.IsLoaded()) { txtPlaka.Text = "Yüklenirken hata oldu.Tekrar deneyin"; return; } }
private static void Main(string[] args) { var region = "us"; var detectRegion = false; var benchmark = false; var json = false; var filename = string.Empty; args.Process( () => Console.WriteLine("Usage: r=us/eu b=0/1 j=0/1 d=0/1 f=<filename>"), new CommandLine.Switch("r", val => { if (val.Any()) region = val.First().Trim().ToLower(); }), new CommandLine.Switch("b", val => { if (val.Any()) benchmark = StrToBool(val.First()); }), new CommandLine.Switch("j", val => { if (val.Any()) json = StrToBool(val.First()); }), new CommandLine.Switch("d", val => { if (val.Any()) detectRegion = StrToBool(val.First()); }), new CommandLine.Switch("f", val => { if (val.Any()) filename = val.First().Trim(); }) ); Console.WriteLine("OpenAlpr Version: {0}", AlprNet.GetVersion()); var config = Path.Combine(AssemblyDirectory, "openalpr.conf"); var runtime_data = Path.Combine(AssemblyDirectory, "runtime_data"); var alpr = new AlprNet(region, config, runtime_data); if (!alpr.IsLoaded()) { Console.WriteLine("OpenAlpr failed to load!"); return; } //var samplePath = Path.Combine(AssemblyDirectory, @"samples\eu-1.jpg"); //alpr.TopN = 3; alpr.DefaultRegion = region; alpr.DetectRegion = detectRegion; if (Directory.Exists(filename)) { var files = Directory.GetFiles(filename, "*.jpg", SearchOption.TopDirectoryOnly); foreach (var fname in files) { PerformAlpr(alpr, fname, benchmark, json); } return; } if (!File.Exists(filename)) { Console.WriteLine("The file doesn't exist!"); return; } var buffer = File.ReadAllBytes(filename); PerformAlpr(alpr, buffer, benchmark, json); }
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 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 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 = ""; } } }
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 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); } } }
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); } } }
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); } } }
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); }
//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); }
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. } } }
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); }
public void Start() { logger.Information("PlateDetectionWorker starting..."); if (!Directory.Exists(plateDetectionBasePath)) { Directory.CreateDirectory(plateDetectionBasePath); } if (!Directory.Exists(plateDectectionIncomingPath)) { Directory.CreateDirectory(plateDectectionIncomingPath); } if (!Directory.Exists(plateDectectionProcessedPath)) { Directory.CreateDirectory(plateDectectionProcessedPath); } if (!Directory.Exists(plateDectectionErrorPath)) { Directory.CreateDirectory(plateDectectionErrorPath); } if (!File.Exists(pathToAlprConf)) { throw new Exception("ALPR configuration file doesn't exist."); } if (!Directory.Exists(pathToRuntimeData)) { throw new Exception("Path to ALPR runtime data doesn't exist."); } alpr = new AlprNet(region, pathToAlprConf, pathToRuntimeData); alpr.FrameProcessed += Alpr_FrameProcessed; if (!alpr.IsLoaded()) { logger.Error("OpenAlpr failed to load!"); throw new Exception("OpenAlpr failed to load!"); } //alpr.Configuration.DebugPlateCorners = true; //alpr.Configuration.DebugPlateLines = true; alpr.DetectRegion = true; var existingFiles = Directory.GetFiles(plateDectectionIncomingPath); if (existingFiles.Any()) { logger.Information($"Found {existingFiles.Length} existing files."); var bw = new BackgroundWorker(); bw.DoWork += Bw_DoWork; bw.RunWorkerAsync(existingFiles); } var fsw = new FileSystemWatcher(plateDectectionIncomingPath, "*.*"); fsw.Created += Fsw_Created; fsw.EnableRaisingEvents = true; logger.Information("PlateDetectionWorker started..."); }
private static void Main(string[] args) { var region = "us"; var detectRegion = false; var benchmark = false; var json = false; var filename = string.Empty; args.Process( () => Console.WriteLine("Usage: r=us/eu b=0/1 j=0/1 d=0/1 f=<filename>"), new CommandLine.Switch("r", val => { if (val.Any()) { region = val.First().Trim().ToLower(); } }), new CommandLine.Switch("b", val => { if (val.Any()) { benchmark = StrToBool(val.First()); } }), new CommandLine.Switch("j", val => { if (val.Any()) { json = StrToBool(val.First()); } }), new CommandLine.Switch("d", val => { if (val.Any()) { detectRegion = StrToBool(val.First()); } }), new CommandLine.Switch("f", val => { if (val.Any()) { filename = val.First().Trim(); } }) ); Console.WriteLine("OpenAlpr Version: {0}", AlprNet.GetVersion()); var config = Path.Combine(AssemblyDirectory, "openalpr.conf"); var runtime_data = Path.Combine(AssemblyDirectory, "runtime_data"); var alpr = new AlprNet(region, config, runtime_data); if (!alpr.IsLoaded()) { Console.WriteLine("OpenAlpr failed to load!"); return; } //var samplePath = Path.Combine(AssemblyDirectory, @"samples\eu-1.jpg"); //alpr.TopN = 3; alpr.DefaultRegion = region; alpr.DetectRegion = detectRegion; if (Directory.Exists(filename)) { var files = Directory.GetFiles(filename, "*.jpg", SearchOption.TopDirectoryOnly); foreach (var fname in files) { PerformAlpr(alpr, fname, benchmark, json); } return; } if (!File.Exists(filename)) { Console.WriteLine("The file doesn't exist!"); return; } var buffer = File.ReadAllBytes(filename); PerformAlpr(alpr, buffer, benchmark, json); }
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}"); } }
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 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; } } }
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); } } }
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; } }
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); }