/// <summary> /// Get borders of meaning part of image /// </summary> /// <param name="angle">Skew angle of image</param> /// <param name="completedWidth">Width to which the image was completed</param> /// /// <param name="resultWidth">Width of result (deskewed) image</param> /// <param name="resultHeight">Height of result (deskewed) image</param> /// <param name="projectedImage">Projected image</param> /// <param name="originalWidth">Width of original image</param> /// <param name="originalHeight">Height of original image</param> /// <returns>Rectangle which bounds meaning part of image</returns> private static Rectangle GetImageBordersWithoutWhiteSpaces(double angle, int completedWidth, int resultWidth, int resultHeight, KrecImage projectedImage, int originalWidth, int originalHeight) { var smallImage = BitmapProcessor.RotateGrayscaleImage(projectedImage, -angle); // Для скорости, границы обрезки ищем на уменьшенном изображении var smallBinary = BitmapProcessor.BinarizeGrayscaleImage(smallImage); var cutBorders = ImagePartitioner.GetImageWithoutBorders(smallBinary); var k = (double)originalWidth / completedWidth; var preComplementWidth = (int)(originalWidth / k); var preComplementHeight = (int)(originalHeight / k); var scaleRect = GetUnprojectedRectangle(cutBorders, projectionSideWidth, projectionSideWidth, preComplementWidth, preComplementHeight, originalWidth, originalHeight, angle); int scaleXError = resultWidth / projectionSideWidth; //Увеличиваем с учетом погрешности int scaleYError = resultHeight / projectionSideWidth; scaleRect.X = Math.Max(scaleRect.X - scaleXError, 0); scaleRect.Y = Math.Max(scaleRect.Y - scaleYError, 0); scaleRect.Width = Math.Min(scaleRect.Width + scaleXError, resultWidth - scaleRect.X); scaleRect.Height = Math.Min(scaleRect.Height + scaleYError, resultHeight - scaleRect.Y); return(scaleRect); }
private bool[,] ProcessImage(Func <bool[, ], bool[, ]> imageDataProcessor, FirmwareImageMetadata imageMetadata, bool rebuildCache = false) { var processedData = imageDataProcessor(ImagePixelGrid.Data); var processedImageSize = processedData.GetSize(); var imageSizeChanged = imageMetadata.Width != processedImageSize.Width || imageMetadata.Height != processedImageSize.Height; imageMetadata.Width = (byte)processedImageSize.Width; imageMetadata.Height = (byte)processedImageSize.Height; m_firmware.WriteImage(processedData, imageMetadata); if (imageSizeChanged || rebuildCache) { ImageCacheManager.RebuildCache(m_firmware); ImageListBox.Invalidate(); } else { var cachedImage = BitmapProcessor.CreateBitmapFromRaw(processedData); ImageCacheManager.SetGlyphImage(imageMetadata.Index, imageMetadata.BlockType, cachedImage); ImageCacheManager.RebuildStringImageCache(m_firmware, imageMetadata.BlockType); var updateCache = new Action(() => { ImageListBox.Invoke(new Action(() => { var itemRect = ImageListBox.GetItemRectangle(imageMetadata.Index - 1); ImageListBox.Invalidate(itemRect); })); }); updateCache.BeginInvoke(null, null); } IsDirty = true; return(processedData); }
/// <summary> /// Convert image to color space of known stain. /// </summary> /// <param name="source">Source image.</param> /// <param name="stain">Known stain.</param> /// <param name="channel">Channel of stain. Takes int 0-2.</param> /// <returns>Color deconvoluted image.</returns> public static Bitmap ColorDeconvolution(Bitmap source, ColorDeconvolution.KnownStain stain, int channel) { using (var image = source.Clone() as Bitmap) { BitmapProcessor bitmapProcessor = new BitmapProcessor(source); ColorDeconvolution colorDeconvolution = new ColorDeconvolution(); GrayscaleProcessor gpDeconvoluted = null; if (channel == 0) { gpDeconvoluted = colorDeconvolution.Get1stStain(bitmapProcessor, stain); } else if (channel == 1) { gpDeconvoluted = colorDeconvolution.Get2ndStain(bitmapProcessor, stain); } else if (channel == 2) { gpDeconvoluted = colorDeconvolution.Get3rdStain(bitmapProcessor, stain); } else { return(null); } Bitmap result = gpDeconvoluted.Bitmap.Clone() as Bitmap; gpDeconvoluted.Dispose(); return(result); } }
/// <summary> /// Image preparing process. Resizing and fixing quality. /// </summary> /// <param name="originalImage">Original image</param> /// <param name="preComplementWidth">Width used when resizing</param> /// <returns>Grayscaled image for descewing</returns> private static KrecImage PrepareImageForDeskewing(KrecImage originalImage, out int preComplementWidth) { if (originalImage.HorizontalResolution > maxDpi) { // TODO: make k be integer to avoid resampling errors double k = maxDpi / originalImage.HorizontalResolution; originalImage = ImageSizesModifier.CompressImageToNewSizes(originalImage, (int)Math.Round(originalImage.Width * k), (int)Math.Round(originalImage.Height * k)); } KrecImage projectionImage; preComplementWidth = Math.Min(projectionSideWidth, originalImage.Width); if (originalImage.Height < maxCompletedSideWith && originalImage.Width < maxCompletedSideWith) //имитирует поведение прошлого сжимателя { int dx = (maxCompletedSideWith - originalImage.Width) / 2; int dy = (maxCompletedSideWith - originalImage.Height) / 2; int newWidth = projectionSideWidth - dx; int newHeight = projectionSideWidth - dy; double k = Math.Max((double)originalImage.Height / newHeight, (double)originalImage.Width / newWidth); var compressedImage = ImageSizesModifier.CompressImageToNewSizes(originalImage, (int)(originalImage.Width / k), (int)(originalImage.Height / k)); compressedImage = BitmapProcessor.AlignImageBackround(compressedImage); preComplementWidth = (int)(originalImage.Width / k); projectionImage = ImageSizesModifier.GetImageWithPowerOf2Side(compressedImage, projectionSideWidth); } else { var alignedImage = BitmapProcessor.AlignImageBackround(originalImage); projectionImage = ImageSizesModifier.GetImageWithPowerOf2Side(alignedImage, projectionSideWidth); } return(projectionImage); }
private Image TakeScreenshot(bool ignoreErrors = false) { try { var data = m_usbConnector.Screenshot(); if (data == null || data.All(x => x == 0x00)) { throw new InvalidOperationException("Invalid screenshot data!"); } return(BitmapProcessor.CreateBitmapFromBytesArray(64, 128, data)); } catch (Exception ex) { if (ignoreErrors) { return(null); } s_logger.Warn(ex); InfoBox.Show ( "An error occurred during taking screenshot..." + "\n\n" + "To continue, please activate or reconnect your device." ); return(null); } }
public static bool IsTissue(Bitmap image) { const double GRENZ_ENTROPIE = 0.5; var bitmapProcessor = new BitmapProcessor(image);//liefert schnelleren Zugriff auf die Pixel-Werte, alternativ auch SharpAccessory.Imaging.Processors.GrayscaleProcessor int[] greyArray = new int[256]; for (var y = 0; y < bitmapProcessor.Height; y++) { for (var x = 0; x < bitmapProcessor.Width; x++) { var r = bitmapProcessor.GetRed(x, y); var g = bitmapProcessor.GetGreen(x, y); var b = bitmapProcessor.GetBlue(x, y); var grauwert = (int)(r + g + b) / 3; greyArray[grauwert]++; } } bitmapProcessor.Dispose(); //Calculate Shannon Entropie return(calcEntropie(greyArray) > GRENZ_ENTROPIE); }
private void CreateMonochromeBitmap() { if (m_originalBitmap == null || m_doNotUpdateMonochrome) { return; } using (var scaledImage = BitmapProcessor.FitToSize(m_originalBitmap, new Size(m_width, m_height))) { if (m_monochromeBitmap != null) { m_monochromeBitmap.Dispose(); m_monochromeBitmap = null; } var mode = (NamedItemContainer <MonochromeConversionMode>)ConversionTypeComboBox.SelectedItem; switch (mode.Data) { case MonochromeConversionMode.ThresholdBased: { m_monochromeBitmap = BitmapProcessor.ConvertTo1Bit(scaledImage, MonochromeConversionMode.ThresholdBased, (int)ThresholdUpDown.Value); break; } case MonochromeConversionMode.FloydSteinbergDithering: { m_monochromeBitmap = BitmapProcessor.ConvertTo1Bit(scaledImage); break; } default: throw new ArgumentOutOfRangeException(); } } }
public Size GetCharSize(char c, Color backgroundColor) { Bitmap bmp = new Bitmap(GetChar(c)); BitmapProcessor.Trim(ref bmp); int minY = bmp.Height; int maxY = 0; for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { Color color = bmp.GetPixel(x, y); if (!BitmapProcessor.ColorsEqual(color, backgroundColor)) { if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } break; } } } int width = bmp.Width; bmp.Dispose(); return(new Size(width, maxY - minY + 1)); }
private void BitmapImportButton_Click(object sender, EventArgs eventArgs) { if (LastSelectedImageMetadata == null) { return; } try { using (var imageConverterWindow = new ImageConverterWindow(true, LastSelectedImageMetadata.Width, LastSelectedImageMetadata.Height)) { if (imageConverterWindow.ShowDialog() != DialogResult.OK) { return; } using (var monochrome = imageConverterWindow.GetConvertedImage()) { var imageData = BitmapProcessor.CreateRawFromBitmap(monochrome); ImagePixelGrid.CreateUndo(); ImagePixelGrid.Data = ImagePreviewPixelGrid.Data = ProcessImage(x => FirmwareImageProcessor.PasteImage(x, imageData), LastSelectedImageMetadata, true); } } } catch (Exception ex) { InfoBox.Show("Unable to import bitmap image.\n" + ex.Message); } }
private void SaveScreenshotButton_Click(object sender, EventArgs e) { if (!ValidateConnectionStatus()) { return; } var screenshot = TakeScreenshot(); if (screenshot == null) { return; } ShowScreenshot(screenshot); using (var export = new Bitmap(ScreenshotContainerPanel.Width, ScreenshotContainerPanel.Height)) { ScreenshotContainerPanel.DrawToBitmap(export, ScreenshotContainerPanel.DisplayRectangle); using (var sf = new SaveFileDialog { FileName = string.Format("{0:yyyy.MM.dd HH.mm.ss}", DateTime.Now), Filter = Consts.PngExportFilter }) { if (sf.ShowDialog() != DialogResult.OK) { return; } using (var export2 = BitmapProcessor.EnlargePixelSize(export, (int)PixelSizeUpDown.Value)) { export2.Save(sf.FileName, ImageFormat.Png); } } } }
private void LogoButton_Click(object sender, EventArgs e) { Bitmap logoBitmap; using (var imageConverterWindow = new ImageConverterWindow(true)) { if (imageConverterWindow.ShowDialog() != DialogResult.OK) { return; } logoBitmap = imageConverterWindow.GetConvertedImage(); if (logoBitmap == null) { return; } } using (logoBitmap) { var imageData = BitmapProcessor.CreateRawFromBitmap(logoBitmap); var block1ImageMetadata = new FirmwareImage1Metadata { Width = LogoWidth, Height = LogoHeight }; var block2ImageMetadata = new FirmwareImage2Metadata { Width = LogoWidth, Height = LogoHeight }; var block1ImageBytes = block1ImageMetadata.Save(imageData); var block2ImageBytes = block2ImageMetadata.Save(imageData); m_worker.RunWorkerAsync(new AsyncProcessWrapper(worker => UpdateLogoAsyncWorker(worker, block1ImageBytes, block2ImageBytes))); } }
protected override void WriteDocument(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; if (File.Exists(FilePath)) { throw new Pdf2KTException("File already exists."); } Document document = null; PdfWriter writer = null; while (Converter.MoveNext()) { if (worker.CancellationPending == true) { e.Cancel = true; break; } BitmapEncoder encoder = BitmapProcessor.GetBitmapEncoder(); BitmapSource processed = BitmapProcessor.Convert(Converter.Current); if (document == null) { document = new Document(new Rectangle(processed.PixelWidth, processed.PixelHeight)); writer = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create)); document.Open(); document.AddTitle(Converter.Document.Title); document.AddAuthor(Converter.Document.Author); document.AddCreationDate(); document.AddCreator("Pdf2KT"); } document.NewPage(); using (MemoryStream ms = new MemoryStream()) { encoder.Frames.Add(BitmapFrame.Create(processed)); encoder.Save(ms); ms.Position = 0; Image pdfpage = Image.GetInstance(ms); pdfpage.SetAbsolutePosition(0, 0); document.Add(pdfpage); } worker.ReportProgress((int)((Converter.CurrentProcessedPageNumber * 1f) / Converter.PageCount * 100)); } document.Close(); }
/// <summary>Повертає зображення символа</summary> /// <param name="c">Символ</param> protected override Bitmap GetChar(char c) { Bitmap bitmap = new Bitmap((int)(fontHeight * 3), _imageHeight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); g.DrawString(c + "", new System.Drawing.Font(family, fontHeight, fontStyle), new SolidBrush(Color.White), 0, 0); BitmapProcessor.BlackAndWhite(ref bitmap, Color.White); BitmapProcessor.Trim(ref bitmap, leave.ContainsKey(c) ? leave[c] : 0); return(bitmap); }
/// <summary> /// Print image with 24bppRgb pixel format /// </summary> /// <param name="image">Image with 24bppRgb pixel format</param> /// <param name="outputPath">Path to print image</param> public static void Print24BppImage(KrecImage image, string outputPath) { var bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb); bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution); bmp.WithBitmapData(bitmapData => { var rgbValues = BitmapProcessor.Reconstruct24To24BppRgbBitmap(bitmapData, image.ImageData); IntPtr ptr = bitmapData.Scan0; Marshal.Copy(rgbValues, 0, ptr, rgbValues.Length); }); bmp.Save(outputPath); }
/// <summary> /// Get angle to right image orientation (Multiples Pi/2, from -Pi/2 to Pi) /// </summary> /// <param name="image">Deskewed mage which nedd to be oriented</param> /// <returns>Angle to right orientation</returns> public static double GetAngleToRightOrientation(KrecImage image) { var binary = BitmapProcessor.BinarizeGrayscaleImage(image); var result90 = Get90AngleToRightOrientation(binary, image.HorizontalResolution, image.VerticalResolution); bool isCorrect90Oriented = result90.Item1; var lines = result90.Item2.Lines; // Not enough information to perform calculations of rotation angle // All lines contains less than one char inside if (lines.All(line => line.Chars.Length <= 1)) { return(0); } if (!isCorrect90Oriented) { binary = RotateMatrixBy90(binary); } CleanUpBinaryFromNoise(binary, result90.Item2.BadChars); var linesSum = GetBluredBoundingRectsSums(lines.Select(line => line.BoundingRect), binary); double orientSum = 0; for (var i = 0; i < linesSum.Count; ++i) { orientSum += GetLineOrientation(lines[i].BoundingRect, binary, linesSum[i], result90.Item2.MaxCharHeight); } double expectation = orientSum / linesSum.Count; bool isCorrect180Oriented = (Math.Abs(expectation) < 0.011) || orientSum >= 0; //при мат. ожидании меньше 0.011 результаты данной оценки недостоверны, а статистически вероятнее всего изображение ориентировано правильно if (!isCorrect180Oriented && !isCorrect90Oriented) { return(-Math.PI / 2); } if (!isCorrect180Oriented) { return(Math.PI); } if (!isCorrect90Oriented) { return(Math.PI / 2); } return(0); }
/// <summary> /// нарисовать подложку - просто закрасить кистью или заблурить (BlurFactor > 0) /// </summary> private void DrawPopupArea(Graphics g, ChartPopup popup) { if (popup.BlurFactor == 0) { g.FillRectangle(popup.BrushArea, popup.Left, popup.Top + ChartPopup.captionWidth, popup.Width, popup.Height); } else { using (var img = BitmapProcessor.CaptureControl(Chart, g)) using (var blured = BitmapProcessor.GetBluredImage(img, new Rectangle(popup.Left, popup.Top + ChartPopup.captionWidth, popup.Width, popup.Height), popup.BlurFactor)) g.DrawImage(blured, popup.Left, popup.Top + ChartPopup.captionWidth); } }
public void TrimBy(char c, int addToTop, int addToBottom) { if (!loaded) { Load(); } Bitmap image = GetChar(c); int top = -1; int bottom = image.Height - 1; for (int y = 0; y < image.Height; y++) { bool free = true; for (int x = 0; x < image.Width; x++) { if (BitmapProcessor.ColorsEqual(image.GetPixel(x, y), Color.Black)) { free = false; break; } } if (free) { if (top == y - 1) { top = y; } } else { bottom = y; } } foreach (CharCollection cc in chars) { foreach (Char ch in cc.chars) { Bitmap bmp = ch.bmp; BitmapProcessor.Copy(ref bmp, new Rectangle(0, Math.Max(top + 1 - addToTop, 0), bmp.Width, Math.Min(bottom - top + addToBottom, bmp.Height - 1))); ch.bmp = bmp; } } }
public static async Task ProcessFrame(Config config, MemoryStream stream, int frame, int width, int height, string outPath) { MemoryStream?resizeMemStream = null; try { stream.Seek(0, SeekOrigin.Begin); var newWidth = (int)Math.Floor(width / config.Model.ReadResolutionReduce); var newHeight = (int)Math.Floor(height / config.Model.ReadResolutionReduce); resizeMemStream = new MemoryStream(newWidth * newHeight * 4); var(zones, zoneTotals) = SetupPixelZones(newWidth, newHeight, config.Model.ZoneRows, config.Model.ZoneColumns); BitmapProcessor.ReadBitmap(stream, width, height, newWidth, newHeight, config.Model.ReadResolutionReduce, config.Model.ZoneRows, config.Model.ZoneColumns, zones, zoneTotals, 4, resizeMemStream); zoneTotals.CalculateAverages(); newWidth = (int)Math.Floor(config.Model.ZoneColumns * config.Model.ResizeScale); newHeight = (int)Math.Floor(config.Model.ZoneRows * config.Model.ResizeScale); var image = new MemoryStream(config.Model.ZoneColumns * config.Model.ZoneRows * 3); var blurImage = new MemoryStream(newWidth * newHeight * 3); (image, blurImage) = BitmapProcessor.PreparePostBitmap(zones, config.Model.ZoneColumns, config.Model.ZoneRows, newWidth, newHeight, config.Model.ResizeFilter, config.Model.ResizeSigma, image, blurImage); await ImageHandler.WriteImageToFile(blurImage, newWidth, newHeight, Path.Combine(outPath, $"out{frame.ToString().PadLeft(6, '0')}.png"), pixelFormat : PixelFormat.Rgb24); await blurImage.DisposeAsync(); await image.DisposeAsync(); foreach (var zone in zones) { zone.Dispose(); } zoneTotals.Dispose(); } catch (Exception ex) { Console.WriteLine(ex); } finally { if (resizeMemStream != null) { await resizeMemStream.DisposeAsync(); } await stream.DisposeAsync(); } }
/// <summary>Задає висоту зображення шрифта</summary> protected virtual void SetImageHeight() { Bitmap d = GetChar('('); BitmapProcessor.Trim(ref d); for (int y = d.Height - 1; y >= 0; y--) { for (int x = 0; x < d.Width; x++) { if (d.GetPixel(x, y).R != 255) { _imageHeight = y + 1; return; } } } }
public void SaveAsImage(string path, ImageFormat imgFormat, int w, int h, bool addChrome) { var width = chart.Width; var height = chart.Height; using (var bmp = new Bitmap(width, height)) { chart.DrawToBitmap(bmp, new Rectangle(0, 0, width, height)); using (var bmpScaled = Scale(bmp, (float)w / width, (float)h / height)) { if (addChrome) { BitmapProcessor.AddChromeEffect(bmpScaled, 180); } bmpScaled.Save(path, imgFormat); } } }
public void RenderBGITest() { Bitmap TestBitmap, TargetBitmap = null; Size TestSize; Rectangle CenterRectangle; TestBitmap = Bitmap.FromFile(@"D:\CSharp\LeonUI\LeonUI\Resources\DefaultButton_0.png") as Bitmap; CenterRectangle = new Rectangle(17, 16, 60, 1); TestSize = TestBitmap.Size; BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 4, TestSize.Height / 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\1.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 2, TestSize.Height / 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\2.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width, TestSize.Height), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\3.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 2, TestSize.Height * 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\4.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 4, TestSize.Height * 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\5.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 4, TestSize.Height / 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\6.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 2, TestSize.Height / 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\7.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 2, TestSize.Height / 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\8.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 4, TestSize.Height / 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\9.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 4, TestSize.Height / 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\10.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 2, TestSize.Height / 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\11.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 2, TestSize.Height / 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\12.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 4, TestSize.Height / 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\13.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 4, TestSize.Height), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\14.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 2, TestSize.Height), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:15.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 2, TestSize.Height), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\16.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 4, TestSize.Height), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\17.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 4, TestSize.Height * 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\18.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 2, TestSize.Height * 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\19.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 2, TestSize.Height * 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\20.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 4, TestSize.Height * 2), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\21.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 4, TestSize.Height * 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\22.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width / 2, TestSize.Height * 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\23.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 2, TestSize.Height * 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\24.PNG", ImageFormat.Png); BitmapProcessor.RenderBGI(TestBitmap, new Size(TestSize.Width * 4, TestSize.Height * 4), CenterRectangle, ref TargetBitmap); TargetBitmap.Save(@"D:\25.PNG", ImageFormat.Png); }
private void BitmapImportButton_Click(object sender, EventArgs eventArgs) { if (LastSelectedImageMetadata == null) { return; } using (var op = new OpenFileDialog { Filter = Consts.BitmapImportFilter }) { if (op.ShowDialog() != DialogResult.OK) { return; } try { var bitmapFile = op.FileName; using (var bitmap = (Bitmap)Image.FromFile(bitmapFile)) { if (bitmap.Width > 2048 || bitmap.Height > 2048) { InfoBox.Show("Selected images is too big. Choose an image that has dimension lower than 2048x2048."); return; } using (var scaledBitmap = BitmapProcessor.ScaleBitmapIfNecessary(bitmap, new Size(LastSelectedImageMetadata.Width, LastSelectedImageMetadata.Height))) using (var monochrome = BitmapProcessor.ConvertTo1Bit(scaledBitmap)) { var imageData = BitmapProcessor.CreateRawFromBitmap(monochrome); ImagePixelGrid.CreateUndo(); ImagePixelGrid.Data = ImagePreviewPixelGrid.Data = ProcessImage(x => FirmwareImageProcessor.PasteImage(x, imageData), LastSelectedImageMetadata, true); } } } catch (Exception ex) { InfoBox.Show("Unable to import bitmap image.\n" + ex.Message); } } }
public IList <Tuple <FirmwareImageMetadata, bool[, ]> > GetImportedData() { var result = new List <Tuple <FirmwareImageMetadata, bool[, ]> >(); using (var surface = DrawSurfaceInRealScale()) { foreach (var letterBox in m_letters) { var metadata = letterBox.Metadata; var rect = letterBox.Rect; var cropRect = new Rectangle(rect.X + 1, rect.Y + 1, rect.Width - 1, rect.Height - 1); using (var croppedLetter = FirmwareImageProcessor.CropImage(surface, cropRect)) { var imageData = BitmapProcessor.CreateRawFromBitmap(croppedLetter, 0x00); result.Add(new Tuple <FirmwareImageMetadata, bool[, ]>(metadata, imageData)); } } } return(result); }
private static void DrawObjectsToImage(Bitmap bitmap, ObjectLayer layer, Color color) { //*** Exception, falls eines der Parameter null ist ********************************************** if (bitmap == null || layer == null || color == null) { throw new NullReferenceException("Parameter ungültig!"); } //*** Exception, falls Bild und Objektebene unterschiedliche Dimension haben ********************* if (bitmap.Width != layer.Map.Width || bitmap.Height != layer.Map.Height) { throw new ArgumentOutOfRangeException("bitmap"); } //*** Bildprozessor anlegen ********************************************************************** using (var processor = new BitmapProcessor(bitmap)) { //*** Über alle Konturpunkte der Objekte iterieren ******************************************* foreach (Point point in layer.Objects.ToArray().SelectMany(imageObject => imageObject.Contour.GetPoints())) { //*** Konturpunkt im Bild auf gegebene Farbe setzen ************************************** processor.SetRed(point.X, point.Y, color.R); processor.SetGreen(point.X, point.Y, color.G); processor.SetBlue(point.X, point.Y, color.B); } } }
/// <summary> /// Print image with 8bppIndexed pixel format (before printing convert it to 24bpp) /// </summary> /// <param name="image">Image with 8bppIndexed pixel format</param> /// <param name="outputPath">Path to print image</param> public static void Print8BppImage(KrecImage image, string outputPath) { var bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb); bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution); int len = image.Width * image.Height * 3; var result = new byte[len]; for (var i = 0; i < len; i += 3) { int ind = i / 3; result[i] = result[i + 1] = result[i + 2] = image.ImageData[ind]; } bmp.WithBitmapData(bitmapData => { var grayscaleValues = BitmapProcessor.Reconstruct24To24BppRgbBitmap(bitmapData, result); IntPtr ptr = bitmapData.Scan0; Marshal.Copy(grayscaleValues, 0, ptr, grayscaleValues.Length); }); bmp.Save(outputPath); }
/// <summary> /// Write the document. /// </summary> /// <param name="sender">The background worker.</param> /// <param name="e">Event args.</param> /// <exception cref="Pdf2KTException">If the directory already exists.</exception> protected override void WriteDocument(object sender, System.ComponentModel.DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; if (Directory.Exists(FilePath)) { throw new Pdf2KTException("Directory already exists."); } Directory.CreateDirectory(FilePath); int pageNum = 1; while (Converter.MoveNext()) { if (worker.CancellationPending == true) { e.Cancel = true; break; } BitmapEncoder encoder = BitmapProcessor.GetBitmapEncoder(); string extension = encoder.CodecInfo.FileExtensions; using (FileStream fs = new FileStream(Path.Combine(FilePath, string.Format("page_{0:0000}{1}", pageNum, extension)), FileMode.Create)) { BitmapSource processed = BitmapProcessor.Convert(Converter.Current); encoder.Frames.Add(BitmapFrame.Create(processed)); encoder.Save(fs); pageNum++; } worker.ReportProgress((int)((Converter.CurrentProcessedPageID * 1f) / Converter.PageCount * 100)); } }
/// <summary> /// Fixing orientiation before returning scew angle /// </summary> /// <param name="originalImage">Original image</param> /// <param name="preparedImage">Prepared for deskewing image</param> /// <param name="angle">Calculated scew angle</param> /// <param name="preComplementWidth">Width used when resizing</param> /// <returns>Fixed descew angle</returns> private static double FixDocumentOrientation(KrecImage originalImage, KrecImage preparedImage, double angle, int preComplementWidth) { var deskewedImage = BitmapProcessor.RotateGrayscaleImage(originalImage, -angle); // TODO: бинаризацию можно сделать в этой точке, а не выполнять ее дважды в // TODO: GetImageBordersWithoutWhiteSpaces и GetAngleToRightOrientation var borders = GetImageBordersWithoutWhiteSpaces(angle, preComplementWidth, deskewedImage.Width, deskewedImage.Height, preparedImage, originalImage.Width, originalImage.Height); var imagePart = deskewedImage.GetSubregion(borders); var orientationResult = OrientationDeterminer.GetAngleToRightOrientation(imagePart); double orientAngle = orientationResult; double result = angle - orientAngle; if (result > Math.PI) { result -= 2 * Math.PI; } else if (result < -Math.PI) { result += 2 * Math.PI; } return(result); }
private void ExportBitmapMenuItem_Click(object sender, EventArgs e) { if (SelectedImageMetadata.Count == 0) { return; } string directoryPath; using (var fb = new FolderBrowserDialog()) { if (fb.ShowDialog() != DialogResult.OK) { return; } directoryPath = fb.SelectedPath; } var exportData = SelectedImageMetadata.Select(x => new { Metadata = x, ImageData = m_firmware.ReadImage(x) }); foreach (var data in exportData) { try { using (var image = BitmapProcessor.Create1BitBitmapFromRaw(data.ImageData)) { var fileName = Path.Combine(directoryPath, "0x" + data.Metadata.Index.ToString("X2") + Consts.BitmapFileExtensionWoAsterisk); image.Save(fileName, ImageFormat.Bmp); } } catch { // Ignore } } }
/// <summary> /// Initialize processor for grayscale image /// </summary> /// <param name="image">Grayscale image</param> public RectanglesProcessor(KrecImage image) : this(BitmapProcessor.BinarizeGrayscaleImage(image), image.VerticalResolution) { }
private void InitializeControls() { var errorIcon = BitmapProcessor.CreateIcon(Resources.exclamation); if (errorIcon != null) { MainErrorProvider.Icon = errorIcon; } MainContainer.SelectedPage = WelcomePage; FirmwareVersionTextBox.ReadOnly = true; FirmwareVersionTextBox.BackColor = Color.White; BuildTextBox.ReadOnly = true; BuildTextBox.BackColor = Color.White; HardwareVersionTextBox.ReadOnly = true; HardwareVersionTextBox.BackColor = Color.White; BootModeTextBox.ReadOnly = true; BootModeTextBox.BackColor = Color.White; TraceTextBox.ReadOnly = true; TraceTextBox.BackColor = Color.White; InititalizeComboBoxes(); TemperatureTypeComboBox.SelectedValueChanged += (s, e) => { var isCelcius = TemperatureTypeComboBox.GetSelectedItem <bool>(); if (isCelcius) { TemperatureUpDown.Minimum = 100; TemperatureUpDown.Maximum = 315; } else { TemperatureUpDown.Minimum = 200; TemperatureUpDown.Maximum = 600; } }; PreheatTypeComboBox.SelectedValueChanged += (s, e) => { var isPercents = PreheatTypeComboBox.GetSelectedItem <bool>(); if (isPercents) { PreheatPowerUpDown.DecimalPlaces = 0; PreheatPowerUpDown.Increment = 1; PreheatPowerUpDown.Minimum = 100; PreheatPowerUpDown.Maximum = 250; } else { PreheatPowerUpDown.DecimalPlaces = 1; PreheatPowerUpDown.Increment = 0.1m; PreheatPowerUpDown.Minimum = 1; PreheatPowerUpDown.Maximum = 75; } }; SelectedModeComboBox.SelectedValueChanged += (s, e) => { var mode = SelectedModeComboBox.GetSelectedItem <VapeMode>(); switch (mode) { case VapeMode.TempNi: SetupModesCheckBoxes(TempNiModeCheckBox); break; case VapeMode.TempTi: SetupModesCheckBoxes(TempTiModeCheckBox); break; case VapeMode.TempSS: SetupModesCheckBoxes(TempSSModeCheckBox); break; case VapeMode.TCR: SetupModesCheckBoxes(TCRModeCheckBox); break; case VapeMode.Power: SetupModesCheckBoxes(PowerModeCheckBox); break; case VapeMode.Bypass: SetupModesCheckBoxes(BypassModeCheckBox); break; case VapeMode.Start: SetupModesCheckBoxes(SmartModeCheckBox); break; default: throw new ArgumentOutOfRangeException(); } SelectedTCRComboBox.SelectedIndex = Math.Min(m_dataflash.ParamsBlock.SelectedTCRIndex, (byte)2); SelectedTCRComboBox.Visible = TCRIndexLabel.Visible = mode == VapeMode.TCR; }; BatteryModelComboBox.SelectedValueChanged += (s, e) => { var batteryModel = BatteryModelComboBox.GetSelectedItem <BatteryModel>(); BatteryEditButton.Visible = batteryModel == BatteryModel.Custom; }; PortComboBox.SelectedIndex = 0; BrightnessTrackBar.ValueChanged += (s, e) => BrightnessPercentLabel.Text = (int)(BrightnessTrackBar.Value * 100m / 255) + @"%"; DownloadButton.Click += DownloadButton_Click; UploadButton.Click += UploadButton_Click; ResetButton.Click += ResetButton_Click; BatteryEditButton.Click += BatteryEditButton_Click; TakeScreenshotButton.Click += TakeScreenshotButton_Click; SaveScreenshotButton.Click += SaveScreenshotButton_Click; BroadcastButton.Click += BroadcastButton_Click; RebootButton.Click += RebootButton_Click; ComConnectButton.Click += ComConnectButton_Click; ComDisconnectButton.Click += ComDisconnectButton_Click; CommandTextBox.KeyDown += CommandTextBox_KeyDown; }
private static void processInput() { int Radius = 2; int NoiseLevel = 10; Console.WriteLine("Processing Input..."); foreach (var import in importItems) { Console.WriteLine(); Console.WriteLine(import.FileName); Console.WriteLine("Slide extrahieren..."); var processingHelper = new Processing(import.FileName); var slide = processingHelper.Slide; Console.WriteLine("Ausschnitt aus Slide extrahieren mit originaler Auflösung..."); int partImageWidth = import.LowerRight.X - import.UpperLeft.X; int partImageHeight = import.LowerRight.Y - import.UpperLeft.Y; Bitmap partImage = slide.GetImagePart( import.UpperLeft.X, import.UpperLeft.Y, partImageWidth, partImageHeight, partImageWidth, partImageHeight ); #region global tissue detection Console.WriteLine("Gewebe suchen und in separatem Layer speichern..."); var bitmapProcessor = new BitmapProcessor(partImage); ObjectLayer overviewLayer = new TissueDetector().Execute(bitmapProcessor, Radius, NoiseLevel); bitmapProcessor.Dispose(); Console.WriteLine("Gewebe-Layer in Ausschnitt zeichnen + speichern..."); DrawObjectsToImage(partImage, overviewLayer, Color.Black); partImage.Save(processingHelper.DataPath + "ImagePartTissue.png"); #endregion global tissue detection #region Deconvolution Console.WriteLine("Execute deconvolution 3..."); var gpX = new ColorDeconvolution().Get3rdStain(partImage, ColorDeconvolution.KnownStain.HaematoxylinEosin); gpX.Dispose(); Bitmap gpX_bmp = gpX.Bitmap; gpX_bmp.Save(processingHelper.DataPath + "ImagePartColor3.png"); Console.WriteLine("Execute deconvolution 2..."); var gpE = new ColorDeconvolution().Get2ndStain(partImage, ColorDeconvolution.KnownStain.HaematoxylinEosin); gpE.Dispose(); Bitmap gpE_bmp = gpE.Bitmap; gpE_bmp.Save(processingHelper.DataPath + "ImagePartColor2.png"); Console.WriteLine("Execute deconvolution 1..."); var gpH = new ColorDeconvolution().Get1stStain(partImage, ColorDeconvolution.KnownStain.HaematoxylinEosin); gpH.Dispose(); Bitmap gpH_bmp = gpH.Bitmap; gpH_bmp.Save(processingHelper.DataPath + "ImagePartColor1.png"); #endregion Deconvolution #region execute edge detection Console.WriteLine("Execute edge detection..."); SobelResponse responseH = Filtering.ExecuteSobel(gpH_bmp); SobelResponse responseE = Filtering.ExecuteSobel(gpE_bmp); var substracted = new double[responseH.Size.Width, responseH.Size.Height]; var substractedRange = new Range<double>(); for (var x = 0; x < responseH.Size.Width; x++) { for (var y = 0; y < responseH.Size.Height; y++) { var value = Math.Max(0, responseE.Gradient[x, y] - responseH.Gradient[x, y]); substracted[x, y] = value; substractedRange.Add(value); } } double[,] nonMaximumSupression = Filtering.ExecuteNonMaximumSupression(substracted, responseE.Orientation); Bitmap edges = Visualization.Visualize(nonMaximumSupression, Visualization.CreateColorizing(substractedRange.Maximum)); edges.Save(processingHelper.DataPath + "ImagePartEdges.png"); #endregion execute edge detection exportItems.Add( new Ausgabe { Identify = import.Identify, Result = false, Message = "kein Fehler" } ); } }
static void Main(string[] args) { #region init if (0 == args.Length) { Console.WriteLine("no slide name"); return; } var slideName = args[0]; var processinHelper = new Processing(slideName); var slide = processinHelper.Slide; #endregion init var part = new WsiPartitioner(new Rectangle(new Point(0, 0), slide.Size), new Size(1000, 1000), new Size(0, 0), 1.0); var tissueData = new TiledProcessInformation<bool>(part, slideName); #region global tissue detection int overviewImageWidth = slide.Size.Width / OverviewTileSize; int overviewImageHeight = slide.Size.Height / OverviewTileSize; Bitmap overviewImage = slide.GetImagePart(0, 0, slide.Size.Width, slide.Size.Height, overviewImageWidth, overviewImageHeight); var bitmapProcessor = new BitmapProcessor(overviewImage); ObjectLayer overviewLayer = new TissueDetector().Execute(bitmapProcessor, Radius, NoiseLevel); bitmapProcessor.Dispose(); DrawObjectsToImage(overviewImage, overviewLayer, Color.Black); overviewImage.Save(processinHelper.DataPath + "tissueDetectionOverview.png"); #endregion global tissue detection //part.Tiles[] foreach (var tile in part) { #region global tissue detection var rect = tile.SourceRect; int overviewX = rect.X / OverviewTileSize; int overviewY = rect.Y / OverviewTileSize; int windowSize = rect.Width / OverviewTileSize; bool tileInObject = true; int partsOutside = 0; for (int y = 0; y < windowSize; y++) { for (int x = 0; x < windowSize; x++) { int newX = overviewX + x; int newY = overviewY + y; if (newX < 0 || newX >= overviewLayer.Map.Width || newY < 0 || newY >= overviewLayer.Map.Height) { continue; } uint id = overviewLayer.Map[newX, newY]; if (id != 0) continue; partsOutside++; if (!(partsOutside >= Math.Pow(windowSize + 1, 2) * 0.75)) continue; tileInObject = false; break; } if (!tileInObject) { break; } } tissueData.AddDataToCurrentTile(tileInObject); #endregion global tissue detection if (tileInObject) Console.WriteLine(tile.SourceRect + ":" + partsOutside); } tissueData.ToFile(processinHelper.DataPath + "tissueData.tpi"); using (Bitmap b = tissueData.GenerateHeatMap(tissue => tissue ? Color.Green : Color.Red)) b.Save(processinHelper.DataPath + "tissueData.png"); Console.WriteLine("done"); Console.ReadKey(); }
private void SelectSourceButton_Click(object sender, EventArgs e) { string fileName; using (var op = new OpenFileDialog { Filter = Consts.BitmapImportFilter }) { if (op.ShowDialog() != DialogResult.OK) { return; } fileName = op.FileName; } try { if (m_originalBitmap != null) { m_originalBitmap.Dispose(); } m_originalBitmap = BitmapProcessor.LoadBitmapFromFile(fileName); if (m_originalBitmap.Width > 2048 || m_originalBitmap.Height > 2048) { if (m_monochromeBitmap != null) { m_monochromeBitmap.Dispose(); m_monochromeBitmap = null; } SourceTextBox.Clear(); ResizeContainerPanel.Enabled = false; ConversionContainerPanel.Enabled = false; m_doNotUpdateMonochrome = true; NewWidthUpDown.Value = m_width = (int)NewWidthUpDown.Minimum; NewHeightUpDown.Value = m_height = (int)NewHeightUpDown.Minimum; m_doNotUpdateMonochrome = false; ImagePreviewSurface.Invalidate(); OkButton.Enabled = false; InfoBox.Show("Selected images is too big. Choose an image that has dimension lower than 2048x2048."); } else { SourceTextBox.Text = fileName; ConversionContainerPanel.Enabled = true; if (m_importMode) { NewWidthUpDown.Value = m_width = m_desireWidth; NewHeightUpDown.Value = m_height = m_desireHeight; } else { ResizeContainerPanel.Enabled = true; m_doNotUpdateMonochrome = true; NewWidthUpDown.Value = m_width = m_originalBitmap.Width; NewHeightUpDown.Value = m_height = m_originalBitmap.Height; m_doNotUpdateMonochrome = false; } CreateMonochromeBitmap(); ImagePreviewSurface.Invalidate(); OkButton.Enabled = true; } } catch (Exception ex) { InfoBox.Show("An error occured during opening image file!\n" + ex.Message); } }