private void Binarization_Click(object sender, RoutedEventArgs e) { Otsu binarization = new Otsu(); outputPicture = new Picture(binarization.ApplyThreshold(70, outputPicture.Bitmap)); OutputImage.Source = outputPicture.BitmapSource; }
private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < bitmaps.Count; i++) { try { //bitmaps[i] = Converter.RgbToBinary(bitmaps[i],trackBar1.Value); //((flowLayoutPanel1.Controls[i]) as PictureBox).Image = new Bitmap(bitmaps[i],100,100); Otsu otsu = new Otsu(); otsu.Convert2GrayScaleFast(bitmaps[i]); int tre = otsu.getOtsuThreshold(bitmaps[i]); //otsu.threshold(bitmaps[i], tre); bitmaps[i] = Converter.GrayToBinary(bitmaps[i], tre); ((flowLayoutPanel1.Controls[i]) as PictureBox).Image = new Bitmap(bitmaps[i], 100, 100); bitmaps[i].Save(@"E:\ocr\out0.jpg"); bitmaps[i] = ImageProcessing.Closing(bitmaps[i], 3, 3); var bmpp = ImageProcessing.FindingLineWithPlate(bitmaps[i]); bmpp.Save(@"E:\ocr\out3.jpg"); } catch (Exception) { MessageBox.Show("Blad"); } } }
private async void OtsuBinaryzationPageMenuFlyoutItem_Click(object sender, RoutedEventArgs e) { AddToUndo(WriteableOutputImage.Clone()); ConvertToGrayScaleITUR_BT709PageMenuFlyoutItem_Click(null, null); int threshold = Otsu.GetOtsuThreshold(WriteableOutputImage); WriteableOutputImage.ForEach((x, y, curColor) => { if (curColor.R > threshold) { return(Color.FromArgb(255, 255, 255, 255)); } return(Color.FromArgb(255, 0, 0, 0)); }); await UpdateOutputImage(); ContentDialog dialog = new ContentDialog { Title = "Binaryzation", Content = "Otsu threshold value = " + threshold, CloseButtonText = "Ok" }; ContentDialogResult result = await dialog.ShowAsync(); }
private void otsu() { //Bitmap temp = (Bitmap)org.Clone(); Bitmap temp = (Bitmap)this.pbGrises.Image.Clone(); Otsu otsu = new Otsu(); //ot.Convert2GrayScaleFast(temp); int otsuThreshold = otsu.getOtsuThreshold((Bitmap)temp); otsu.threshold(temp, otsuThreshold); //textBox1.Text = otsuThreshold.ToString(); pbUmbralizacion.Image = temp; }
unsafe private static Bitmap działajToolStripMenuItem_Click(Bitmap Dana) { Size Zmiejszony = new Size(Dana.Width / StopieńZmiejszenia, Dana.Height / StopieńZmiejszenia); bool *c = Otsu.OtsuGlobalneNaTablice(Otsu.PonierzMonohormatyczny(new Bitmap(Dana, Zmiejszony)), Zmiejszony); var a = WstepnePrzygotowanie.PobierzZZdziecia(ref c, Zmiejszony.Width, Zmiejszony.Height); a *= 8; Bitmap SamLoto = a.WeźFragmntObrazu(Dana, Color.Black); //znajdywanie kodu byte *Mon = Otsu.PonierzMonohormatyczny(SamLoto); Size RozmarLotka = new Size(SamLoto.Width, SamLoto.Height); Otsu.ProgowanieRegionalne(Mon, RozmarLotka, new Size(30, 30)); //Obrócenie.UstawLotka(ref b, c,ref Rozmiar); //pictureBox1.Image = b; //dzielenie na fragmenty int *l; c = (bool *)Mon; Mon = (byte *)c; List <ZdjecieZPozycją>[] ls = PodziałLinik.PodzielNaLiniki(ref c, SamLoto); Graphics g = Graphics.FromImage(SamLoto); float R = 255 / ((ls.Length / 3) - 1); for (int i = 0; i < ls.Length; i++) { byte k = Convert.ToByte((i / 3) * R); Color ck = Color.FromArgb(k, 0, 0); if (i % 3 == 1) { ck = Color.FromArgb(0, k, 0); } else if (i % 3 == 2) { ck = Color.FromArgb(0, 0, k); } Pen pk = new Pen(ck); foreach (var item in ls[i]) { g.DrawRectangle(pk, item.Obszar); } } g.Dispose(); return(SamLoto); }
/// <summary> /// Returns a binarized image using otsu's adaptative thresholding algorithm /// </summary> /// <returns></returns> public Bitmap BinarizeOtsuAdaptive() { using (var grayscale = ToGrayscale()) { Bitmap binarized = (Bitmap)grayscale.Clone(); var data = binarized.LockBits(new Rectangle(0, 0, grayscale.Width, grayscale.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int threshold = Otsu.GetThreshold(grayscale); unsafe { int totalRGB; byte *ptr = (byte *)data.Scan0.ToPointer(); int stopAddress = (int)ptr + data.Stride * data.Height; while ((int)ptr != stopAddress) { totalRGB = ptr[0] + ptr[1] + ptr[2]; if (totalRGB <= threshold) { ptr[2] = 0; ptr[1] = 0; ptr[0] = 0; } else { ptr[2] = 255; ptr[1] = 255; ptr[0] = 255; } ptr += 3; } } binarized.UnlockBits(data); return(binarized); } }
void load_click(Object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = "JPEG (*.jpg)|*.jpg"; if (ofd.ShowDialog() == DialogResult.OK) { orig = new Bitmap(ofd.FileName); imWidth = orig.Width; imHeight = orig.Height; mult = Math.Min(((double)pa.Width) / ((double)imWidth), ((double)pa.Height) / ((double)imHeight)); pb.Width = (int)Math.Round(mult * imWidth); pb.Height = (int)Math.Round(mult * imHeight); pb.Image = orig; mask = Otsu.OtsuMask(orig); mask = new Connect(imWidth, imHeight, mask).Connection(); index = 0; ImageMask(); viewm.Enabled = true; viewp.Enabled = true; proc.Enabled = true; } } }
public Bitmap ApplyMethod(Bitmap src) { var width = src.Width; var height = src.Height; var otsu = Otsu.ApplyOtsu(src); var erosionMethod = new Erosion(); var erosion = erosionMethod.ApplyErosion(otsu); var result = new Bitmap(width, height); for (var i = 0; i < height; ++i) { for (var j = 0; j < width; ++j) { if (erosion.GetPixel(j, i) != otsu.GetPixel(j, i)) { result.SetPixel(j, i, Color.White); } } } for (var i = 2; i < height - 2; ++i) { for (var j = 2; j < width - 2; ++j) { if (result.GetPixel(j, i).R != 0) { dots.Add(new Point(j, i)); } } } for (var i = 0; i < dots.Count; i += 50) { var counts = new Dictionary <int, int>(); for (var j = -i; j < dots.Count; j++) { if (i + j < dots.Count && i + j != i && Math.Abs(dots[i].X - dots[j + i].X) < 25 && Math.Abs(dots[i].Y - dots[j + i].Y) < 25) { var neighbor = dots[i + j]; counts[j + i] = CountingVotes(dots[i], neighbor); } } var greenPen = new Pen(Color.Green, 3); if (counts.Count == 0) { continue; } var max = counts.Max(x => x.Value); if (max == 0) { continue; } using (var graphics = Graphics.FromImage(result)) { var index = counts.First(x => x.Value == max).Key; var points = GetPoints(dots[i], dots[index], result); if (points.Count > 0) { var last = points.Last(); var first = points.First(); if (last.Y < first.Y) { Point temp = last; last = first; first = temp; } double tg = (last.X - first.X) != 0 ? (double)(Math.Abs(last.Y - first.Y)) / Math.Abs(last.X - first.X) : double.MaxValue; if ((last.X - first.X) != 0 && ((tg == 0 && (last.X - first.X) > 12) || Math.Abs(tg - Math.Sqrt(3)) < 0.4)) { graphics.DrawLine(greenPen, first, last); _lineSegments[first] = last; } } } } var ind = 0; var prevYHorisontal = 0; var prev = new Point(); foreach (var point in _lineSegments.Keys) { if ((ind == 0 || (point.Y - prev.Y > 10)) && ((point.Y - _lineSegments[point].Y) / (point.X - _lineSegments[point].X) == 0) && (point.X - _lineSegments[point].X) < 0) { var yellowPen = new Pen(Color.Yellow, 3); using (var graphics = Graphics.FromImage(src)) { if (ind == 0) { var firstGreenY = FindFirstGreen(result); graphics.DrawRectangle(yellowPen, new Rectangle(new Point(point.X - 20, firstGreenY - 10), new Size(100, point.Y - firstGreenY + 10))); prevYHorisontal = point.Y; } else { graphics.DrawRectangle(yellowPen, new Rectangle(new Point(point.X - 40, prevYHorisontal), new Size(75, point.Y - prevYHorisontal + 10))); } ind++; } } prev = point; } return(src); }
public void ProcessFile(string path) { String str = ""; String line = ""; Console.WriteLine("Processed file '{0}'.", path); String label = Path.GetDirectoryName(path); String result = System.IO.Path.GetFileName(label); // Table de correspondance if (Path.GetFileNameWithoutExtension(path).ToUpper() == "TRANSCO") { try { ifs = new FileStream(path, FileMode.Open); transco = new StreamReader(ifs); while ((line = transco.ReadLine()) != null) { String[] split = line.Split('='); Correspondance.Add(split[0], split[1]); } transco.Close(); ifs.Close(); } catch (Exception err) { Console.WriteLine(err.Message); } } else { switch (Path.GetExtension(path).ToUpper()) { case ".JPEG": break; case ".PNG": Bitmap BitmapNormalisation = null; Bitmap BitmapResize = null; Bitmap BitmapBorder = null; Bitmap BitmapFinal = null; Image imgPhotoVert = null; Bitmap bitMapMedian = null; Bitmap bitMapOtsu = null; Bitmap bitMapCCL = null; Bitmap bitMapSave = null; try { BitmapNormalisation = null; imgPhotoVert = Image.FromFile(path); //Image imgPhoto = null; Dictionary <string, Structure> dic = null; string repertoire = Path.GetDirectoryName(path); string pattern = Path.GetFileName(repertoire); char caractere = Convert.ToChar(Correspondance[pattern]); string fichierResize = Path.GetFileNameWithoutExtension(path) + "_R.png"; // Filtre médian bitMapMedian = (Bitmap)imgPhotoVert; // bmp = ToolsImages.Filtres.Median.MedianFilter(bmp, 3); //Otsu Otsu otsu = new Otsu(); bitMapOtsu = (Bitmap)bitMapMedian.Clone(); otsu.Convert2GrayScaleFast(bitMapOtsu); int otsuThreshold = otsu.getOtsuThreshold((Bitmap)bitMapOtsu); otsu.threshold(bitMapOtsu, otsuThreshold); bitMapCCL = (Bitmap)bitMapOtsu.Clone(); bitMapSave = (Bitmap)bitMapCCL.Clone(); // Detection objet CCL dic = SetCCL(bitMapCCL); if (dic.Count == 1) { // Normalement un seul element foreach (var pair in dic) { Structure structure = (Structure)pair.Value; int largeur = structure.Largeur; int hauteur = structure.Hauteur; if (largeur > 0 && hauteur > 0) { Rectangle source_rect = new Rectangle(structure.X, structure.Y, largeur, hauteur); Rectangle dest_rect = new Rectangle(0, 0, largeur, hauteur); BitmapNormalisation = new Bitmap(largeur, hauteur); DisplayGraphics = Graphics.FromImage(BitmapNormalisation); DisplayGraphics.DrawImage(bitMapSave, dest_rect, source_rect, GraphicsUnit.Pixel); } } if (BitmapNormalisation != null) { // Prendre la plus grande largeur int max = MaximumSize(BitmapNormalisation.Height, BitmapNormalisation.Width); BitmapResize = ToolsImages.Conversion.Conversion.ResizeBitmap(BitmapNormalisation, max, max); ///Bordure BitmapBorder = BitmapWithBorder(BitmapResize, BitmapResize.Height + 4); BitmapFinal = Conversion.Conversion.ResizeBitmap((Bitmap)BitmapBorder, 32, 32); //Bitmap bmp = Conversion.Conversion.ResizeBitmap((Bitmap)imgPhotoVert, 29, 29); byte[] test = Conversion.Conversion.ConvertGrayscaleBitmaptoBytes(BitmapFinal); //int reso = 29 * 29; int reso = 32 * 32; for (int i = 0; i < reso; ++i) { str += test[i] + " "; } int a = (int)caractere; // Chiffres 48 à 57 // Majuscules de 65 à 90 // Minuscules de 97 à 122 if (a >= 97 && a <= 122 || a >= 48 && a <= 57) { if (Minuscules_Printed == null) { Minuscules_Printed = new StreamWriter(Path.Combine(this.PathDestination, "Minuscules_Chiffres_1106_Printed.txt")); } Minuscules_Printed.WriteLine(caractere + " " + str); Minuscules_Printed.Flush(); } else { if (Majuscules_Printed == null) { Majuscules_Printed = new StreamWriter(Path.Combine(this.PathDestination, "Majuscules_1106_Printed.txt")); } Majuscules_Printed.WriteLine(caractere + " " + str); Majuscules_Printed.Flush(); } /* * * if (a >= 65 && a <= 90 || a >= 48 && a <= 57) * { * if (Majuscules_Printed == null) * Majuscules_Printed = new StreamWriter(Path.Combine(this.PathDestination, "Majuscules_Printed.txt")); * * Majuscules_Printed.WriteLine(caractere + " " + str); * Majuscules_Printed.Flush(); * } * else * { * if (Minuscules_Printed == null) * Minuscules_Printed = new StreamWriter(Path.Combine(this.PathDestination, "Minuscules_Printed.txt")); * * Minuscules_Printed.WriteLine(caractere + " " + str); * Minuscules_Printed.Flush(); * * }*/ //if (a >= 48 && a <= 57) //{ // if (Chiffres_Printed == null) // Chiffres_Printed = new StreamWriter(Path.Combine(this.PathDestination, "Chiffres_Printed.txt")); // Chiffres_Printed.WriteLine(caractere + " " + str); // Chiffres_Printed.Flush(); //} //else if (a >= 65 && a <= 90) //{ // if (Majuscules_Printed == null) // Majuscules_Printed = new StreamWriter(Path.Combine(this.PathDestination, "Majuscules_Printed.txt")); // Majuscules_Printed.WriteLine(caractere + " " + str); // Majuscules_Printed.Flush(); //} //else if (a >= 97 && a <= 122) //{ // if (Minuscules_Printed == null) // Minuscules_Printed = new StreamWriter(Path.Combine(this.PathDestination, "Minuscules_Printed.txt")); // Minuscules_Printed.WriteLine(caractere + " " + str); // Minuscules_Printed.Flush(); //} } } if (BitmapNormalisation != null) { BitmapNormalisation.Dispose(); BitmapNormalisation = null; } if (BitmapResize != null) { BitmapResize.Dispose(); BitmapResize = null; } if (BitmapBorder != null) { BitmapBorder.Dispose(); BitmapBorder = null; } if (BitmapFinal != null) { BitmapFinal.Dispose(); BitmapFinal = null; } if (DisplayGraphics != null) { DisplayGraphics.Dispose(); DisplayGraphics = null; } if (imgPhotoVert != null) { imgPhotoVert.Dispose(); imgPhotoVert = null; } if (bitMapMedian != null) { bitMapMedian.Dispose(); bitMapMedian = null; } if (bitMapOtsu != null) { bitMapOtsu.Dispose(); bitMapOtsu = null; } if (bitMapCCL != null) { bitMapCCL.Dispose(); bitMapCCL = null; } if (bitMapSave != null) { bitMapSave.Dispose(); bitMapSave = null; } } catch (Exception err) { Console.WriteLine(err.Message + " " + err.Source); } finally { } // Ecrire dans fichier // imgPhoto.Save(Path.Combine(this.PathDestination, fichierResize), ImageFormat.Png); // imgPhoto.Dispose(); break; case ".TIFF": break; default: break; } } }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { IGH_Goo goo = null; Image image = new Image(); if (!DA.GetData(0, ref goo)) { return; } if (!goo.TryGetImage(ref image)) { return; } int mode = 0; DA.GetData(1, ref mode); double numValA = 0.5; DA.GetData(2, ref numValA); double numValB = 0.5; DA.GetData(3, ref numValB); int numValC = 1; DA.GetData(4, ref numValC); Filter filter = new Filter(); int[] indices = new int[] { 2, 3, 4 }; switch ((FilterModes)mode) { case FilterModes.Otsu: filter = new Otsu(); ClearParameters(indices); image.Filters.Add(new Otsu()); break; case FilterModes.SIS: filter = new SIS(); ClearParameters(indices); image.Filters.Add(new SIS()); break; case FilterModes.Bradley: SetParameter(2, "B", "Brightness", "Brightness difference limit"); SetParameter(3, "S", "Size", "Window size"); SetParameter(4); filter = new Bradley(numValA, (int)numValB); image.Filters.Add(new Bradley(numValA, (int)numValB)); break; case FilterModes.Iterative: SetParameter(2, "M", "Minimum", "Minimum error value"); SetParameter(3, "T", "Threshold", "Threshold value"); SetParameter(4); filter = new Iterative(numValA, numValB); image.Filters.Add(new Iterative(numValA, numValB)); break; case FilterModes.Nilback: SetParameter(2, "C", "C", "Mean offset C"); SetParameter(3, "K", "K", "Parameter K"); SetParameter(4, "R", "Radius", "Filter convolution radius"); filter = new Nilback(numValA, numValB, numValC); image.Filters.Add(new Nilback(numValA, numValB, numValC)); break; case FilterModes.Sauvola: SetParameter(2, "R", "R", "Dynamic range"); SetParameter(3, "K", "K", "Parameter K"); SetParameter(4, "R", "Radius", "Filter convolution radius"); filter = new Sauvola(numValA, numValB, numValC); image.Filters.Add(new Sauvola(numValA, numValB, numValC)); break; case FilterModes.WolfJolion: SetParameter(2, "R", "R", "Dynamic range"); SetParameter(3, "K", "K", "Parameter K"); SetParameter(4, "R", "Radius", "Filter convolution radius"); filter = new WolfJolion(numValA, numValB, numValC); image.Filters.Add(new WolfJolion(numValA, numValB, numValC)); break; } message = ((FilterModes)mode).ToString(); UpdateMessage(); DA.SetData(0, image); DA.SetData(1, filter); }
public Bitmap ApplyMethod(Bitmap src) { var width = src.Width; var height = src.Height; var otsu = Otsu.ApplyOtsu(src); var erosionMethod = new Erosion(); var erosion = erosionMethod.ApplyErosion(otsu); var result = new Bitmap(width, height); for (var i = 0; i < height; ++i) { for (var j = 0; j < width; ++j) { if (erosion.GetPixel(j, i) != otsu.GetPixel(j, i)) { result.SetPixel(j, i, Color.White); } } } for (var i = 2; i < height - 2; ++i) { for (var j = 2; j < width - 2; ++j) { if (result.GetPixel(j, i).R != 0) { dots.Add(new Point(j, i)); } } } var maxR = (int)Math.Sqrt(width * width + height * height); var phaseImage = new int[maxR, 180]; var accuraccy = 1; for (var i = 0; i < dots.Count; i += 1) { var infos = new List <PointInfo>(); for (var f = 0; f < 180; ++f) { for (var r = 0; r < maxR; ++r) { var rad = f * Math.PI / 180.0; if (Math.Abs(dots[i].Y * Math.Sin(rad) + dots[i].X * Math.Cos(rad) - r) < accuraccy) { phaseImage[r, f]++; infos.Add(new PointInfo(f, r)); } } } _pointsInfo[dots[i]] = infos; } var maxPhaseValues = new List <int>(); var thetas = new List <double>(); var Rs = new List <int>(); for (var f = 60; f < 120; f += 30) { for (var r = 0; r < maxR; ++r) { var a = phaseImage[r, f]; if (a > 1) { maxPhaseValues.Add(phaseImage[r, f]); thetas.Add(f); Rs.Add(r); } } } var RsUniq = new List <double>(); var horisontalValue = new Point(0, 0); for (var k = 0; k < maxPhaseValues.Count; ++k) { if (RsUniq.Contains(Rs[k])) { continue; } RsUniq.Add(Rs[k]); var theta = (thetas[k] * Math.PI / 180.0); for (var i = 0; i < height; ++i) { for (var j = 0; j < width; ++j) { var a = i * Math.Sin(theta) + j * Math.Cos(theta); var line = (a * 10) % 10 > 5 ? (int)(a + 1) : (int)a; if (line == Rs[k]) { var point = new Point(j, i); if (dots.Contains(point) && Criteria(src.GetPixel(j, i), Color.FromArgb(255, 99, 78, 88))) { result.SetPixel(j, i, Color.FromArgb(255, 0, 255, 0)); if (thetas[k] == 90) { horisontalValue = point; } } } } } } var yellowPen = new Pen(Color.Yellow, 3); using (var graphics = Graphics.FromImage(src)) { var firstGreenY = FindFirstGreen(result); graphics.DrawRectangle(yellowPen, new Rectangle(new Point(horisontalValue.X - 20, firstGreenY - 10), new Size(85, 85))); graphics.DrawRectangle(yellowPen, new Rectangle(new Point(horisontalValue.X - 40, horisontalValue.Y), new Size(55, 55))); } return(src); }