public void InsertInUnDoRedoForCrop(BitmapImage bitmap, StorageFile beforeCropFile, StorageFile afterCropFile, PaintObjectTemplatedControl paintControl, ObservableCollection <StoredImage> imageCollection) { ICommand cmd = new CropCommand(bitmap, beforeCropFile, afterCropFile, paintControl, imageCollection); _Undocommands.Push(cmd); _Redocommands.Clear(); }
private void InitCommands() { OpenCommand = new OpenCommand(this); ApplyCommand = new ApplyCommand(this); FlipCommand = new FlipCommand(this); HistogramEqualizeCommand = new HistogramEqualizeCommand(this); HistogramStretchCommand = new HistogramStretchCommand(this); CropCommand = new CropCommand(this); InpaintCommand = new InpaintCommand(this); ResizeCommand = new ResizeCommand(this); RotateCommand = new RotateCommand(this); SaveAsCommand = new SaveAsCommand(this); SaveCommand = new SaveCommand(this); ZoomCommand = new ZoomCommand(this); ResetCommand = new ResetCommand(this); CloseCommand = new CloseCommand(this); SelectToolCommand = new SelectToolCommand(this); UndoCommand = new UndoCommand(this); RedoCommand = new RedoCommand(this); DropboxCommand = new DropboxCommand(this); DownloadCommand = new DownloadCommand(this); UploadCommand = new UploadCommand(this); DCommand = new DCommand(this); ECommand = new ECommand(this); PrewittCommand = new PrewittCommand(this); }
public CropDialog(CropCommand Cropcommand, RasterImage CropImage) { InitializeComponent(); _CropCommand = Cropcommand; _CropImage = CropImage; InitializeUI(); }
static void Main(string[] args) { String fileToConvert = @"FILE PATH HERE"; RasterSupport.SetLicense(@"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC", System.IO.File.ReadAllText(@"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC.KEY")); using (RasterCodecs codecs = new RasterCodecs()) { using (IOcrEngine ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false)) { ocrEngine.Startup(null, null, null, @"C:\LEADTOOLS 20\Bin\Common\OcrLEADRuntime"); using (IOcrPage ocrPage = ocrEngine.CreatePage(ocrEngine.RasterCodecsInstance.Load(fileToConvert, 1), OcrImageSharingMode.AutoDispose)) { ocrPage.AutoZone(null); ocrPage.Recognize(null); string recognizedCharacters = ocrPage.GetText(-1); BarcodeEngine engine = new BarcodeEngine(); int resolution = 300; using (RasterImage image = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.White))) { BarcodeWriter writer = engine.Writer; QRBarcodeData data = BarcodeData.CreateDefaultBarcodeData(BarcodeSymbology.QR) as QRBarcodeData; data.Bounds = new LeadRect(0, 0, image.ImageWidth, image.ImageHeight); QRBarcodeWriteOptions writeOptions = writer.GetDefaultOptions(data.Symbology) as QRBarcodeWriteOptions; writeOptions.XModule = 30; writeOptions.HorizontalAlignment = BarcodeAlignment.Near; writeOptions.VerticalAlignment = BarcodeAlignment.Near; data.Value = recognizedCharacters; writer.CalculateBarcodeDataBounds(new LeadRect(0, 0, image.ImageWidth, image.ImageHeight), image.XResolution, image.YResolution, data, writeOptions); Console.WriteLine("{0} by {1} pixels", data.Bounds.Width, data.Bounds.Height); writer.WriteBarcode(image, data, writeOptions); CropCommand cmd = new CropCommand(new LeadRect(0, 0, data.Bounds.Width, data.Bounds.Height)); cmd.Run(image); codecs.Save(image, "QR.tif", RasterImageFormat.CcittGroup4, 1); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var process = new Process(); process.StartInfo = new ProcessStartInfo("QR.tif") { UseShellExecute = true }; process.Start(); } Console.WriteLine(); } } } } }
public CropDialog() { InitializeComponent(); _CropCommand = new CropCommand(); //Set command default values InitializeUI(); }
private static RasterImage CreateTextFooter(LeadSize size, string tag) { var bpp = 24; var byteOrder = RasterByteOrder.Bgr; var viewPerspective = RasterViewPerspective.TopLeft; var image = new RasterImage(RasterMemoryFlags.Conventional, size.Width, size.Height, bpp, byteOrder, viewPerspective, null, null, 0); var fill = new FillCommand(RasterColor.FromKnownColor(RasterKnownColor.White)); fill.Run(image); using (var graphics = RasterImagePainter.CreateGraphics(image)) { using (var brush = new SolidBrush(Color.Black)) { using (var font = new Font(FontFamily.GenericSansSerif, size.Width / 128)) { var pos = new PointF(0, 0); { SizeF stringSize = new SizeF(); stringSize = graphics.Graphics.MeasureString(tag, font); float scaleX = (float)size.Width / stringSize.Width; float scaleY = (float)size.Height / stringSize.Height; scaleX = Math.Min(1f, scaleX); scaleY = Math.Min(1f, scaleY); graphics.Graphics.ScaleTransform(scaleX, scaleY); if (size.Height > (int)stringSize.Height) { size.Height = (int)stringSize.Height; } } graphics.Graphics.DrawString(tag, font, Brushes.Black, new PointF(0, 0)); } } } if (size.Height < image.Height) { var crop = new CropCommand(LeadRect.FromLTRB(0, 0, size.Width, size.Height)); crop.Run(image); } return(image); }
private static RasterImage GetCroppedImage(RasterImage input, LeadRect boundaries) { boundaries.Inflate(INFLATE, INFLATE); RasterImage target = null; try { target = input.Clone(); CropCommand cc = new CropCommand(); cc.Rectangle = boundaries; cc.Run(target); } catch (Exception) { return(null); } return(target); }
private static void Transform(Transform transformProperties, RasterImage result) { var cropCommand = new CropCommand(); var rotateCommand = new RotateCommand { Angle = (int)(transformProperties.Rotation * 100) }; var rectCrop = new LeadRect( (int)transformProperties.Bounds.Left, (int)transformProperties.Bounds.Top, (int)transformProperties.Bounds.Width, (int)transformProperties.Bounds.Height); cropCommand.Rectangle = rectCrop; rotateCommand.Run(result); if (!transformProperties.Bounds.IsEmpty) { cropCommand.Run(result); } }
/// <summary> /// Returns "Crop to custom selection" composite command. /// </summary> /// <param name="path">Custom selection path.</param> /// <param name="pathBounds">Selection path bounds.</param> /// <param name="crop">Crop command.</param> /// <returns>Crop command for custom selection.</returns> ProcessingCommandBase GetCropToPathCommand( GraphicsPath path, RectangleF pathBounds, CropCommand crop) { Rectangle viewerImageRect = new Rectangle(0, 0, _viewer.Image.Width, _viewer.Image.Height); crop.RegionOfInterest = new RegionOfInterest(GetBoundingRect(RectangleF.Intersect(pathBounds, viewerImageRect))); // overlay command _overlayImage = crop.Execute(_viewer.Image); OverlayCommand overlay = new OverlayCommand(_overlayImage); // overlay with path command ProcessPathCommand overlayWithPath = new ProcessPathCommand(overlay, path); // clear image command ClearImageCommand clearImage = new ClearImageCommand(Color.Transparent); // create composite command: clear, overlay with path, crop return(new CompositeCommand(clearImage, overlayWithPath, crop)); }
private static void Transform(Transform transformProperties, RasterImage result) { var cropCommand = new CropCommand(); var rotateCommand = new RotateCommand { Angle = (int)(transformProperties.Rotation * 100) }; var rectCrop = new LeadRect( (int)transformProperties.Bounds.Left, (int)transformProperties.Bounds.Top, (int)transformProperties.Bounds.Width, (int)transformProperties.Bounds.Height); cropCommand.Rectangle = rectCrop; rotateCommand.Run(result); if (!transformProperties.Bounds.IsEmpty) { cropCommand.Run(result); } }
public List <FilledForm> ProcessOcr(ResultsForPrettyJson formResults, List <ImageInfo> fileInfos) { try { var outDir = formResults.OriginalDirectoryName; var retForms = new List <FilledForm>(); var usedMasters = new HashSet <MasterForm>(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); formResults.PagesInPdf = fileInfos.Count; foreach (var ofi in fileInfos) { FilledForm newForm = new FilledForm(); retForms.Add(newForm); newForm.ImageInfoMaster.InitialImage = ofi; newForm.Name = Path.GetFileNameWithoutExtension(ofi.ImageFileInfo.Name); if (ofi.Image == null) { ofi.Image = LoadImageFile(ofi.ImageFileInfo.FullName, 1, -1); } //CleanupImage(ofi.Image); var par = new FormThreadCallParams() { ImageInfo = ofi, StopWatch = stopWatch, Form = newForm }; if (PageTimeoutInSeconds < 50) { Thread t = new Thread(this.PrepareNewFormThreader); t.Start(par); if (!t.Join(TimeSpan.FromSeconds(PageTimeoutInSeconds))) { t.Abort(); formResults.TimedOutPages.Add(newForm.Name); formResults.BestFormConfidence.Add(-1); if (formResults.TimedOutPages.Count > 2 && formResults.PagesMappedToForm == 0) { formResults.Status = $"Form abandoned for timeout after {formResults.BestFormConfidence.Count} pages"; logger.Error(formResults.Status); return(retForms); } continue; } } else { PrepareNewFormThreader(par); } Debug.Assert(par.Attributes != null); var filledFormAttributes = par.Attributes; //List<FormRecognitionResult> results = new List<FormRecognitionResult>(); MasterForm currentMasterBlockForm = null; int bestConfidence = -1; int currentConfidence = 85; foreach (var master in BlockMasterForms) { if (usedMasters.Contains(master)) { continue; } var result = RecognitionEngine.CompareForm(master.Attributes, filledFormAttributes, null, null); //logger.Debug($"Check {master} for {newForm} {stopWatch.ElapsedMilliseconds} {result.Confidence}"); if (result.Confidence > currentConfidence) { currentMasterBlockForm = master; bestConfidence = currentConfidence = result.Confidence; } else if (result.Confidence > bestConfidence) { bestConfidence = result.Confidence; } } formResults.BestFormConfidence.Add(bestConfidence); if (currentMasterBlockForm != null) { formResults.MasterFormPages.Add(currentMasterBlockForm.Properties.Name); formResults.PagesMappedToForm++; logger.Info($"FilledForm matched {newForm.Name} {newForm.Status} {stopWatch.ElapsedMilliseconds} "); newForm.ImageInfoMaster.InitialImage = ofi; var centeredImage = ofi.Image.CloneAll(); CleanupImage(centeredImage); newForm.ImageInfoMaster.CenteredImage = new ImageInfo() { Image = centeredImage }; var omrImage = centeredImage.CloneAll(); PrepareOmrImage(omrImage); newForm.ImageInfoMaster.OmrImage = new ImageInfo() { Image = omrImage }; newForm.Status = "Matched"; newForm.Master = currentMasterBlockForm; var alignment = RecognitionEngine.GetFormAlignment(newForm.Master.Attributes, newForm.Attributes, null); var fields = currentMasterBlockForm.ProcessingPages[0]; var scaler = currentMasterBlockForm.Resolution; var fieldsOnlyImage = RasterImage.Create(centeredImage.Width, centeredImage.Height, centeredImage.BitsPerPixel, 300, RasterColor.White); //fieldsOnlyImage = new RasterImage(RasterMemoryFlags.Conventional, centeredImage.Width, centeredImage.Height, centeredInage.BitsPerPixel, RasterByteOrder.Rgb, RasterViewPerspective.TopLeft, null, null, 0); var subDirField = Path.Combine(outDir, "fields"); var fileNameFieldOnly = Path.Combine(subDirField, newForm.Name + "_fields.jpg"); var googleResultsFile = Path.Combine(subDirField, newForm.Name + "_google.json"); var combined = false; foreach (var field in fields) { var isBlock = field.Name.Contains("block"); var rect200 = alignment[0].AlignRectangle(field.Bounds); scaler = 300; int fudge = isBlock ? 30 : 1; var rect300 = new LeadRect(rect200.Left * 300 / scaler - fudge, rect200.Top * 300 / scaler - fudge, rect200.Width * 300 / scaler + fudge, rect200.Height * 300 / scaler + fudge); try { var imageInfoToUse = newForm.ImageInfoMaster.CenteredImage; var zoneType = OcrZoneType.Text; if (field.GetType() == typeof(OmrFormField)) { imageInfoToUse = newForm.ImageInfoMaster.OmrImage; zoneType = OcrZoneType.Omr; } else if (field.GetType() == typeof(ImageFormField)) { zoneType = OcrZoneType.Graphic; } var image = imageInfoToUse.Image.CloneAll(); var subDir = Path.Combine(outDir, isBlock ? "blocks" : "fields"); var fileName = Path.Combine(subDir, newForm.Name + "_" + field.Name + ".jpg"); var imageField = new ImageField { Field = field, FieldResult = { FieldName = field.Name, IsBlock = isBlock, ImageFile = fileName, Bounds = rect300.ToString(), FieldType = zoneType.ToString(), Error = "None" } }; imageField.Rectangle = new Rectangle(rect300.X, rect300.Y, rect300.Width, rect300.Height); try { EnsurePathExists(subDir); CropCommand command = new CropCommand { Rectangle = rect300 }; command.Run(image); RasterCodecs.Save(image, fileName, RasterImageFormat.Jpeg, bitsPerPixel: 8); if (!isBlock && zoneType == OcrZoneType.Text && !combined) { try { ; var combiner = new CombineCommand(); //combiner.DestinationImage = fieldsOnlyImage; combiner.SourceImage = image.Clone(); combiner.DestinationRectangle = rect300; var regionBounds = image.GetRegionBounds(null); combiner.SourcePoint = new LeadPoint(regionBounds.X, regionBounds.Y); //combiner.Flags = CombineCommandFlags.OperationAdd | CombineCommandFlags.Destination0 | CombineCommandFlags.Source1 | CombineCommandFlags.Destination0 ; combiner.Flags = CombineCommandFlags.OperationOr | CombineCommandFlags.Destination0;; // |CombineFastCommandFlags.OperationAverage; combiner.Run(fieldsOnlyImage); //combined = true; } catch (Exception exCombine) { logger.Error(exCombine, $"error combining field {field.Name} {rect300}"); } } var imageInfo = new ImageInfo() { Image = image, ImageFileInfo = new FileInfo(fileName) }; imageField.ImageInfo = imageInfo; if (!isBlock && zoneType != OcrZoneType.Graphic) { using (IOcrPage ocrPage = OcrEngine.CreatePage(image, OcrImageSharingMode.AutoDispose)) { OcrZone ocrZone = new OcrZone { ZoneType = zoneType, Bounds = new LeadRect(fudge, fudge, image.ImageSize.Width - fudge, image.ImageSize.Height - fudge) }; ocrPage.Zones.Add(ocrZone); ocrPage.Recognize(null); if (zoneType == OcrZoneType.Omr) { if (field.Name.Contains("C2NGVD1929")) { logger.Info(ocrZone.Bounds); } GetOmrReading(ocrPage, field, imageField); } else if (zoneType == OcrZoneType.Text) { var resultsPage = GetPageConfidence(ocrPage); imageField.FieldResult.Confidence = resultsPage.Confidence; char[] crlf = { '\r', '\n' }; imageField.FieldResult.Text = ocrPage.GetText(0).TrimEnd(crlf); } } } logger.Info( $"field {field.Name} {rect300} [{imageField.FieldResult.Text}] confidence: {imageField.FieldResult.Confidence}"); } catch (Exception exField) { logger.Error(exField, $"Error processing {field.Name}"); formResults.FieldsWithError++; imageField.FieldResult.Error = exField.Message; } newForm.ImageFields.Add(imageField); formResults.OcrFields.Add(imageField.FieldResult); formResults.Status = "FormMatched"; } catch (Exception ex) { logger.Error(ex, $"Error on field {field.Name} {rect300}"); newForm.Status = $"Error|Field {field.Name} {rect300}: [{ex.Message}]"; } } RasterCodecs.Save(PrepareOmrImage(fieldsOnlyImage), fileNameFieldOnly, RasterImageFormat.Jpeg, bitsPerPixel: 8); var googleResults = GoogleOcr(fileNameFieldOnly); if (googleResults.Count > 0) { var json = JsonConvert.SerializeObject(googleResults, Formatting.Indented); File.WriteAllText(googleResultsFile, json); MergeGoogleOcr(newForm, googleResults); } usedMasters.Add(currentMasterBlockForm); } else { newForm.Status = "Unmatched|No MasterForm match"; } logger.Info($"FilledForm processed {newForm.Name} {newForm.Status} {stopWatch.ElapsedMilliseconds} "); if (usedMasters.Count == BlockMasterForms.Count) { logger.Info("found all master forms"); break; } } stopWatch.Stop(); return(retForms); } catch (Exception ex) { logger.Error(ex, "Untrapped error found"); return(null); } }
private void Crop() { bool blnBestFit = false; int intBestFitWidth = 0; int intBestFitHeight = 0; int intCropLeft = 0; int intCropRight = 0; int intCropTop = 0; int intCropBottom = 0; int intCropping = 0; #region load properties from action profile xml try { blnBestFit = Convert.ToBoolean(xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='crop']/bestFit").InnerText.Trim()); intBestFitWidth = Convert.ToInt32(xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='crop']/bestFitWidth").InnerText.Trim()); intBestFitHeight = Convert.ToInt32(xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='crop']/bestFitHeight").InnerText.Trim()); intCropLeft = Convert.ToInt32(xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='crop']/left").InnerText.Trim()); intCropRight = Convert.ToInt32(xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='crop']/right").InnerText.Trim()); intCropTop = Convert.ToInt32(xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='crop']/top").InnerText.Trim()); intCropBottom = Convert.ToInt32(xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='crop']/bottom").InnerText.Trim()); } catch { } #endregion load properties from action profile xml CropCommand cmd = new CropCommand(); SizeCommand cmd1 = new SizeCommand(); cmd1.Flags = Leadtools.RasterSizeFlags.Resample; if (intSetCropWidth > 0 && intSetCropHeight > 0) { // do a crop based on the input parameters intSetCropLeft = Convert.ToInt32((float)intSetCropLeft * flVisualCropFactor); intSetCropTop = Convert.ToInt32((float)intSetCropTop * flVisualCropFactor); intSetCropWidth = Convert.ToInt32((float)intSetCropWidth * flVisualCropFactor); intSetCropHeight = Convert.ToInt32((float)intSetCropHeight * flVisualCropFactor); cmd.Rectangle = new Rectangle(intSetCropLeft, intSetCropTop, intSetCropWidth - intSetCropLeft, intSetCropHeight - intSetCropTop); } else if (blnBestFit) { // first size the image to the closer region and then crop the rest float flFactor = (float)img.Width / (float)img.Height; int intWidthDiff = intBestFitWidth - img.Width; int intCalcWidthDiff = intWidthDiff; if (intCalcWidthDiff < 0) { intCalcWidthDiff = intCalcWidthDiff * -1; } int intHeightDiff = intBestFitHeight - img.Height; int intCalcHeightDiff = intHeightDiff; if (intCalcHeightDiff < 0) { intCalcHeightDiff = intCalcHeightDiff * -1; } if (intCalcHeightDiff < intCalcWidthDiff) { // crop width intCropping = (intBestFitWidth - img.Width) / 2; if (intCropping < 0) { intCropping = intCropping * -1; } cmd.Rectangle = new Rectangle(intCropping, 0, intBestFitWidth, img.Height); } else { // crop height intCropping = (intBestFitHeight - img.Height) / 2; if (intCropping < 0) { intCropping = intCropping * -1; } cmd.Rectangle = new Rectangle(0, intCropping, img.Width, intBestFitHeight); } } else { // do a crop based on the config parameters cmd.Rectangle = new Rectangle(intCropLeft, intCropTop, img.Width - intCropLeft - intCropRight, img.Height - intCropTop - intCropBottom); } if (imageInfo.TotalPages > 0 && imageInfo.Format == Leadtools.RasterImageFormat.Gif) // #1.0.4.0 { rasterCodecs.Options.Gif.Save.AnimationWidth = cmd.Rectangle.Height; rasterCodecs.Options.Gif.Save.AnimationHeight = cmd.Rectangle.Width; for (int i = 1; i <= img.PageCount; i++) { img.Page = i; cmd.Run(img); } } else { cmd.Run(img); } }
private void _btnOK_Click(object sender, EventArgs e) { if (radioResize.Checked) { if (_txtWidth.Value < 32) { if (_width > 32) { MessageBox.Show("Width is too small, Must be at least 32"); return; } } if (_txtHeight.Value < 32) { if (_height > 32) { MessageBox.Show("Height is too small, Must be at least 32"); return; } } int i; SizeCommand sizeCommand = new SizeCommand(_txtWidth.Value, _txtHeight.Value, RasterSizeFlags.Resample); GrayscaleCommand grayCommand = new GrayscaleCommand(8); int oldWidth = _image.Width; int oldHeight = _image.Height; for (i = 1; i <= _image.PageCount; i++) { _image.Page = i; grayCommand.Run(_image); sizeCommand.Run(_image); } _object.VoxelSpacing = new Medical3DPoint(_object.VoxelSpacing.X * oldWidth / _txtWidth.Value, _object.VoxelSpacing.Y * oldHeight / _txtHeight.Value, _object.VoxelSpacing.Z); } else { if (Math.Abs(_txtCropWidthTo.Value - _txtCropWidthFrom.Value) < 32) { if (_width > 32) { MessageBox.Show("Width is too small, Must be at least 32"); return; } } if (_txtHeight.Value < 32) { if (_height > 32) { MessageBox.Show("Height is too small, Must be at least 32"); return; } } if (Math.Abs(_txtCropHeightTo.Value - _txtCropHeightFrom.Value) < 32) { MessageBox.Show("Height is too small, Must be at least 32"); return; } int i; CropCommand cropCommand = new CropCommand(new Rectangle(_txtCropWidthFrom.Value, _txtCropHeightFrom.Value, _txtCropWidthTo.Value - _txtCropWidthFrom.Value, _txtCropHeightTo.Value - _txtCropHeightFrom.Value)); GrayscaleCommand grayCommand = new GrayscaleCommand(8); for (i = 1; i <= _image.PageCount; i++) { _image.Page = i; grayCommand.Run(_image); cropCommand.Run(_image); } _object.FirstPosition = new Medical3DPoint(_object.FirstPosition.X + _object.ImageOrientation[0] * _txtCropWidthFrom.Value + _object.ImageOrientation[3] * _txtCropHeightFrom.Value, _object.FirstPosition.Y + _object.ImageOrientation[1] * _txtCropWidthFrom.Value + _object.ImageOrientation[4] * _txtCropHeightFrom.Value, _object.FirstPosition.Z + _object.ImageOrientation[2] * _txtCropWidthFrom.Value + _object.ImageOrientation[5] * _txtCropHeightFrom.Value); _object.SecondPosition = new Medical3DPoint(_object.SecondPosition.X + _object.ImageOrientation[0] * _txtCropWidthFrom.Value + _object.ImageOrientation[3] * _txtCropHeightFrom.Value, _object.SecondPosition.Y + _object.ImageOrientation[1] * _txtCropWidthFrom.Value + _object.ImageOrientation[4] * _txtCropHeightFrom.Value, _object.SecondPosition.Z + _object.ImageOrientation[2] * _txtCropWidthFrom.Value + _object.ImageOrientation[5] * _txtCropHeightFrom.Value); } this.DialogResult = DialogResult.OK; this.Close(); }