public static Bitmap FileTo24bbpRgb(this string file, double ResizeRatio = 1.0d, double FrameCrop = 1.0d, double ImageZoom = 1.0d, int RotateDegree = 0) { try { StreamReader streamReader = new StreamReader(file); Bitmap tempOri = (Bitmap)Image.FromStream(streamReader.BaseStream, true); int CanvasWidth = (int)Math.Round(ResizeRatio * tempOri.Width); int CanvasHeight = (int)Math.Round(ResizeRatio * tempOri.Height); Bitmap Original = new Bitmap(CanvasWidth, CanvasHeight, PixelFormat.Format24bppRgb); using (Graphics graphics = Graphics.FromImage(Original)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.DrawImage(tempOri, (int)Math.Round(ResizeRatio * (ImageZoom - 1.0d) * tempOri.Width / -2.0d), (int)Math.Round(ResizeRatio * (ImageZoom - 1.0d) * tempOri.Height / -2.0d), (int)Math.Round(ResizeRatio * ImageZoom * tempOri.Width), (int)Math.Round(ResizeRatio * ImageZoom * tempOri.Height)); } tempOri.Dispose(); streamReader.Dispose(); if (FrameCrop != 1.0d) { Crop cropfilter = new Crop(new Rectangle((int)Math.Round(FrameCrop * (1 - FrameCrop) * CanvasWidth), (int)Math.Round(FrameCrop * (1 - FrameCrop) * CanvasHeight), (int)Math.Round(FrameCrop * CanvasWidth), (int)Math.Round(FrameCrop * CanvasHeight))); Original = cropfilter.Apply(Original); } if (RotateDegree != 0) { RotateBicubic rotatefilter = new RotateBicubic(RotateDegree, keepSize: true); Original = rotatefilter.Apply(Original); } return(Original); } catch { throw new Exception("Failed to import the image files."); } }
//rotate with bicubic interpolation private static Bitmap Rotate(Bitmap image) { var angle = r.NextDouble() * .8 - .4; RotateBicubic filter = new RotateBicubic(angle, false); // apply the filter return(filter.Apply(image)); }
public mRotateBicubic(double Angle, bool Fit, System.Drawing.Color CornerColor) { BitmapType = mFilter.BitmapTypes.Rgb24bpp; Effect = new RotateBicubic(Angle, Fit); Effect.FillColor = CornerColor; filter = Effect; }
public static Bitmap RotateBicubic(Bitmap bmp, int degree) { // create filter - rotate for 30 degrees keeping original image size RotateBicubic filter = new RotateBicubic(degree, true); // apply the filter Bitmap newImage = filter.Apply(bmp); return(bmp); }
void goruntuGuncelle() { try { if (comboBox1.SelectedIndex == 0) { //resim döndürme filtresi tanımlandı //bu filtre sistemi yormuyor //diğerleri sistemi zorluyor //resim döndürme saat yönünün tersine doğru yapılıyor //fonksiyona paremetre olarak true verilirse resmin tamamı ekrana sığdırılmıyor //bazı yerler kırpılıyor //fakat resim boyutu (genişliği ve yükseliği) değişmiyor //görüntü daha güzel görünüyor //eğer false olursa resim küçültme büyütme işlemelerinde resim boyutuda (genişliği ve yükseliği) değişiyor //yani false olunca resim daima ekrana sığdırılıyor RotateNearestNeighbor boyutlandirmaFiltresi = new RotateNearestNeighbor(trackBar1.Value, tamEkran); //resim dosyasına filtre uygulandı pictureBox2.Image = boyutlandirmaFiltresi.Apply((Bitmap)pictureBox1.Image); //resim boyut değiştirme filtresi tanımlandı //bu filtre sistemi yormuyor //diğerleri sistemi zorluyor ResizeNearestNeighbor boyutlandirma = new ResizeNearestNeighbor(resim.Width + trackBar2.Value, resim.Height + trackBar2.Value); //resim dosyasına filtre uygulandı pictureBox2.Image = boyutlandirma.Apply((Bitmap)pictureBox1.Image); } if (comboBox1.SelectedIndex == 1) { //resim döndürme filtresi tanımlandı RotateBilinear boyutlandirmaFiltresi = new RotateBilinear(trackBar1.Value, tamEkran); //resim dosyasına filtre uygulandı pictureBox2.Image = boyutlandirmaFiltresi.Apply((Bitmap)pictureBox1.Image); //resim boyut değiştirme filtresi tanımlandı ResizeBicubic boyutlandirma = new ResizeBicubic(resim.Width + trackBar2.Value, resim.Height + trackBar2.Value); //resim dosyasına filtre uygulandı pictureBox2.Image = boyutlandirma.Apply((Bitmap)pictureBox1.Image); } if (comboBox1.SelectedIndex == 2) { //resim döndürme filtresi tanımlandı RotateBicubic boyutlandirmaFiltresi = new RotateBicubic(trackBar1.Value, tamEkran); //resim dosyasına filtre uygulandı pictureBox2.Image = boyutlandirmaFiltresi.Apply((Bitmap)pictureBox1.Image); //resim boyut değiştirme filtresi tanımlandı ResizeBilinear boyutlandirma = new ResizeBilinear(resim.Width + trackBar2.Value, resim.Height + trackBar2.Value); //resim dosyasına filtre uygulandı pictureBox2.Image = boyutlandirma.Apply((Bitmap)pictureBox1.Image); } } catch { } }
public static Bitmap Rotate(Bitmap input, double angle) { if (angle < 0) { angle = 360 + angle; } if (angle == 0) { return(input); } RotateBicubic rotator = new RotateBicubic(angle); return(rotator.Apply(input)); }
private void tbRotate_Scroll(object sender, EventArgs e) { tbScrollValue.Text = tbRotate.Value.ToString(); RotateBicubic filter = new RotateBicubic(tbRotate.Value, true); //RotateNearestNeighbor filter = new RotateNearestNeighbor(tbRotate.Value, true); Bitmap tmpImage = new Bitmap(pbFace.Image); Bitmap convertedBitmap = ConvertToFortmat(tmpImage, PixelFormat.Format24bppRgb); Bitmap newImage = filter.Apply(convertedBitmap); pbFace.Image = null; pbFace.Image = newImage; convertedBitmap.Dispose(); tmpImage.Dispose(); FitFaceImage(); }
private void RotateStripMenuItem1_Click(object sender, EventArgs e) { RotateBicubic ro = new RotateBicubic(90, false); try { pictureBox1ImagePreview.Image = ro.Apply((Bitmap)pictureBox1ImagePreview.Image); imgFile = pictureBox1ImagePreview.Image; pictureBox1ImagePreview.Image = imgFile; pictureBox1ImagePreview.Refresh(); } catch (Exception ex) { MetroFramework.MetroMessageBox.Show(this, "There is no Loaded Picture ib the Box !." + ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Apply a filter over an image /// </summary> /// <param name="imageFilterParameters">Filter parameters</param> /// <returns>Image result of apply filter</returns> public static Bitmap ApplyFilter(ImageFilterParameters imageFilterParameters) { dynamic filterProcessor; // choose the filter switch (imageFilterParameters.Filter) { case EnumImageFilter.GrayScale: filterProcessor = new Grayscale(0.2125, 0.7154, 0.0721); break; case EnumImageFilter.Invert: filterProcessor = new Invert(); break; case EnumImageFilter.Median: filterProcessor = new Median(); break; case EnumImageFilter.Rotate: var finalAngle = imageFilterParameters.Angle ?? 0; filterProcessor = new RotateBicubic(finalAngle); break; case EnumImageFilter.TexturedHue: filterProcessor = new TexturedFilter(new CloudsTexture(), new HueModifier(50)); break; case EnumImageFilter.Resize: var finalWidth = imageFilterParameters.Width ?? imageFilterParameters.Image.Width; var finalHeight = imageFilterParameters.Height ?? imageFilterParameters.Image.Height; filterProcessor = new ResizeBicubic(finalWidth, finalHeight); break; case EnumImageFilter.FaceDetection: return(FaceDetection(imageFilterParameters.Image).ImageResult); default: filterProcessor = new TexturedFilter(new CloudsTexture(), new GrayscaleBT709(), new Sepia()); break; } // apply the filter var response = filterProcessor.Apply(imageFilterParameters.Image); // return new image return(response); }
private void button7_Click(object sender, EventArgs e) { string path = OriPath + "\\test.jpg"; string pathoutput2 = OriPath + "\\testoutput2.jpg"; string pathoutput3 = OriPath + "\\testoutput3.jpg"; string pathoutput4 = OriPath + "\\testoutput4.jpg"; string pathoutput5 = OriPath + "\\testoutput5.jpg"; string pathoutput6 = OriPath + "\\testoutput6.jpg"; string pathoutput7 = OriPath + "\\testoutput7.jpg"; Bitmap image = new Bitmap(path); // 普通最近领算法 ResizeNearestNeighbor filter = new ResizeNearestNeighbor(4000, 3000); // 双线性插值 ResizeBicubic filter2 = new ResizeBicubic(4000, 3000); // 双三次插值 ResizeBilinear filter3 = new ResizeBilinear(4000, 3000); // create filter - rotate for 30 degrees keeping original image size RotateNearestNeighbor filter4 = new RotateNearestNeighbor(30, true); RotateBilinear filter5 = new RotateBilinear(30, true); RotateBicubic filter6 = new RotateBicubic(30, true); // apply the filter Bitmap newImage = filter.Apply(image); newImage.Save(pathoutput2); newImage = filter2.Apply(image); newImage.Save(pathoutput3); newImage = filter3.Apply(image); newImage.Save(pathoutput4); newImage = filter4.Apply(image); newImage.Save(pathoutput5); newImage = filter5.Apply(image); newImage.Save(pathoutput6); newImage = filter6.Apply(image); newImage.Save(pathoutput7); }
/// <summary> /// Gets the corrected image. /// </summary> /// <remarks>Done by looking for the barcodes with OMR::TL, etc.</remarks> public System.Drawing.Image GetCorrectedImage() { if (this.m_disposed) { throw new ObjectDisposedException("ImageProcessor"); } if (!this.IsScannable) { throw new InvalidOperationException("Form doesn't have sufficient control information to perform this operation"); } float dy = this.m_topRight.Y - this.m_topLeft.Y, dx = this.m_topRight.X - this.m_topLeft.X; double offsetAngle = Math.Tan(dy / dx); RotateBicubic rotate = new RotateBicubic(offsetAngle * (180 / Math.PI), true); return(rotate.Apply(this.m_bitmap)); }
private void process1() { var bitmap1 = (Bitmap)sourcebox1.Image; var bitmap2 = (Bitmap)sourcebox2.Image; var hash1 = ImagePhash.ComputeDigest(bitmap1.ToLuminanceImage()); var hash2 = ImagePhash.ComputeDigest(bitmap2.ToLuminanceImage()); var score = ImagePhash.GetCrossCorrelation(hash1, hash2); Console.WriteLine("score: {0}", score); //threshold value var thres = new Threshold(110); Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721); // apply the filter to the model Bitmap grey1 = filter.Apply(bitmap1); thres.ApplyInPlace(grey1); // Apply the filter to the observed image Bitmap grey2 = filter.Apply(bitmap2); thres.ApplyInPlace(grey2); int modelPoints = 0, matchingPoints = 0; var skewChecker = new DocumentSkewChecker(); var angle1 = skewChecker.GetSkewAngle(grey1); var rotationFilter1 = new RotateBicubic(-angle1); rotationFilter1.FillColor = Color.White; grey1 = rotationFilter1.Apply(grey1); var angle2 = skewChecker.GetSkewAngle(grey2); var rotationFilter2 = new RotateBicubic(-angle2); rotationFilter2.FillColor = Color.White; grey2 = rotationFilter2.Apply(grey2); //CorrelationMatching matcher = new CorrelationMatching(5, grey1, grey2); //var results = matcher.GetHashCode(); var detector = new FastCornersDetector(15); var freak = new FastRetinaKeypointDetector(detector); FastRetinaKeypoint[] features1 = freak.Transform(grey1).ToArray(); modelPoints = features1.Count(); Console.WriteLine("count: {0}", modelPoints); FastRetinaKeypoint[] features2 = freak.Transform(grey2).ToArray(); Console.WriteLine("count: {0}", features2.Count()); KNearestNeighborMatching matcher = new KNearestNeighborMatching(7); //var length = 0; IntPoint[][] results = matcher.Match(features1, features2); matchingPoints = results[0].Count(); // similarity of image1 to image2 ////matchingPoints = results[1].Count(); // similarity of image2 to image1 Console.WriteLine("matched points: {0}", matchingPoints); sourcebox1.Image = bitmap1; sourcebox2.Image = bitmap2; var marker1 = new FeaturesMarker(features1, 30); var marker2 = new FeaturesMarker(features2, 30); double similPercent = 0; if (matchingPoints <= 0) { similPercent = 0.0f; } similPercent = (matchingPoints * 100d) / (double)modelPoints; Console.WriteLine("score: {0}", similPercent); simil1.Text = similPercent.ToString("##.##") + "%"; simil2.Text = (score * 100.00d).ToString("##.##") + "%"; angle_text.Text = angle2.ToString("##.##") + "°"; resultbox1.Image = marker1.Apply(grey1); resultbox2.Image = marker2.Apply(grey2); }
public static Tuple <Bitmap, double, Rectangle> smate_rotate(Bitmap src) { Bitmap retB = null; Rectangle retR = Rectangle.Empty; double retAngle = 90.0; double angle = 0.0; RotateBicubic filter = new RotateBicubic(retAngle); Bitmap src1 = filter.Apply(src); //Bitmap src1 = (Bitmap)src.Clone(); Bitmap g = Grayscale.CommonAlgorithms.BT709.Apply(src1); Invert it = new Invert(); it.ApplyInPlace(g); //g.Save("temp_1.jpg"); ImageStatistics stat = new ImageStatistics(g); Threshold t = new Threshold((int)(stat.Gray.Mean - stat.Gray.StdDev)); t.ApplyInPlace(g); //g.Save("temp_2.jpg"); stat = new ImageStatistics(g); DifferenceEdgeDetector edgeDetector = new DifferenceEdgeDetector(); edgeDetector.ApplyInPlace(g); //g.Save("temp_3.jpg"); HoughLineTransformation lineTransform = new HoughLineTransformation(); lineTransform.ProcessImage(g); HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.8); foreach (HoughLine l in lines) { Program.logIt(string.Format("Intensity={0}, Radius={1}, Theta={2}", l.Intensity, l.Radius, l.Theta)); if (l.Radius < 0) { if (l.Theta < 90) { angle = -l.Theta; } else { angle = 180.0 - l.Theta; } } else { if (l.Theta < 90) { angle = -l.Theta; } else { angle = 180.0 - l.Theta; } } if (Math.Abs(angle) < 45.0) { break; } } Program.logIt(string.Format("angle={0}", angle)); retAngle += angle; RotateBicubic r_filter = new RotateBicubic(angle); Bitmap rotated = r_filter.Apply(src1); // crop if (rotated != null) { Grayscale g_filter = new Grayscale(0.2125, 0.7154, 0.0721); Bitmap grayImage = g_filter.Apply(rotated); Blur bf = new Blur(); bf.ApplyInPlace(grayImage); OtsuThreshold o_filter = new OtsuThreshold(); o_filter.ApplyInPlace(grayImage); BlobCounter blobCounter = new BlobCounter(); blobCounter.MinHeight = 20; blobCounter.MinWidth = 20; blobCounter.FilterBlobs = false; blobCounter.BlobsFilter = null; blobCounter.ObjectsOrder = ObjectsOrder.YX; blobCounter.ProcessImage(grayImage); Blob[] blobs = blobCounter.GetObjectsInformation(); Program.logIt(string.Format("blobs={0}", blobCounter.ObjectsCount)); Rectangle r = Rectangle.Empty; for (int i = 1; i < blobs.Length; i++) { Blob b = blobs[i]; Program.logIt(string.Format("{0}: {1}", b.ID, b.Rectangle)); if (r == Rectangle.Empty) { r = b.Rectangle; } else { r = Rectangle.Union(r, b.Rectangle); } } Program.logIt(string.Format("rect: {0}", r)); retR = r; Crop c_filter = new Crop(r); retB = c_filter.Apply(rotated); } return(new Tuple <Bitmap, double, Rectangle>(retB, retAngle, retR)); }
/// <summary> /// /// </summary> /// <param name="img"></param> /// <param name="flip"></param> /// <param name="angle"></param> /// <param name="keep"></param> /// <returns></returns> internal protected static Image RotateImage(Image img, RotateFlipType flip, double angle, bool keep) { if (img != null) { Image dst = AddinUtils.CloneImage(img) as Image; double angleNew = angle; if (angleNew < 0) { angleNew = 360 + angleNew; } if (angleNew == 0) { dst.RotateFlip(flip); return(dst); } else if (angleNew % 90 == 0) { RotateFlipType flipT = RotateFlipType.RotateNoneFlipNone; if (angleNew % 360 == 000) { flipT = RotateFlipType.RotateNoneFlipNone; } else if (angleNew % 360 == 090) { flipT = RotateFlipType.Rotate90FlipNone; } else if (angleNew % 360 == 180) { flipT = RotateFlipType.Rotate180FlipNone; } else if (angleNew % 360 == 270) { flipT = RotateFlipType.Rotate270FlipNone; } dst.RotateFlip(flipT); return(dst); } else { if (keep) { double a = Math.Abs(angleNew); if (0 < a && a < 45) { // } else if (45 < a && a < 135) { RotateFlipType flipT = RotateFlipType.Rotate90FlipNone; dst.RotateFlip(flipT); angleNew = a - 90; } else if (135 < a && a < 225) { // } else if (225 < a && a < 315) { RotateFlipType flipT = RotateFlipType.Rotate270FlipNone; dst.RotateFlip(flipT); angleNew = a - 270; } else if (315 < a && a < 360) { // } } RotateBicubic filter = new RotateBicubic(-angleNew, keep); dst = AddinUtils.ProcessImage(filter, dst); if (!AddinUtils.AlphaFormat.Contains(dst.PixelFormat)) { dst = AddinUtils.MakeAlphaRotate(img as Bitmap, dst as Bitmap, (float)angleNew); } AddinUtils.CloneExif(img, dst); return(dst); } } return(img); }
public static void AforgeRotateAutoCrop(Bitmap image, double angle, string outputPath) { Logger logger = LogManager.GetCurrentClassLogger(); // create filter - rotate for 30 degrees keeping original image size RotateBicubic rFilter = new RotateBicubic(angle, true); // apply the filter Bitmap newImage = rFilter.Apply(image); //return newImage; Bitmap autoCropImage = null; try { autoCropImage = newImage; // create grayscale filter (BT709) Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721); Bitmap grayImage = filter.Apply(autoCropImage); // create instance of skew checker DocumentSkewChecker skewChecker = new DocumentSkewChecker(); // get documents skew angle angle = 0;//skewChecker.GetSkewAngle(grayImage); // create rotation filter RotateBilinear rotationFilter = new RotateBilinear(-angle); rotationFilter.FillColor = Color.White; // rotate image applying the filter Bitmap rotatedImage = rotationFilter.Apply(grayImage); new ContrastStretch().ApplyInPlace(rotatedImage); new Threshold(25).ApplyInPlace(rotatedImage); BlobCounter bc = new BlobCounter(); bc.FilterBlobs = true; // bc.MinWidth = 500; //bc.MinHeight = 500; bc.ProcessImage(rotatedImage); Rectangle[] rects = bc.GetObjectsRectangles(); if (rects.Length == 0) { logger.Error("No rectangle found in image "); } else if (rects.Length == 1) { autoCropImage = rotatedImage.Clone(rects[0], rotatedImage.PixelFormat);; } else if (rects.Length > 1) { // get largets rect Console.WriteLine("Using largest rectangle found in image "); var r2 = rects.OrderByDescending(r => r.Height * r.Width).ToList(); autoCropImage = rotatedImage.Clone(r2[1], rotatedImage.PixelFormat); } else { Console.WriteLine("Huh? on image "); } } catch (Exception ex) { logger.Error(ex.Message); } autoCropImage.Save(outputPath); }