/// <summary> /// Draws a red rectangle on the bitmap /// </summary> /// <param name="bitmap">The bitmap to draw on</param> /// <param name="rect">The position of the rectangle to draw</param> public static void DrawRectangle( WriteableBitmap bitmap, Rect rect ) { int stride = ( bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7 ) / 8; byte[] pixelByteArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels( pixelByteArray, stride, 0 ); for ( int column = 0; column < bitmap.PixelWidth; column++ ) { for ( int row = 0; row < bitmap.PixelHeight; row++ ) { if ( ( column == rect.X && row >= rect.Y && row <= rect.Y + rect.Height ) || ( row == rect.Y && column >= rect.X && column <= rect.X + rect.Width ) || ( column == rect.X + rect.Width && row >= rect.Y && row <= rect.Y + rect.Height ) || ( row == rect.Y + rect.Height && column >= rect.X && column <= rect.X + rect.Width ) ) { int index = row * stride + 4 * column; pixelByteArray[index] = 0; pixelByteArray[index + 1] = 0; pixelByteArray[index + 2] = 255; } } } bitmap.WritePixels( new Int32Rect( 0, 0, bitmap.PixelWidth, bitmap.PixelHeight ), pixelByteArray, stride, 0 ); }
public WriteableBitmapWrapper(WriteableBitmap source) { _inner = source; _width = source.PixelWidth; int width = _inner.PixelWidth; int height = _inner.PixelHeight; _pixels = new int[width * height]; _inner.CopyPixels(_pixels, width * 4, 0); }
public static Mat<byte> BitmapSourceToMat(BitmapSource source) { WriteableBitmap writeableBmp = new WriteableBitmap(source); byte[] rawData = new byte[writeableBmp.PixelWidth * writeableBmp.PixelHeight]; writeableBmp.CopyPixels(rawData, writeableBmp.PixelWidth, 0); Mat<byte> image = new Mat<byte>(writeableBmp.PixelHeight, writeableBmp.PixelWidth); for (int i = 0; i < writeableBmp.PixelHeight; i++) for (int j = 0; j < writeableBmp.PixelWidth; j++) image[i, j] = rawData[i * writeableBmp.PixelWidth + j]; return image; }
/// <summary> /// Obtains the image data once it is loaded /// </summary> protected void Image_ImageOpened(object sender, RoutedEventArgs e) { if (bitmap == null) { bitmap = new WriteableBitmap((BitmapImage)image.Source); image.Source = bitmap; #if WPF int w = bitmap.PixelWidth; int h = bitmap.PixelHeight; pixelData = new int[w * h]; int widthInBytes = 4 * w; bitmap.CopyPixels(pixelData, widthInBytes, 0); #else pixelData = bitmap.Pixels; #endif } }
public TileSet(System.Drawing.Bitmap source, int tileWidth, int tileHeight) { _source = new WriteableBitmap(Imaging.CreateBitmapSourceFromHBitmap( source.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(source.Width, source.Height))); TileWidth = tileWidth; TileHeight = tileHeight; _tilesPerRow = (int)_source.Width / TileWidth; _bytesPerPixel = _source.Format.BitsPerPixel / BITS_PER_BYTE; _stride = _source.PixelWidth * _bytesPerPixel; _originalPixels = new byte[_stride * _source.PixelHeight]; _source.CopyPixels(_originalPixels, _stride, 0); _tiles = new List<CroppedBitmap>(); GenerateTiles(); }
public void execute() { if (Path != null) origin = LoadBitmap(Path); try { if (origin != null) { origin = origin.Resize(68, 42, WriteableBitmapExtensions.Interpolation.NearestNeighbor); origin.CopyPixels(new Int32Rect(0,0,origin.PixelWidth,origin.PixelHeight), monitor.BackBuffer, monitor.BackBufferStride * monitor.PixelHeight, monitor.BackBufferStride); } } catch (AccessViolationException e) { MessageBox.Show(e.Message); } }
/// <summary> /// Colors the connected objects in the bitmap. Note this function assumes the image is thresholded /// </summary> /// <param name="bitmap">The bitmap to color</param> /// <returns>A list of final colors in the image, one for each object</returns> public static List<Color> ColorBitmap( WriteableBitmap bitmap ) { int stride = ( bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7 ) / 8; byte[] pixelArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels( pixelArray, stride, 0 ); var colorMergeDictionary = new Dictionary<int, int>(); var colors = new List<Color>(); var random = new Random(); for ( int i = 0; i < bitmap.PixelHeight; i++ ) { for ( int j = 0; j < bitmap.PixelWidth; j++ ) { int index = i * stride + 4 * j; // Check if it is a foreground object and has not been colored if ( GetPixelColor( pixelArray, index ) == Colors.Black ) { var color = GetPixelColoring( pixelArray, index, stride, colors, random, colorMergeDictionary ); pixelArray[index] = color.B; pixelArray[index + 1] = color.G; pixelArray[index + 2] = color.R; // Keep track of all the colors in the image so // we can merge them later if ( !colors.Contains( color ) ) { colors.Add( color ); colorMergeDictionary[colors.Count - 1] = colors.Count - 1; } } } } var trueColors = MergeConnectedColors( pixelArray, colors, colorMergeDictionary ); bitmap.WritePixels( new Int32Rect( 0, 0, bitmap.PixelWidth, bitmap.PixelHeight ), pixelArray, stride, 0 ); return trueColors; }
public unsafe override void Draw(WriteableBitmap desktop) { // Avoid exception if window is dragged bottom of screen if (rectangle.Top + rectangle.Height >= framebuffer.Height) { rectangle.Height = framebuffer.Height - rectangle.Top - 1; } if ((rectangle.Y * desktop.PixelWidth + rectangle.X) < (source.Y * desktop.PixelWidth + source.X)) { Int32Rect srcRect = new Int32Rect(source.X, source.Y, rectangle.Width, rectangle.Height); desktop.WritePixels(srcRect, desktop.BackBuffer, desktop.BackBufferStride * desktop.PixelHeight, desktop.PixelWidth * 4, rectangle.X, rectangle.Y); } else { Int32[] pixelBuf = new Int32[rectangle.Width * rectangle.Height]; desktop.CopyPixels(new Int32Rect(source.X, source.Y, rectangle.Width, rectangle.Height), pixelBuf, rectangle.Width * 4, 0); desktop.WritePixels(new Int32Rect(0, 0, rectangle.Width, rectangle.Height), pixelBuf, rectangle.Width * 4, rectangle.X, rectangle.Y); } }
public static void ApplyBlobMaskToOtherBitmaps(WriteableBitmap bitmap, WriteableBitmap gradientBitmapRef, WriteableBitmap realBitmapRef, System.Windows.Media.Color blobColor) { int stride = (bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7) / 8; byte[] pixelByteArray = new byte[bitmap.PixelHeight * stride]; byte[] gradientByteArray = new byte[gradientBitmapRef.PixelHeight * stride]; byte[] realByteArray = new byte[realBitmapRef.PixelHeight * stride]; bitmap.CopyPixels(pixelByteArray, stride, 0); gradientBitmapRef.CopyPixels(gradientByteArray, stride, 0); realBitmapRef.CopyPixels(realByteArray, stride, 0); for (int column = 0; column < bitmap.PixelWidth; column++) { for (int row = 0; row < bitmap.PixelHeight; row++) { int index = row * stride + 4 * column; var pixelColor = new System.Windows.Media.Color(); pixelColor = System.Windows.Media.Color.FromRgb(pixelByteArray[index + 2], pixelByteArray[index + 1], pixelByteArray[index]); if (pixelColor != blobColor) { gradientByteArray[index] = 0; gradientByteArray[index + 1] = 0; gradientByteArray[index + 2] = 0; realByteArray[index] = 0; realByteArray[index + 1] = 0; realByteArray[index + 2] = 0; } } } gradientBitmapRef.WritePixels(new Int32Rect(0, 0, gradientBitmapRef.PixelWidth, gradientBitmapRef.PixelHeight), gradientByteArray, stride, 0); realBitmapRef.WritePixels(new Int32Rect(0, 0, realBitmapRef.PixelWidth, realBitmapRef.PixelHeight), realByteArray, stride, 0); }
public void Can_Create_Color_Image() { var imageFactory = new RgbImageSourceFactory(); var pointerFactory = new ArrayToPointerFactory(); var data = new ushort[20 * 10 * 2]; for (int index = data.Length / 2; index < data.Length; index++) { data[index] = ushort.MaxValue; } var bitmap = new WriteableBitmap(20, 10, 96, 96, PixelFormats.Bgr24, null); var pointer = pointerFactory.CreatePointer(data); try { imageFactory.CreateImage(bitmap, pointer); } finally { pointerFactory.Destroy(pointer); } int height = bitmap.PixelHeight; int width = bitmap.PixelWidth; int stride = bitmap.PixelWidth * 3; byte[] pixelByteArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels(pixelByteArray, stride, 0); Assert.AreEqual(0, pixelByteArray[0]); Assert.AreEqual(0, pixelByteArray[1]); Assert.AreEqual(0, pixelByteArray[2]); Assert.AreEqual(255, pixelByteArray[10 * 3 + 9 * stride]); Assert.AreEqual(255, pixelByteArray[10 * 3 + 9 * stride + 1]); Assert.AreEqual(255, pixelByteArray[10 * 3 + 9 * stride + 2]); }
public Image Create(BitmapSource bitmapSource) { if (bitmapSource == null) return Image.Empty; try { var width = bitmapSource.PixelWidth; var height = bitmapSource.PixelHeight; var format = bitmapSource.Format; var bitmap = new WriteableBitmap(bitmapSource); var bytesPerPixel = (bitmap.Format.BitsPerPixel + 7)/8; var stride = 4*((bitmapSource.PixelWidth*bytesPerPixel + 3)/4); var length = stride*bitmapSource.PixelHeight; var pixels = new byte[length]; bitmap.CopyPixels(pixels, stride, 0); return new Image(format.BitsPerPixel, width, height, pixels, format.ToString()); } catch (Exception) { return Image.Empty; } }
public static BitmapSource ColorizeBitmap(BitmapSource bmp, Color tint) { var wbmp = new WriteableBitmap(bmp); var arr = new uint[wbmp.PixelWidth * wbmp.PixelHeight]; wbmp.CopyPixels(arr, wbmp.PixelWidth * 4, 0); for (int i = 0; i < arr.Length; ++i) { byte a = (byte)((arr[i] >> 24) & 0xff); byte r = (byte)((arr[i] >> 16) & 0xff); byte g = (byte)((arr[i] >> 8) & 0xff); byte b = (byte)((arr[i] >> 0) & 0xff); var c = Color.FromArgb(a, r, g, b); c = TileSetHelpers.TintColor(c, tint); arr[i] = (uint)((c.A << 24) | (c.R << 16) | (c.G << 8) | (c.B << 0)); } wbmp.WritePixels(new Int32Rect(0, 0, wbmp.PixelWidth, wbmp.PixelHeight), arr, wbmp.PixelWidth * 4, 0); return wbmp; }
public static System.Windows.Media.Color PixelColorOfCentralBlob(WriteableBitmap bitmap) { int stride = (bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7) / 8; ConcurrentDictionary<System.Windows.Media.Color, int > colorDict = new ConcurrentDictionary<System.Windows.Media.Color, int>(); byte[] pixelByteArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels(pixelByteArray, stride, 0); //Draw a Horizontal Line accross the middle for (int column = 0; column < bitmap.PixelWidth; column++) { var color = new System.Windows.Media.Color(); int row = (int)(bitmap.PixelHeight/2.0); int index = row * stride + 4 * column; int R = Convert.ToInt32(pixelByteArray[index+2]); int G = Convert.ToInt32(pixelByteArray[index+1]); int B = Convert.ToInt32(pixelByteArray[index]); color = System.Windows.Media.Color.FromRgb(pixelByteArray[index + 2], pixelByteArray[index + 1], pixelByteArray[index]); if (!(R == 255 && B == 255 && G == 255) && !(R== 0 && B == 0 && G == 0)) { colorDict.AddOrUpdate(color, 1, (id, count) => count + 1); } } int maxValue = 0; var colorKey = new System.Windows.Media.Color(); foreach (var item in colorDict) { if (item.Value > maxValue) { colorKey = item.Key; maxValue = item.Value; } } return colorKey; }
/// <summary> /// Méthode qui permet de générer la carte de chaleur ou de transparence de l'image /// </summary> /// <param name="mode">Mode sélectionné</param> /// <param name="img">Image sur laquelle on appose le masque</param> private void GenerateMask(string mode, ImageExp img) { ImageBmp = new WriteableBitmap(new BitmapImage(new Uri(img.Acces, UriKind.RelativeOrAbsolute))); imgBackground.Source = ImageBmp; // Taille de l'image d'origine //int width = imageBitmap.PixelWidth; //int height = imageBitmap.PixelHeight; int width = 1680; int height = 900; // Creation du masque a partir du bitmap d'origine WriteableBitmap bitmap = new WriteableBitmap(ImageBmp); // Pixels Destination (r,g,b,a) byte[, ,] pixels = new byte[height, width, 4]; // Pixels Source int strideSource = ImageBmp.PixelWidth * 4; int sizeSource = ImageBmp.PixelHeight * strideSource; byte[] pixelSource = new byte[sizeSource]; bitmap.CopyPixels(pixelSource, strideSource, 0); double max = Data[AppData.ImagesExp[img.Numero-1]].Cast<double>().Max(); for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { // le numéro de l'image à indiquer est un en dessous double tps = Data[AppData.ImagesExp[img.Numero-1]][row, col]; // Pixel d'origine int indexSource = row * strideSource + 4 * col; double coef = tps / max; // 0 : bleu, 1 : vert, 2 : rouge // Cas où on demande le gris if (mode == "gris") { pixels[row, col, 0] = (byte)(pixelSource[indexSource] * coef); pixels[row, col, 1] = (byte)(pixelSource[indexSource + 1] * coef); pixels[row, col, 2] = (byte)((pixelSource[indexSource + 2]) * coef); } // Cas où l'utilisateur demande de la couleur else { int x = (int)Math.Floor((1000 / max) * (max-tps)); if (x >= 0 && x < 255) { pixels[row, col, 2] = (byte)(pixelSource[indexSource+2]/2 + (255)/2); pixels[row, col, 1] = (byte)(pixelSource[indexSource+1]/2 + (x)/2); pixels[row, col, 0] = (byte)( pixelSource[indexSource]/2 + (0)/2); } if (x >= 255 && x < 510) { pixels[row, col, 2] = (byte)(pixelSource[indexSource + 2] / 2 + (510 - x) / 2); pixels[row, col, 1] = (byte)(pixelSource[indexSource + 1] / 2 + (255) / 2); pixels[row, col, 0] = (byte)(pixelSource[indexSource] / 2 + (0) / 2); } if (x >= 510 && x < 765) { pixels[row, col, 2] = (byte)(pixelSource[indexSource + 2] / 2 + (0) / 2); pixels[row, col, 1] = (byte)(pixelSource[indexSource + 1] / 2 + (255) / 2); pixels[row, col, 0] = (byte)(pixelSource[indexSource] / 2 + (x-510) / 2); } if (x >= 765 && x < 1020) { pixels[row, col, 2] = (byte)(pixelSource[indexSource + 2] / 2 + (0) / 2); pixels[row, col, 1] = (byte)(pixelSource[indexSource + 1] / 2 + (1020-x) / 2); pixels[row, col, 0] = (byte)(pixelSource[indexSource] / 2 + (255) / 2); } if (x >= 1020 && x < 1275) { pixels[row, col, 2] = (byte)(pixelSource[indexSource + 2] / 2 + (x-1020) / 2); pixels[row, col, 1] = (byte)(pixelSource[indexSource + 1] / 2 + (0) / 2); pixels[row, col, 0] = (byte)(pixelSource[indexSource] / 2 + (255) / 2); } if (x >= 1275 && x <= 1530) { pixels[row, col, 2] = (byte)(pixelSource[indexSource + 2] / 2 + (255) / 2); pixels[row, col, 1] = (byte)(pixelSource[indexSource + 1] / 2 + (0) / 2); pixels[row, col, 0] = (byte)(pixelSource[indexSource] / 2 + (1530-x) / 2); } } // Alpha pixels[row, col, 3] = 255; } } // Flat le tableau byte[] pixels1d = new byte[height * width * 4]; int index = 0; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { for (int i = 0; i < 4; i++) pixels1d[index++] = pixels[row, col, i]; } } Int32Rect rect = new Int32Rect(0, 0, width, height); int stride = 4 * width; bitmap.WritePixels(rect, pixels1d, stride, 0); imgMask.Source = bitmap; }
public static List<Rect> FindFaces( WriteableBitmap bitmap ) { int stride = ( bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7 ) / 8; byte[] pixelArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels( pixelArray, stride, 0 ); int bitmapWidth = bitmap.PixelWidth; int bitmapHeight = bitmap.PixelHeight; var faceLock = new Object(); var faces = new List<Rect>(); for ( int width = bitmapWidth - 1; width > 15; width -= 15 ) { for ( int height = bitmapHeight - 1; height > 15; height -= 15 ) { Parallel.ForEach( ExtensionMethods.SteppedRange( 0, bitmapWidth - width, bitmapWidth / 45 ), column => { Parallel.ForEach( ExtensionMethods.SteppedRange( 0, bitmapHeight - height, bitmapHeight / 45 ), row => { var croppedPixelArray = pixelArray.CropPixelArray( column, row, width, height, stride ); var colorBins = GetColorBins( croppedPixelArray, true ); var distance = CalculateBinDistance( colorBins, FaceTemplate ); if ( distance <= 36 /*distance threshold*/ ) { var rect = new Rect( new Point( column, row ), new Size( width, height ) ); lock ( faceLock ) { if ( !faces.Any( x => x.Contains( rect ) ) ) { faces.Add( rect ); } } } } ); } ); } } var significantFaces = faces.Select( x => MergeSignificantIntersections( x, faces ) ).Distinct().ToList(); while ( true ) { var oldCount = significantFaces.Count; significantFaces = significantFaces.Select( x => MergeSignificantIntersections( x, significantFaces ) ).Distinct().ToList(); var newCount = significantFaces.Count; if ( oldCount == newCount ) { break; } } Console.WriteLine( "Found {0} possible face(s)", faces.Count ); Console.WriteLine( "Found {0} possible significant face(s)", significantFaces.Count ); Console.WriteLine( "Press any key to continue..." ); Console.ReadKey(); return significantFaces; }
/// <summary> /// Takes a bitmap whites out all the pixels of a color not of the given color /// </summary> /// <param name="bitmap">The bitmap to start with</param> /// <param name="color">The color to keep</param> /// <returns>A bitmap that only has the given color remaining</returns> public static WriteableBitmap EraseAllButCertainColor( WriteableBitmap bitmap, Color color ) { int stride = ( bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7 ) / 8; byte[] pixelByteArray = new byte[bitmap.PixelHeight * stride]; byte[] newPixelByteArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels( pixelByteArray, stride, 0 ); for ( int i = 0; i < bitmap.PixelWidth; i++ ) { for ( int j = 0; j < bitmap.PixelHeight; j++ ) { int index = j * stride + 4 * i; if ( GetPixelColor( pixelByteArray, index ) != color ) { newPixelByteArray[index] = 255; newPixelByteArray[index + 1] = 255; newPixelByteArray[index + 2] = 255; } else { newPixelByteArray[index] = color.B; newPixelByteArray[index + 1] = color.G; newPixelByteArray[index + 2] = color.R; } } } var newBitmap = bitmap.Clone(); newBitmap.WritePixels( new Int32Rect( 0, 0, bitmap.PixelWidth, bitmap.PixelHeight ), newPixelByteArray, stride, 0 ); return newBitmap; }
public static Rect GetBoundingBoxOfColor( WriteableBitmap bitmap, Color color ) { int stride = ( bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7 ) / 8; byte[] pixelArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels( pixelArray, stride, 0 ); var boundingBox = new Rect( int.MaxValue, int.MaxValue, 0, 0 ); for ( int column = 0; column < bitmap.PixelWidth; column++ ) { for ( int row = 0; row < bitmap.PixelHeight; row++ ) { int index = row * stride + 4 * column; if ( GetPixelColor( pixelArray, index ) == color ) { boundingBox.X = Math.Min( boundingBox.X, column ); boundingBox.Y = Math.Min( boundingBox.Y, row ); boundingBox.Width = Math.Max( boundingBox.Width, column - boundingBox.X ); boundingBox.Height = Math.Max( boundingBox.Height, row - boundingBox.Y ); } } } return boundingBox; }
public static double[] GetColorBins( WriteableBitmap bitmap, bool normalize = false ) { int stride = ( bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7 ) / 8; byte[] pixelArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels( pixelArray, stride, 0 ); return GetColorBins( pixelArray, normalize ); }
public WriteableBitmapWrapper(int width, int height) { _inner = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null); _pixels = new int[width * height]; _inner.CopyPixels(_pixels, width * 4, 0); }
public static void EraseAllButCertainColorandWhite(WriteableBitmap bitmap, System.Windows.Media.Color color) { int stride = (bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7) / 8; byte[] pixelByteArray = new byte[bitmap.PixelHeight * stride]; bitmap.CopyPixels(pixelByteArray, stride, 0); for (int column = 0; column < bitmap.PixelWidth; column++) { for (int row = 0; row < bitmap.PixelHeight; row++) { int index = row * stride + 4 * column; if (GetPixelColor(pixelByteArray, index) != color && GetPixelColor(pixelByteArray, index) != Colors.White) { pixelByteArray[index] = 0; pixelByteArray[index + 1] = 0; pixelByteArray[index + 2] = 0; } } } bitmap.WritePixels(new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight), pixelByteArray, stride, 0); }
/// <summary> /// Metoda typu Coarse-grained, realizująca ważone nakładanie obrazów. /// </summary> public unsafe void BlendImages() { #region Load Bitmap LoadImagesFromUserPaths(); SetMaxArraySize(); CropAllImagesToMaxArraySize(); WriteableBitmap img1Bitmap = new WriteableBitmap(croppedBmpList[0]); WriteableBitmap img2Bitmap = new WriteableBitmap(croppedBmpList[1]); #endregion #region Initialization int linePadding; // liczba bajtów wyrównujacych wiersz do wielokrotności 4 int moduloFromDivWidthByFour = ((int)Math.Round(croppedBmpList[0].Width) * 3) % 4; /* * Ustalenie odpowiedniego wyrównania, jeśli wiersz dzieli się przez 4 bez reszty, wtedy w zapisie dodatkowe bajty nie występują * w przeciwnym wypadku wyrównanie równa się liczbie brakujących bajtów aby wiersz był wielokrotnością 4. */ linePadding = (moduloFromDivWidthByFour == 0) ? 0 : (4 - moduloFromDivWidthByFour); int stride = ((int)Math.Round(croppedBmpList[0].Width) * 4) + linePadding; // rozmiar wiersza w bajtach int arraySize = stride * (int)Math.Round(croppedBmpList[0].Height); // rozmiar tablicy pikseli (ilosc_bajtow_w_wierszu * liczba_wierszy) img1PixelsByte = new byte[arraySize]; // tablice pikseli img2PixelsByte = new byte[arraySize]; img1Bitmap.CopyPixels(img1PixelsByte, stride, 0); // kopiowanie tablicy pikseli z bitmapy do tablicy bajtów, z ustalonym krokiem, zaczynając od 0 img2Bitmap.CopyPixels(img2PixelsByte, stride, 0); #endregion /* * Jeśli będzie używany algortym z biblioteki ASM należy * utworzyć tablicę pikseli, w postaci wskaźników. */ if (appSettings.LoadAsmLibrary == true) { intBitmapsList = createIntArrayFromByte(); } else { byteBitmapsList = new byte[2][]; byteBitmapsList[0] = img1PixelsByte; byteBitmapsList[1] = img2PixelsByte; } #region Main Algorithm int bytesPerPixel = img1Bitmap.Format.BitsPerPixel / 8; int pixelsNumber = arraySize / bytesPerPixel; // liczba wszystkich pikseli threadPixelsStep = pixelsNumber / appSettings.ThreadNumber; // liczba pikseli dla pojedyńczego wątku /** * Jeśli nie można dokonać równego podziału to zostaje stworzonych n - 1 wątków * z regularnym krokiem, gdzie n - liczba wątków zadana przez użytkownika, * natomiast wątek n który wykonuje obliczenia dla pozostałej reszty pikseli. * * W przeciwnym wypadku zostaje utworzonych n regularnych wątków. */ if ( threadPixelsStep * bytesPerPixel * appSettings.ThreadNumber != arraySize) { int delta = pixelsNumber - ( threadPixelsStep * appSettings.ThreadNumber); createThreadList(appSettings.ThreadNumber-1); // utworzenie n-1 wątków int start = threadPixelsStep * (appSettings.ThreadNumber - 1); int[] coords = { start, arraySize / bytesPerPixel }; createNewThread(coords); // utworzenie n-tego wątku obliczającego pozostałe piksele } else { createThreadList(appSettings.ThreadNumber); } Stopwatch clock = new Stopwatch(); clock.Start(); //uruchomienie wszystkich wątków foreach (Thread th in threadList) { th.Start(); } //oczekiwanie na zakończenie obliczeń przez wszystkie wątki foreach (Thread th in threadList) { th.Join(); } clock.Stop(); appSettings.ResultTime = "Czas wykonania " + clock.ElapsedMilliseconds.ToString() + " ms."; #endregion #region Save Result Bitmap if (appSettings.LoadAsmLibrary == true) { copyAsmResultToImg1PixelsByte(); } Int32Rect rect = new Int32Rect(0, 0, maxWidth, maxHeight); img1Bitmap.WritePixels(rect, img1PixelsByte, stride, 0); // zapisanie wyniku obliczeń do bitmapy SaveDialog(img1Bitmap); //zapisanie bitmapy na dysku #endregion }
private void RenderTile() { if (_visual != null) { _visual = null; this.RemoveVisualChild(_visual); this.RemoveLogicalChild(_visual); } _visual = new DrawingVisual(); Width = Source.Width * Scale; Height = Source.Height * Scale; var dc = _visual.RenderOpen(); //BitmapImage test = (BitmapImage)Source; Width = Source.Width * Scale; Height = Source.Height * Scale; WriteableBitmap test = new WriteableBitmap((BitmapSource)Source); //BitmapImage test = (BitmapImage)Source; int w = (int)test.PixelWidth; int h = (int)test.PixelHeight; Int32Rect rect = new Int32Rect(0, 0, w, h); int b = test.Format.BitsPerPixel; Byte[] pixels = new Byte[w * h * b / 8]; int stride = w * b / 8; test.CopyPixels(pixels, stride, 0); double sc = Scale; /*//if (Modified == true) //{ //Drawing DrawObj = new Drawing(); Byte[] output;// = pixels ; //Thread MulThread = new Thread(delegate() //{ output = Drawing.DrawImage(pixels, w, h, b, value); //}); // MulThread.Start(); BitmapSource image = BitmapSource.Create(w, h, 96, 96, test.Format, null, output, stride); /*MemoryStream mStream = new MemoryStream(output); mStream.Seek(0, SeekOrigin.Begin); BitmapImage _bitmap = new BitmapImage(); _bitmap.BeginInit(); _bitmap.StreamSource = mStream; _bitmap.CacheOption = BitmapCacheOption.OnLoad; _bitmap.EndInit(); Source = _bitmap; test.WritePixels(rect, output, stride, 0); //Source = test; //Scale = sc; }*/ dc.DrawImage(Source, new Rect(0, 0, Width, Height)); dc.Close(); CacheMode = new BitmapCache(1 / Scale); // catch (Exception e) // Animate opacity Opacity = 0; BeginAnimation(OpacityProperty, _opacityAnimation); }
public void Webcam_execute() { if (bitmap != null) { using (memory = new MemoryStream()) { bitmap.Save(memory, ImageFormat.Bmp); memory.Position = 0; bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); } } if (bitmapImage != null) { origin = BitmapFactory.ConvertToPbgra32Format(bitmapImage); origin = origin.Resize(68, 42, WriteableBitmapExtensions.Interpolation.NearestNeighbor); origin.CopyPixels(new Int32Rect(0, 0, origin.PixelWidth, origin.PixelHeight), monitor.BackBuffer, monitor.BackBufferStride * monitor.PixelHeight, monitor.BackBufferStride); } }
public void sendData(WriteableBitmap b, bool playerFound, int xStart, int xEnd, int yStart, int yEnd) { if (!clientConnected) { return; } else { //Background has been sent and there is a player //in the image send a message to the client //with the size of the bounding box and the image //Send every sixth frame that we receive if (backgroundSent && playerFound && imageSendCounter%3 == 0) { //Send the client a flag ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = encoder.GetBytes("playerimage"); byte[] readyToReceive = encoder.GetBytes("rcomplete"); clientStream.Write(readyToReceive, 0, readyToReceive.Length); clientStream.Flush(); byte[] completeMessage = new byte[65536]; int k = s.Receive(completeMessage); while (k == 0) { k = s.Receive(completeMessage); } //Get the string from the first 9 bytes since //rcomplete may have been appended to ensure there is no deadlock string tempMessage = encoder.GetString(completeMessage, 0, 9); if (!tempMessage.Equals("rcomplete")) { Console.WriteLine("Message received: " + encoder.GetString(completeMessage, 0, k)); return; } clientImage = b.Resize(320, 240, RewritableBitmap.Interpolation.Bilinear); double tmpXStart = (xStart / 2); double tmpYStart = (yStart / 2); double tmpXEnd = (xEnd / 2); double tmpYEnd = (yEnd / 2); xStart = Convert.ToInt32(Math.Floor(tmpXStart)); xEnd = Convert.ToInt32(Math.Floor(tmpXEnd)); yStart = Convert.ToInt32(Math.Floor(tmpYStart)); yEnd = Convert.ToInt32(Math.Floor(tmpYEnd)); int smallWidth = (xEnd - xStart); int smallHeight = (yEnd - yStart); int imgSize = smallWidth * smallHeight * 4; //Console.WriteLine("Image size: " + imgSize); byte[] transmitPlayerImage = new byte[imgSize]; clientImage.CopyPixels(new Int32Rect(xStart, yStart, smallWidth, smallHeight), transmitPlayerImage, (smallWidth * 4), 0); //b.CopyPixels(new Int32Rect(xStart, yStart, (xEnd - xStart), (yEnd - yStart)), playerImage, ((xEnd - xStart) * 4), 0); //Send the actual size of the bounding box byte[] xS = BitConverter.GetBytes(xStart); byte[] xE = BitConverter.GetBytes(xEnd); byte[] yS = BitConverter.GetBytes(yStart); byte[] yE = BitConverter.GetBytes(yEnd); byte[] playerImageSize = BitConverter.GetBytes(transmitPlayerImage.Length); s.Send(buffer); s.Send(xS); s.Send(xE); s.Send(yS); s.Send(yE); s.Send(playerImageSize); imageSendCounter = 1; s.Send(transmitPlayerImage); //Console.WriteLine("Image sent, size of image: " + transmitPlayerImage.Length + "," + xStart + ", " + xEnd + ", " + yStart + ", " + yEnd); } else if (!backgroundSent) { clientImage = b.Resize(320, 240, RewritableBitmap.Interpolation.Bilinear); byte[] smallBackgroundImage = new byte[TRANSMIT_IMAGE_SIZE]; clientImage.CopyPixels(new Int32Rect(0, 0, 320, 240), smallBackgroundImage, 320 * 4, 0); s.Send(smallBackgroundImage); backgroundSent = true; Console.WriteLine("Background sent"); } else { imageSendCounter++; } } }
private static object PseudoLocalizeObject(object obj) { #if !SILVERLIGHT // "Translate" bitmaps by inverting every pixel var bitmap = obj as Bitmap; if (null != bitmap) { for (var y = 0; y < bitmap.Height; y++) { for (var x = 0; x < bitmap.Width; x++) { var color = bitmap.GetPixel(x, y); var inverseColor = Color.FromArgb(color.A, (byte)~color.R, (byte)~color.G, (byte)~color.B); bitmap.SetPixel(x, y, inverseColor); } } } #endif // "Translate" encoded images by decoding, inverting every pixel, and re-encoding var byteArray = obj as byte[]; if (null != byteArray) { try { using (var stream = new MemoryStream(byteArray)) { var bitmapImage = new BitmapImage(); #if SILVERLIGHT bitmapImage.SetSource(stream); #else bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); #endif var writeableBitmap = new WriteableBitmap(bitmapImage); var width = writeableBitmap.PixelWidth; var height = writeableBitmap.PixelHeight; #if SILVERLIGHT var pixels = writeableBitmap.Pixels; #else var pixels = new int[width * height]; var stride = width * 4; writeableBitmap.CopyPixels(pixels, stride, 0); #endif for (var i = 0; i < pixels.Length; i++) { uint pixel = (uint)pixels[i]; pixels[i] = (int)((~pixel & 0x00ffffff) | (pixel & 0xff000000)); } #if SILVERLIGHT throw new NotSupportedException(); #else writeableBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, stride, 0); var pngBitmapEncoder = new PngBitmapEncoder(); pngBitmapEncoder.Frames.Add(BitmapFrame.Create(writeableBitmap)); using (var memoryStream = new MemoryStream()) { pngBitmapEncoder.Save(memoryStream); obj = memoryStream.GetBuffer(); } #endif } } catch { // byte[] may not have been an encoded image; leave obj alone } } // Return the object return obj; }
private void OpenButton_Click(object sender, RoutedEventArgs e) { var fileDialog = new System.Windows.Forms.OpenFileDialog(); fileDialog.Filter = "Image Files (*.png)|*.png"; fileDialog.FilterIndex = 1; var result = fileDialog.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { BitmapImage originalImage = new BitmapImage(); originalImage.BeginInit(); originalImage.UriSource = new Uri(fileDialog.FileName); PngBitmapDecoder decoder = new PngBitmapDecoder(originalImage.UriSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource = decoder.Frames[0]; WriteableBitmap modifiedImage = new WriteableBitmap(bitmapSource); int stride = bitmapSource.PixelWidth * 4; int size = bitmapSource.PixelHeight * stride; byte[] pixelData = new byte[size]; modifiedImage.CopyPixels(pixelData, stride, 0); drawOriginalHistogram(pixelData); pixelData = equalize(pixelData); drawModifiedHistogram(pixelData); modifiedImage.WritePixels(new Int32Rect(0, 0, bitmapSource.PixelWidth, bitmapSource.PixelHeight), pixelData, stride, 0); ModifiedImage.Source = modifiedImage; originalImage.EndInit(); OriginalImage.Source = originalImage; } }
public static WriteableBitmap ResizeWritableBitmap(this WriteableBitmap wBitmap, int reqWidth, int reqHeight) { int Stride = wBitmap.PixelWidth * ((wBitmap.Format.BitsPerPixel + 7) / 8); int NumPixels = Stride * wBitmap.PixelHeight; ushort[] ArrayOfPixels = new ushort[NumPixels]; wBitmap.CopyPixels(ArrayOfPixels, Stride, 0); int OriWidth = (int)wBitmap.PixelWidth; int OriHeight = (int)wBitmap.PixelHeight; double nXFactor = (double)OriWidth / (double)reqWidth; double nYFactor = (double)OriHeight / (double)reqHeight; double fraction_x, fraction_y, one_minus_x, one_minus_y; int ceil_x, ceil_y, floor_x, floor_y; ushort pix1, pix2, pix3, pix4; int nStride = reqWidth * ((wBitmap.Format.BitsPerPixel + 7) / 8); int nNumPixels = reqWidth * reqHeight; ushort[] newArrayOfPixels = new ushort[nNumPixels]; /*Core Part*/ /* Code project article : * Image Processing for Dummies with C# and GDI+ Part 2 - Convolution Filters By Christian Graus</a> * * href=<a href="http://www.codeproject.com/KB/GDI-plus/csharpfilters.aspx"></a> */ for (int y = 0; y < reqHeight; y++) { for (int x = 0; x < reqWidth; x++) { // Setup floor_x = (int)Math.Floor(x * nXFactor); floor_y = (int)Math.Floor(y * nYFactor); ceil_x = floor_x + 1; if (ceil_x >= OriWidth) { ceil_x = floor_x; } ceil_y = floor_y + 1; if (ceil_y >= OriHeight) { ceil_y = floor_y; } fraction_x = x * nXFactor - floor_x; fraction_y = y * nYFactor - floor_y; one_minus_x = 1.0 - fraction_x; one_minus_y = 1.0 - fraction_y; pix1 = ArrayOfPixels[floor_x + floor_y * OriWidth]; pix2 = ArrayOfPixels[ceil_x + floor_y * OriWidth]; pix3 = ArrayOfPixels[floor_x + ceil_y * OriWidth]; pix4 = ArrayOfPixels[ceil_x + ceil_y * OriWidth]; ushort g1 = (ushort)(one_minus_x * pix1 + fraction_x * pix2); ushort g2 = (ushort)(one_minus_x * pix3 + fraction_x * pix4); ushort g = (ushort)(one_minus_y * (double)(g1) + fraction_y * (double)(g2)); newArrayOfPixels[y * reqWidth + x] = g; } } /*End of Core Part*/ WriteableBitmap newWBitmap = new WriteableBitmap(reqWidth, reqHeight, 96, 96, PixelFormats.Gray16, null); Int32Rect Imagerect = new Int32Rect(0, 0, reqWidth, reqHeight); int newStride = reqWidth * ((PixelFormats.Gray16.BitsPerPixel + 7) / 8); newWBitmap.WritePixels(Imagerect, newArrayOfPixels, newStride, 0); return(newWBitmap); }
private static BitmapSource AlphaBlending(BitmapSource bitmap, byte[] alphaData) { var pixelCount = (uint)(bitmap.Width * bitmap.Height); var bmp = new WriteableBitmap(new FormatConvertedBitmap(bitmap, PixelFormats.Bgra32, null, 0)); var bytes = new byte[pixelCount * 4]; var rect = new Int32Rect(0, 0, (int)bmp.Width, (int)bmp.Height); bmp.CopyPixels(rect, bytes, bmp.BackBufferStride, 0); for (var i = 0; i < alphaData.Length; i++) { bytes[i * 4 + 3] = alphaData[i]; } bmp.WritePixels(rect, bytes, bmp.BackBufferStride, 0); return bmp; }
// Sample -- private void ModifyImage(string method) { WriteableBitmap modifiedImage; try { BitmapSource bitmapSource = new FormatConvertedBitmap(originalImage, PixelFormats.Bgra32, null, 0); modifiedImage = new WriteableBitmap(bitmapSource); } catch (ArgumentNullException) { return; } int height = modifiedImage.PixelHeight; int width = modifiedImage.PixelWidth; int[] pixelData = new int[width*height]; int widthInByte = 4*width; modifiedImage.CopyPixels(pixelData, widthInByte, 0); // ----------- Extern call here -- int[,] pixels; switch (method) { case "D": double gmin = 0; Double.TryParse(GMin.Text, out gmin); double gmax = 255; Double.TryParse(GMax.Text, out gmax); imageProcessing.TresholdD(ref pixelData, (int)gmin, (int)gmax); break; case "E": double fmin = 0; double fmax = 255; Double.TryParse(FMin.Text, out fmin); Double.TryParse(FMax.Text, out fmax); imageProcessing.TresholdE(ref pixelData, (int)fmin, (int)fmax); break; case "MIN": pixels = ArrayConverter.To2D(pixelData, modifiedImage.PixelWidth, modifiedImage.PixelHeight); pixels = imageProcessing.MinFilter(pixels); pixelData = ArrayConverter.ToLinear(pixels); break; case "MAX": pixels = ArrayConverter.To2D(pixelData, modifiedImage.PixelWidth, modifiedImage.PixelHeight); pixels = imageProcessing.MaxFilter(pixels); pixelData = ArrayConverter.ToLinear(pixels); break; case "MINMAX": pixels = ArrayConverter.To2D(pixelData, modifiedImage.PixelWidth, modifiedImage.PixelHeight); pixels = imageProcessing.MinMaxFilter(pixels); pixelData = ArrayConverter.ToLinear(pixels); break; case "BLUR": pixels = ArrayConverter.To2D(pixelData, modifiedImage.PixelWidth, modifiedImage.PixelHeight); pixels = imageProcessing.Blur(pixels); pixelData = ArrayConverter.ToLinear(pixels); break; default: break; } // -------------------------------- modifiedImage.WritePixels(new Int32Rect(0, 0, width, height), pixelData, widthInByte, 0); ModifiedImage.Source = modifiedImage; DrawHistogram(pixelData, "MODIFIED"); }
private static List<bool> ClassifyBitmap( WriteableBitmap bitmap, Image<Gray, byte> cvImage ) { // Let's pick 7 items to classify var classifications = new List<bool> { false, // banana 0 false, // strawberry 1 false, // cookie 2 false, // hotdog 3 false, // broccoli 4 false, // french fries 5 false // egg 6 }; int stride = ( bitmap.PixelWidth*bitmap.Format.BitsPerPixel + 7 )/8; byte[] pixelArray = new byte[bitmap.PixelHeight*stride]; bitmap.CopyPixels( pixelArray, stride, 0 ); int bitmapWidth = bitmap.PixelWidth; int bitmapHeight = bitmap.PixelHeight; // Lets limit the number of "distant" colors we classify var colorDistances = new List<double> { 0, // banana 0 0, // strawberry 1 0, // cookie 2 0, // hotdog 3 0, // broccoli 4 0, // french fries 5 0 // egg 6 }; // Get the color distances Parallel.For( 0, classifications.Count(), i => { colorDistances[i] = GetColorDistance( pixelArray, bitmapWidth, bitmapHeight, stride, ClassificationColorBins.FoodColors[i] ); if ( colorDistances[i] < 50 ) { // Always classify objects with this close a color classifications[i] = ClassifyByTexture( pixelArray ) && ClassifyWithSurf( (FoodType)i, cvImage ); } } ); // If we didn't have enough close color distances, classify some farther ones var closeDistanceCount = colorDistances.Count( x => x < 50 ); if ( closeDistanceCount < 2 ) { colorDistances.ForEach( x => { if ( x < 50 ) { x = double.PositiveInfinity; } }); // Classify the closest color var minValue = colorDistances.Min(); if ( minValue < 105 ) { var indexOfMinValue = colorDistances.IndexOf( minValue ); classifications[indexOfMinValue] = ClassifyByTexture( pixelArray ) && ClassifyWithSurf( (FoodType)indexOfMinValue, cvImage ); } if ( closeDistanceCount == 0 ) { // Classify the second closest color var secondMin = double.PositiveInfinity; foreach ( var colorDistance in colorDistances ) { if ( colorDistance != minValue && colorDistance < secondMin ) { secondMin = colorDistance; } } if ( secondMin < 105 ) { var indexOfSecondValue = colorDistances.IndexOf( secondMin ); classifications[indexOfSecondValue] = ClassifyByTexture( pixelArray ) && ClassifyWithSurf( (FoodType)indexOfSecondValue, cvImage ); } } } for ( int i = 0; i < classifications.Count(); i++ ) { if ( classifications[i] ) { MessageBox.Show( ( (FoodType)i ).ToString() ); } } return classifications; }
// Create rainbow Text Effect in Aquarion EVOL anime public MainWindow() { InitializeComponent(); // Create the outline strategy which is used later on for measuring // the size of text in order to generate a correct sized gradient image var strategyOutline2 = TextDesignerWpf.Canvas.TextOutline(MaskColor.Blue, MaskColor.Blue, 6); WriteableBitmap canvas = TextDesignerWpf.Canvas.GenImage((int)(image1.Width), (int)(image1.Height)); // Text context to store string and font info to be sent as parameter to Canvas methods TextContext context = new TextContext(); // Load a font from its resource, // instead of from system font collection //============================================================= FontFamily fontFamily = new FontFamily(new Uri("pack://application:,,,/resources/"), "./#Ruzicka Freehand LT Std"); context.fontFamily = fontFamily; context.fontStyle = FontStyles.Normal; context.fontWeight = FontWeights.Regular; context.nfontSize = 46; context.pszText = "I cross over the deep blue void"; context.ptDraw = new Point(0, 0); // Generate the mask image for measuring the size of the text image required //============================================================================ WriteableBitmap maskOutline2 = TextDesignerWpf.Canvas.GenMask(strategyOutline2, (int)(image1.Width), (int)(image1.Height), new Point(0, 0), context); uint top = 0; uint bottom = 0; uint left = 0; uint right = 0; TextDesignerWpf.Canvas.MeasureMaskLength(maskOutline2, MaskColor.Blue, ref top, ref left, ref bottom, ref right); bottom += 2; right += 2; // Generate the gradient image //============================= WriteableBitmap bmpGrad = new WriteableBitmap((int)(right - left), (int)(bottom - top), 96.0, 96.0, PixelFormats.Pbgra32, null); List<Color> list = new List<Color>(); list.Add(Color.FromRgb(255, 0, 0)); list.Add(Color.FromRgb(0, 0, 255)); list.Add(Color.FromRgb(0, 255, 0)); DrawGradient.Draw(ref bmpGrad, list, true); // Because Canvas::ApplyImageToMask requires the all images to have equal dimension, // we need to blit our new gradient image onto a larger image to be same size as canvas image //============================================================================================== WriteableBitmap bmpGrad2 = new WriteableBitmap((int)(image1.Width), (int)(image1.Height), 96.0, 96.0, PixelFormats.Pbgra32, null); byte[] pixels = new byte[bmpGrad.PixelHeight * bmpGrad.PixelWidth * bmpGrad.Format.BitsPerPixel / 8]; bmpGrad.CopyPixels(pixels, bmpGrad.BackBufferStride, 0); bmpGrad2.WritePixels(new Int32Rect((int)left, (int)top, (int)(right - left), (int)(bottom - top)), pixels, bmpGrad.BackBufferStride, 0); // Apply the rainbow text against the blue mask onto the canvas TextDesignerWpf.Canvas.ApplyImageToMask(bmpGrad2, maskOutline2, canvas, MaskColor.Blue, false); // Draw the (white body and black outline) text onto the canvas //============================================================== ITextStrategy strategyOutline1 = TextDesignerWpf.Canvas.TextOutline(Color.FromRgb(255, 255, 255), Color.FromRgb(0, 0, 0), 1); TextDesignerWpf.Canvas.DrawTextImage(strategyOutline1, ref canvas, new Point(0, 0), context); // Finally blit the rendered image onto the window by assigning canvas to the image control image1.Source = canvas; }