//scaling image public static Bitmap ScaleImage(Bitmap mmap) { var obj = new ResizeNearestNeighbor(50, 50); var result = obj.Apply(mmap); return(result); }
public void resize_nearest() { double[,] diag = Matrix.Magic(5); diag = diag.Divide(diag.Max()); Bitmap input = diag.ToBitmap(); // Create a new resize bilinear filter var filter = new ResizeNearestNeighbor(7, 8); // Apply the filter Bitmap output = filter.Apply(input); Assert.AreEqual(7, output.Width); Assert.AreEqual(8, output.Height); double[,] actual; new ImageToMatrix().Convert(output, out actual); string str = actual.ToString(CSharpMatrixFormatProvider.InvariantCulture); double[,] expected = { { 0.67843137254902, 0.67843137254902, 0.956862745098039, 0.0392156862745098, 0.0392156862745098, 0.317647058823529, 0.6 }, { 0.67843137254902, 0.67843137254902, 0.956862745098039, 0.0392156862745098, 0.0392156862745098, 0.317647058823529, 0.6 }, { 0.917647058823529, 0.917647058823529, 0.2, 0.27843137254902, 0.27843137254902, 0.556862745098039, 0.63921568627451 }, { 0.917647058823529, 0.917647058823529, 0.2, 0.27843137254902, 0.27843137254902, 0.556862745098039, 0.63921568627451 }, { 0.156862745098039, 0.156862745098039, 0.23921568627451, 0.517647058823529, 0.517647058823529, 0.8, 0.87843137254902 }, { 0.4, 0.4, 0.47843137254902, 0.756862745098039, 0.756862745098039, 0.83921568627451, 0.117647058823529 }, { 0.4, 0.4, 0.47843137254902, 0.756862745098039, 0.756862745098039, 0.83921568627451, 0.117647058823529 }, { 0.43921568627451, 0.43921568627451, 0.717647058823529, 1, 1, 0.0784313725490196, 0.356862745098039 } }; Assert.IsTrue(expected.IsEqual(actual, 1e-6)); }
public void ConvertTest2() { // Create a matrix representation // of a 4x4 image with a inner 2x2 // square drawn in the middle double[,] pixels = { { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 0, 0, 0, 0 }, }; // Create the converter to convert the matrix to a image MatrixToImage conv = new MatrixToImage(min: 0, max: 1); // Declare an image and store the pixels on it Bitmap image; conv.Convert(pixels, out image); // Show the image on screen image = new ResizeNearestNeighbor(320, 320).Apply(image); // ImageBox.Show(image, PictureBoxSizeMode.Zoom); Assert.AreEqual(0, conv.Min); Assert.AreEqual(1, conv.Max); Assert.AreEqual(320, image.Height); Assert.AreEqual(320, image.Width); }
private string GerarThumbnail(string caminhoCompletoDoArquivo) { ImageInfo imageInfo; var nomeSaida = Path.Combine(Path.GetDirectoryName(caminhoCompletoDoArquivo), string.Format("{0}_THUMB.JPG", Path.GetFileNameWithoutExtension(caminhoCompletoDoArquivo))); var bitmapOriginal = ImageDecoder.DecodeFromFile(caminhoCompletoDoArquivo, out imageInfo); int width; int height; if (bitmapOriginal.Width > bitmapOriginal.Height) { width = Contexto.DimensoesThumbnail[1]; height = Contexto.DimensoesThumbnail[0]; } else { width = Contexto.DimensoesThumbnail[0]; height = Contexto.DimensoesThumbnail[1]; } var filter = new ResizeNearestNeighbor(width, height); var bmpThumb = filter.Apply(bitmapOriginal); this.SalvarComo(bmpThumb, nomeSaida, ImageFormat.Jpeg, 8, Contexto.QualidadeThumbnail); bmpThumb.Dispose(); bitmapOriginal.Dispose(); return(nomeSaida); }
public void ConvertTest4() { // Create an array representation // of a 4x4 image with a inner 2x2 // square drawn in the middle Color[] pixels = { Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Transparent, Color.Red, Color.Black, Color.Black, Color.Green, Color.Blue, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, }; // Create the converter to create a Bitmap from the array ArrayToImage conv = new ArrayToImage(width: 4, height: 4); // Declare an image and store the pixels on it Bitmap image; conv.Convert(pixels, out image); // Show the image on screen image = new ResizeNearestNeighbor(320, 320).Apply(image); // Accord.Controls.ImageBox.Show(image, PictureBoxSizeMode.Zoom); Assert.AreEqual(0, conv.Min); Assert.AreEqual(1, conv.Max); Assert.AreEqual(320, image.Height); Assert.AreEqual(320, image.Width); }
private void removeBlankPlaces() { Shrink shrinkFilter = new Shrink(Color.FromArgb(255, 255, 255)); ResizeNearestNeighbor resizeFilter = new ResizeNearestNeighbor(0, 0); Bitmap tempImage = shrinkFilter.Apply(_processedImage.Bitmap); // image dimenstoin int width = _processedImage.Width; int height = _processedImage.Height; // shrinked image dimension int tw = tempImage.Width; int th = tempImage.Height; // resize factors float fx = (float)width / (float)tw; float fy = (float)height / (float)th; if (fx > fy) { fx = fy; } // set new size of shrinked image int nw = (int)Math.Round(fx * tw); int nh = (int)Math.Round(fy * th); resizeFilter.NewWidth = nw; resizeFilter.NewHeight = nh; // resize image Bitmap tempImage2 = resizeFilter.Apply(tempImage); Image <Bgr, Byte> imageCV = new Image <Bgr, byte>(tempImage2); _processedImage = imageCV.Mat; }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> /// <remarks></remarks> public TileOCR(string trainingPath) { classifier = new KNearestClassifier(1, Metric.EuclideanDistance, WeightMode.InverseDistance); training = LoadInstancesFromBitmaps(trainingPath); classifier.Train(training); results = new List <OCRResult>(); grayscale = new Grayscale(0, 0.85, 0.15); invert = new Invert(); resize = new ResizeNearestNeighbor(32, 32); floodFill = new PointedColorFloodFill(Color.Black); dilate = new BinaryDilatation3x3(); blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinWidth = 4; blobCounter.MinHeight = 14; blobCounter.MaxWidth = 30; blobCounter.MaxHeight = 30; blobCounter.ObjectsOrder = ObjectsOrder.XY; threshold = new BradleyLocalThresholding(); threshold.PixelBrightnessDifferenceLimit = 0; //Threshold.WindowSize = 20; threshold.WindowSize = 24; }
public Bitmap getCut(System.Drawing.Point inP, System.Drawing.Point finP, System.Drawing.Image imgOrigin) { Crop cut = null; Bitmap bmp = (Bitmap)imgOrigin; if (inP.X < finP.X && inP.Y < finP.Y) { cut = new Crop(new Rectangle(inP.X, inP.Y, finP.X - inP.X, finP.Y - inP.Y)); } else if (inP.X > finP.X && inP.Y > finP.Y) { cut = new Crop(new Rectangle(finP.X, finP.Y, inP.X - finP.X, inP.Y - finP.Y)); } else if (inP.X < finP.X && inP.Y > finP.Y) { cut = new Crop(new Rectangle(inP.X, finP.Y, finP.X - inP.X, inP.Y - finP.Y)); } else if (inP.X > finP.X && inP.Y < finP.Y) { cut = new Crop(new Rectangle(finP.X, inP.Y, inP.X - finP.X, finP.Y - inP.Y)); } bmp = cut.Apply(bmp); ResizeNearestNeighbor filter = new ResizeNearestNeighbor(bmp.Width * 2, bmp.Height * 2); bmp = filter.Apply(bmp); return(bmp); }
public void Infer(ResizeNearestNeighbor layer, ResizeNearestNeighborLayerArgument argument, InferenceContext context) { var inputAlloc = context.MainMemoryMap[layer.Input.Connection.From]; var outputAlloc = context.MainMemoryMap[layer.Output]; argument.MainMemoryInputAddress = inputAlloc.GetAddress(); argument.MainMemoryOutputAddress = outputAlloc.GetAddress(); }
public static Bitmap ResizeNearestNeighbor(Bitmap Imagem, int newWidth, int newHeight) { ResizeNearestNeighbor filter = new ResizeNearestNeighbor(newWidth, newHeight); Imagem = Imagem.Clone(new Rectangle(0, 0, Imagem.Width, Imagem.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb); Imagem = filter.Apply(Imagem); return(Imagem); }
public static Bitmap Shrink(Bitmap img, float scaleFactor) { var newX = (int)(img.Width * scaleFactor); var newY = (int)(img.Height * scaleFactor); var scale = new ResizeNearestNeighbor(newX, newY); return(scale.Apply(img)); }
public override ulong Create(BitmapData image) { var data = new DenseMatrix(32, 32); using (var unmanaged = UnmanagedImage.FromManagedImage(image)) using (var filtered = ExtractChannel.Apply(unmanaged)) { new Convolution(Filter, 9).ApplyInPlace(filtered); using (var imgdata = new ResizeNearestNeighbor(32, 32).Apply(filtered)) { unsafe { byte* src = (byte*)imgdata.ImageData.ToPointer(); int offset = imgdata.Stride - imgdata.Width; int width = imgdata.Width; int height = imgdata.Height; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++, src++) { data.At(y, x, (float)*src / 255); } src += offset; } } } } var dct = DctMatrix.FastDCT(data); int dctsize = 8; var vals = new List<double>(); for (int r = 1; r <= dctsize; r++) { for (int c = 1; c <= dctsize; c++) { vals.Add(dct[r, c]); } } var sorted = new List<double>(vals); sorted.Sort(); var mid = dctsize * dctsize / 2; double median = (sorted[mid - 1] + sorted[mid]) / 2d; ulong index = 1; ulong result = 0; for (int i = 0; i < dctsize * dctsize; i++) { if (vals[i] > median) { result |= index; } index = index << 1; } return result; }
public Bitmap ResizeImage() { ResizeNearestNeighbor filter = new ResizeNearestNeighbor(BitmapToBeResized.Width * 5, BitmapToBeResized.Height * 5); Bitmap resizedImage = filter.Apply(BitmapToBeResized); return(resizedImage); }
public Bitmap Resize(Bitmap bmp, int newWidth, int newHeight) { // create filter ResizeNearestNeighbor filter = new ResizeNearestNeighbor(newWidth, newHeight); // apply the filter Bitmap newImage = filter.Apply(bmp); return(newImage); }
/// <summary> /// Resize an image to 10x20 px /// </summary> /// <param name="image">Reference to a Bitmap</param> private void Resize(ref System.Drawing.Bitmap image) { ResizeNearestNeighbor filter = new ResizeNearestNeighbor(10, 17); try { image = filter.Apply(image); } catch (Exception) { } }
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 ResizeNearestNeighborLayerArgument Convert(ResizeNearestNeighbor layer, ConvertContext context) { return(new ResizeNearestNeighborLayerArgument { InputWidth = (uint)layer.Input.Dimensions[3], InputHeight = (uint)layer.Input.Dimensions[2], Channels = (uint)layer.Input.Dimensions[1], OutputWidth = (uint)layer.Output.Dimensions[3], OutputHeight = (uint)layer.Output.Dimensions[2], AlignCorners = layer.AlignCorners ? 1 : 0 }); }
public mResizeNearistNeighbor(int ImageWidth, int ImageHeight) { BitmapType = mFilter.BitmapTypes.None; Width = ImageWidth; Height = ImageHeight; Effect = new ResizeNearestNeighbor(Width, Height); Sequence.Clear(); Sequence.Add(Effect); }
void reader_IRFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e) { var reference = e.FrameReference.AcquireFrame(); using (InfraredFrame frame = reference.InfraredFrameReference.AcquireFrame()) { if (frame != null) { int width = frame.FrameDescription.Width; int height = frame.FrameDescription.Height; ushort[] data = new ushort[width * height]; byte[] pixelData = new byte[width * height * 4]; int xcoord = 0; int ycoord = 0; frame.CopyFrameDataToArray(data); int akt = 0; Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb); for (int infraredIndex = 0; infraredIndex < data.Length; infraredIndex++) { ushort ir = data[infraredIndex]; byte intensity = (byte)(ir >> 8); pixelData[infraredIndex * 4] = intensity; // Blue pixelData[infraredIndex * 4 + 1] = intensity; // Green pixelData[infraredIndex * 4 + 2] = intensity; // Red pixelData[infraredIndex * 4 + 3] = 255; //Brightness } var bitmapdata = bitmap.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, bitmap.PixelFormat ); IntPtr ptr = bitmapdata.Scan0; Marshal.Copy(pixelData, 0, ptr, pixelData.Length); bitmap.UnlockBits(bitmapdata); bitmap.RotateFlip(RotateFlipType.Rotate180FlipY); EuclideanColorFiltering filter = new EuclideanColorFiltering(); ResizeNearestNeighbor filter2 = new ResizeNearestNeighbor(512, 424); filter.Radius = (short)trackBar1.Value; //Increase this to allow off-whites filter.FillOutside = false; Bitmap bmp = filter.Apply(bitmap); filter2.Apply(bmp); //filter3.Apply(bmp); pictureBox1.Image = bitmap; } } }
public void ConvertTest3() { double[] pixels = { 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, }; ArrayToImage conv1 = new ArrayToImage(width: 4, height: 4); Bitmap image; conv1.Convert(pixels, out image); image = new ResizeNearestNeighbor(16, 16).Apply(image); // Obtain an image // Bitmap image = ... // Show on screen //ImageBox.Show(image, PictureBoxSizeMode.Zoom); // Create the converter to convert the image to a // matrix containing only values between 0 and 1 ImageToMatrix conv = new ImageToMatrix(min: 0, max: 1); // Convert the image and store it in the matrix double[,] matrix; conv.Convert(image, out matrix); /* * // Show the matrix on screen as an image * ImageBox.Show(matrix, PictureBoxSizeMode.Zoom); * * * // Show the matrix on screen as a .NET multidimensional array * MessageBox.Show(matrix.ToString(CSharpMatrixFormatProvider.InvariantCulture)); * * // Show the matrix on screen as a table * DataGridBox.Show(matrix, nonBlocking: true) * .SetAutoSizeColumns(DataGridViewAutoSizeColumnsMode.Fill) * .SetAutoSizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders) * .SetDefaultFontSize(5) * .WaitForClose(); */ Assert.AreEqual(0, matrix.Min()); Assert.AreEqual(1, matrix.Max()); Assert.AreEqual(16 * 16, matrix.Length); }
private Layer ConvertResizeNearestNeighbor(tflite.Operator op) { var inputs = op.GetInputsArray(); var input = _graph.Tensors(inputs[0]).Value; var newSize = _model.GetTensor <int>(_graph.Tensors(inputs[1]).Value); var options = op.BuiltinOptions <tflite.ResizeNearestNeighborOptions>().Value; var blockShape = _graph.Tensors(inputs[1]).Value; var layer = new ResizeNearestNeighbor(input.GetShapeArray().ToNCHW(), newSize[1], newSize[0], options.AlignCorners); _inputs.Add(layer.Input, inputs[0]); _outputs.Add(op.Outputs(0), layer.Output); return(layer); }
private Layer ConvertNearestInterp(paddle.OpDesc op) { var w = GetAttr(op, "out_w").I; var h = GetAttr(op, "out_h").I; var alignCorners = GetAttr(op, "align_corners").B; var x = GetParameter(op.Inputs, "X").Arguments[0]; var output = GetParameter(op.Outputs, "Out").Arguments[0]; var layer = new ResizeNearestNeighbor(GetVarShape(x), w, h, alignCorners); _inputs.Add(layer.Input, x); _outputs.Add(output, layer.Output); return(layer); }
private Bitmap Detecting(Bitmap _bitmap) { UnmanagedImage im = UnmanagedImage.FromManagedImage(_bitmap); float xscale = im.Width / 160f; float yscale = im.Height / 120f; ResizeNearestNeighbor resize = new ResizeNearestNeighbor(160, 120); UnmanagedImage downsample = resize.Apply(im); Rectangle[] regions = detector.ProcessFrame(downsample); if (regions.Length > 0) { tracker.Reset(); // Reduce the face size to avoid tracking background Rectangle window = new Rectangle( (int)((regions[0].X + regions[0].Width / 2f) * xscale), (int)((regions[0].Y + regions[0].Height / 2f) * yscale), 1, 1); window.Inflate( (int)(0.2f * regions[0].Width * xscale), (int)(0.4f * regions[0].Height * yscale)); this.FaceTracked = window; // Initialize tracker tracker.SearchWindow = window; tracker.ProcessFrame(im); marker = new RectanglesMarker(window); marker.ApplyInPlace(im); // (Bitmap) Helpers.BitmapHelper.ByteArrayToImage(Helpers.RijndaelHelper.EncryptBytes(Helpers.BitmapHelper.ImageToByte(im.ToManagedImage()), "fzafa", "afzd")) this.isTracking = true; return(im.ToManagedImage()); } else { this.isDetecting = false; return(_bitmap); } }
private void captureHand(UnmanagedImage mask, Rectangle rect, PictureBox pbArm, PictureBox pbHand) { Crop c = new Crop(rect); var handImage = c.Apply(mask); var ps = handImage.Collect16bppPixelValues(handImage.CollectActivePixels()); if (ps.Length > 0) { ushort max = Matrix.Max(ps); LevelsLinear16bpp levels = new LevelsLinear16bpp(); levels.InGray = new IntRange(0, max); levels.OutGray = new IntRange(0, 65535); levels.ApplyInPlace(handImage); // pbArm.Image = handImage.ToManagedImage(); double cutoff = 30000; Threshold th = new Threshold((int)cutoff); var handMask = th.Apply(handImage); var handMask8bit = AForge.Imaging.Image.Convert16bppTo8bpp(handMask.ToManagedImage()); BlobCounter bch = new BlobCounter(); bch.ObjectsOrder = ObjectsOrder.Area; bch.ProcessImage(handMask8bit); var blob = bch.GetObjectsInformation(); if (blob.Length > 0) { Intersect inters = new Intersect(); inters.UnmanagedOverlayImage = handMask; inters.ApplyInPlace(handImage); Crop ch = new Crop(blob[0].Rectangle); handImage = ch.Apply(handImage); ResizeNearestNeighbor res = new ResizeNearestNeighbor(25, 25); handImage = res.Apply(handImage); var leftHand = AForge.Imaging.Image.Convert16bppTo8bpp(handImage.ToManagedImage()); pbHand.Image = leftHand; } } }
private void PicForm_Load(object sender, EventArgs e) { double heightFactor = (double)sourceImage.Height / sourceImage.Width, widthFactor = sourceImage.Width / sourceImage.Height; ResizeNearestNeighbor resize; if (heightFactor > widthFactor) { resize = new ResizeNearestNeighbor(drawWidht, (int)(drawHeight * heightFactor)); } else { resize = new ResizeNearestNeighbor((int)(drawWidht * widthFactor), drawHeight); } pictureBox.Image = resize.Apply(sourceImage); }
public static BitmapSheet FromImage(string path, int scale, int pieceScale, int pieceSize, bool saveSheet, bool savePieces = false, bool animated = false) { var bs = new BitmapSheet { Bitmaps = new Dictionary <ushort, Bitmap>() }; var bitmap = AImage.FromFile(path); var totalBitmap = new Bitmap(bitmap.Width * scale, bitmap.Height * scale); var index = 0; for (var y = 0; y < bitmap.Height; y += pieceSize) { for (var x = 0; x < bitmap.Width; x += pieceSize) { var crop = new Crop(new Rectangle(x, y, pieceSize, pieceSize)); var piece = crop.Apply(bitmap); var resizeW = System.Math.Min(32, pieceSize * 4); var resizeH = System.Math.Min(32, pieceSize * 4); var outW = System.Math.Min(40, pieceSize * 5); var outH = System.Math.Min(40, pieceSize * 5); var resize = new ResizeNearestNeighbor(resizeW, resizeH); piece = resize.Apply(piece); var outBitmap = new Bitmap(outW, outH); outBitmap.Add(piece); outBitmap = outBitmap.OutlineGlow(0, 0, .8, 1.4, 10); if (savePieces) { outBitmap.Save($"{path} - 0x{index:x2}.png", ImageFormat.Png); } totalBitmap.Add(outBitmap, x * 5, y * 5); bs.Bitmaps.Add((ushort)index, outBitmap); index++; } } if (saveSheet) { totalBitmap.SavePng($"{path} - {(int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds}.png"); } return(bs); }
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); }
private void Stream_NewFrame(object sender, NewFrameEventArgs eventArgs) { int x, y; //gets the current size of the output image so the stream can be resized correctly x = imgOutput.Size.Width; y = imgOutput.Size.Height; Bitmap bmp = (Bitmap)eventArgs.Frame.Clone(); //resizing Image ResizeNearestNeighbor filter = new ResizeNearestNeighbor(x, y); Bitmap resizedImage = filter.Apply(bmp); //sets the output image to the before rezized image imgOutput.Image = resizedImage; }
public AForge.Imaging.UnmanagedImage GetInput(out double[] input, int countBlocks = 100) { double toDbl(Color c) { var s = c.A + c.B + c.G; return(s > 50 ? 1 : 0); } input = new double[countBlocks * countBlocks + 1]; AForge.Imaging.UnmanagedImage img; var filter = new ResizeNearestNeighbor(countBlocks, countBlocks); double angle; lock (balanceLock) { angle = AngleRad; img = filter.Apply(processed); } double max_input = 0; for (int i = 0; i < countBlocks; i++) { for (int j = 0; j < countBlocks; j++) { var d = toDbl(img.GetPixel(i, j)); input[i * countBlocks + j] = d; if (d > max_input) { max_input = d; } } } if (max_input != 0) { for (int i = 0; i < input.Length - 1; i++) { input[i] /= max_input; } } input[countBlocks * countBlocks] = AngleRad / Math.PI / 2.0; return(img); }
public Bitmap ProcessFrame(Bitmap inputBitmap, int x, int y) { // Create an image for AForge to process Bitmap workingImage = new Bitmap(inputBitmap.Width, inputBitmap.Height); workingImage = AForge.Imaging.Image.Clone(inputBitmap, PixelFormat.Format24bppRgb); // Create a mask for ROI selection Rectangle roi = new Rectangle(x - 30, y - 30, 80, 80); Crop roicrop = new Crop(roi); Bitmap outimage = roicrop.Apply(workingImage); BlobCounter blobCounter = new BlobCounter(); blobCounter.ObjectsOrder = ObjectsOrder.Area; Blob[] blobs; // Find the blobs blobCounter.ProcessImage(outimage); blobs = blobCounter.GetObjectsInformation(); List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[0]); GrahamConvexHull grahamScan = new GrahamConvexHull(); List <IntPoint> hullPoints = grahamScan.FindHull(edgePoints); Graphics g = Graphics.FromImage(outimage); Pen redPen = new Pen(Color.Red, 2); g.DrawPolygon(redPen, ToPointsArray(hullPoints)); //g.Clear(Color.Black); //g.DrawImage(handImage, x, y); //g.DrawRectangle(redPen, roi); //g.DrawEllipse(redPen, x, y, 20, 20); ResizeNearestNeighbor resizeFilter = new ResizeNearestNeighbor(160, 160); Bitmap resizedImage = resizeFilter.Apply(outimage); return(resizedImage); }
private UnmanagedImage ZoomImage(UnmanagedImage lfu) { if (ZFactor > 1) { var f1 = new ResizeNearestNeighbor(lfu.Width, lfu.Height); var f2 = new Crop(ViewRectangle); try { lfu = f2.Apply(lfu); lfu = f1.Apply(lfu); } catch (Exception ex) { if (ErrorHandler != null) { ErrorHandler(ex.Message); } } } return(lfu); }
/// <summary> /// Detects face regions and creates trackers /// </summary> /// <param name="image">Image to search for faces on</param> private async void DetectFacesAsync(UnmanagedImage image) { if (this.detector == null) throw new NullReferenceException("Initialize provider first! detector is null"); var sw = new System.Diagnostics.Stopwatch(); sw.Start(); this.isDetectingInProgress = true; double xScale = image.Width / this.DetectingFrameWidthDefault; double yScale = image.Height / this.DetectingFrameHeightDefault; // Resize image (downsample) var resize = new ResizeNearestNeighbor((int) this.DetectingFrameWidthDefault, (int) this.DetectingFrameHeightDefault); UnmanagedImage downsampledImage = resize.Apply(image); // Get detector regions var regions = new Rectangle[0]; await Task.Run(() => regions = detector.ProcessFrame(downsampledImage)); // Check if the face has been steady for 5 frames in a row if (this.detector.Steady > 5) { // Create face tracker for each of detected regions foreach (var region in regions) { this.CreateFaceTracker(region, xScale, yScale, image); } } this.isDetectingInProgress = false; sw.Stop(); this.log.Info("\n{0} faces detected in {1}ms", regions.Length, sw.ElapsedMilliseconds); }
// New frame received by the player private void videoSourcePlayer_NewFrame(object sender, ref Bitmap image) { if (!detecting && !tracking) return; lock (this) { if (detecting) { detecting = false; tracking = false; UnmanagedImage im = UnmanagedImage.FromManagedImage(image); float xscale = image.Width / 160f; float yscale = image.Height / 120f; ResizeNearestNeighbor resize = new ResizeNearestNeighbor(160, 120); UnmanagedImage downsample = resize.Apply(im); Rectangle[] regions = detector.ProcessFrame(downsample); if (regions.Length > 0) { tracker.Reset(); // Will track the first face found Rectangle face = regions[0]; // Reduce the face size to avoid tracking background Rectangle window = new Rectangle( (int)((regions[0].X + regions[0].Width / 2f) * xscale), (int)((regions[0].Y + regions[0].Height / 2f) * yscale), 1, 1); window.Inflate( (int)(0.2f * regions[0].Width * xscale), (int)(0.4f * regions[0].Height * yscale)); // Initialize tracker tracker.SearchWindow = window; tracker.ProcessFrame(im); marker = new RectanglesMarker(window); marker.ApplyInPlace(im); image = im.ToManagedImage(); tracking = true; //detecting = true; } else { detecting = true; } } else if (tracking) { UnmanagedImage im = UnmanagedImage.FromManagedImage(image); // Track the object tracker.ProcessFrame(im); // Get the object position var obj = tracker.TrackingObject; var wnd = tracker.SearchWindow; if (displayBackprojectionToolStripMenuItem.Checked) { var backprojection = tracker.GetBackprojection(PixelFormat.Format24bppRgb); im = UnmanagedImage.FromManagedImage(backprojection); } if (drawObjectAxisToolStripMenuItem.Checked) { LineSegment axis = obj.GetAxis(); // Draw X axis Drawing.Line(im, axis.Start.Round(), axis.End.Round(), Color.Red); } if (drawObjectBoxToolStripMenuItem.Checked && drawTrackingWindowToolStripMenuItem.Checked) { marker = new RectanglesMarker(new Rectangle[] { wnd, obj.Rectangle }); } else if (drawObjectBoxToolStripMenuItem.Checked) { //InteractionPoints p = new InteractionPoints(); //p.setHead(obj.Rectangle); marker = new RectanglesMarker(obj.Rectangle); } else if (drawTrackingWindowToolStripMenuItem.Checked) { marker = new RectanglesMarker(wnd); } else { marker = null; } if (marker != null) marker.ApplyInPlace(im); image = im.ToManagedImage(); } else { if (marker != null) image = marker.Apply(image); } } }