/// <summary> /// Преобразование изображения в цвета Ч/Б /// </summary> /// <param name="img">source</param> /// <returns></returns> public static Bitmap ConvertToBlackWhite(this Bitmap img) { // создаём BitmapSource из изображения, переданного в параметре Bitmap input = new Bitmap(img); // создаём BitmapSource для черно-белого изображения Bitmap output = new Bitmap(input.Width, input.Height); // перебираем в циклах все пиксели исходного изображения for (int j = 0; j < input.Height; j++) { for (int i = 0; i < input.Width; i++) { // получаем (i, j) пиксель UInt32 oldPixel = (UInt32)(input.GetPixel(i, j).ToArgb()); // получаем компоненты цветов пикселя float R = (float)((oldPixel & 0x00FF0000) >> 16); // красный float G = (float)((oldPixel & 0x0000FF00) >> 8); // зеленый float B = (float)(oldPixel & 0x000000FF); // синий // делаем цвет черно-белым (оттенки серого) - находим среднее арифметическое R = G = B = (R + G + B) / 3.0f; // собираем новый пиксель по частям (по каналам) UInt32 newPixel = 0xFF000000 | ((UInt32)R << 16) | ((UInt32)G << 8) | ((UInt32)B); // добавляем его в BitmapSource нового изображения var pixel = System.Drawing.Color.FromArgb((int)newPixel); pixel = PixelConvert.Invert(pixel); output.SetPixel(i, j, pixel); } } // выводим черно-белый BitmapSource в pictureBox2 return(output); }
/// <summary> /// Инвертирует изображение в цвета изображение из БД MNIST (в ч/б) /// </summary> /// <param name="image"></param> /// <returns></returns> public static BitmapSource ConvertToColorMnist(this BitmapSource image) { var img = image.GetBitmap(); Bitmap output = new Bitmap(img.Width, img.Height); for (int j = 0; j < img.Height; j++) { for (int i = 0; i < img.Width; i++) { // получаем (i, j) пиксель var pixel = img.GetPixel(i, j); output.SetPixel(i, j, PixelConvert.Invert(pixel)); } } return(output.BitmapToBitmapSource()); }