예제 #1
0
 private void _btnReset_Click(object sender, EventArgs e)
 {
     _viewer.Image     = _orgImage.Clone();
     _applied          = false;
     _btnApply.Enabled = true;
     _btnReset.Enabled = false;
 }
예제 #2
0
 private void _btnReset_Click(object sender, EventArgs e)
 {
     if (!_firstPointSelected && _polyPoints.Count == 4)
     {
         _firstPointSelected = true;
         _viewer.Image       = _orgImage.Clone();
         _btnApply.Enabled   = true;
         _btnReset.Enabled   = false;
     }
 }
예제 #3
0
 void _viewer_MouseDown(object sender, MouseEventArgs e)
 {
     if (e.Button == MouseButtons.Left)
     {
         _drawing = true;
         _segIndex++;
         _viewer.Image = _orgImage.Clone();
         _viewer.Invalidate();
     }
 }
예제 #4
0
        private IOcrPage DoublePass(RasterImage image)
        {
            //first pass with default settings
            IOcrPage page = _ocrEngine.CreatePage(image.Clone(), OcrImageSharingMode.AutoDispose);

            page.Recognize(null);

            //second pass with mobile image processing set to true
            _ocrEngine.SettingManager.SetBooleanValue("Recognition.Preprocess.MobileImagePreprocess", true);
            IOcrPage mobilePage = _ocrEngine.CreatePage(image.Clone(), OcrImageSharingMode.AutoDispose);

            mobilePage.Recognize(null);

            //get the confidence of both pages
            PageResults firstPassResults  = GetPageConfidence(page);
            PageResults secondPassResults = GetPageConfidence(mobilePage);

            double confidenceDif = firstPassResults.Confidence - secondPassResults.Confidence;

            IOcrPage    highestConfidence;
            PageResults pageResultsHighest;

            if (confidenceDif > 2)
            {
                highestConfidence  = page;
                pageResultsHighest = firstPassResults;
            }
            else
            {
                highestConfidence  = mobilePage;
                pageResultsHighest = secondPassResults;
            }

            if (pageResultsHighest.TotalWords < 20)
            {
                IOcrPage thirdPass = highestConfidence.Copy();
                thirdPass.Unrecognize();
                OcrZone singleZone = new OcrZone()
                {
                    Bounds = new LeadRect(0, 0, image.Width, image.Height)
                };
                thirdPass.Zones.Add(singleZone);
                thirdPass.Recognize(null);
                PageResults thirdResults        = GetPageConfidence(thirdPass);
                double      confidencetDifThird = thirdResults.Confidence - pageResultsHighest.Confidence;
                if (confidenceDif > 5)
                {
                    highestConfidence  = thirdPass;
                    pageResultsHighest = thirdResults;
                }
            }

            return(highestConfidence);
        }
예제 #5
0
 void _viewer_MouseDown(object sender, MouseEventArgs e)
 {
     if (e.Button == MouseButtons.Left)
     {
         _drawing = true;
         _segIndex++;
         LeadPoint point = _viewer.ScrollOffset;
         _viewer.Image = _orgImage.Clone();
         _viewer.ScrollBy(point);
         _viewer.Invalidate();
     }
 }
        private void ApplyFilter()
        {
            RasterImage runImage = _originalBitmap.Clone();

            try
            {
                MultiscaleEnhancementCommandType type = MultiscaleEnhancementCommandType.Gaussian;
                switch (_cbFilter.SelectedIndex)
                {
                case 0:
                    type = MultiscaleEnhancementCommandType.Normal;
                    break;

                case 1:
                    type = MultiscaleEnhancementCommandType.Resample;
                    break;

                case 2:
                    type = MultiscaleEnhancementCommandType.Bicubic;
                    break;

                case 3:
                    type = MultiscaleEnhancementCommandType.Gaussian;
                    break;
                }
                MultiscaleEnhancementCommandFlags flags = MultiscaleEnhancementCommandFlags.None;
                if (_cbEdge.Checked)
                {
                    flags |= MultiscaleEnhancementCommandFlags.EdgeEnhancement;
                }
                if (_cbLatitude.Checked)
                {
                    flags |= MultiscaleEnhancementCommandFlags.LatitudeReduction;
                }

                MultiscaleEnhancementCommand command = new MultiscaleEnhancementCommand(
                    Convert.ToInt32(_numContrast.Value * 100),
                    (_cbEdgeLevel.Checked) ? Convert.ToInt32(_numEdgeLevel.Value) : -1,
                    (_cbEdgeCoef.Checked) ? Convert.ToInt32(_numEdgeCoef.Value * 100) : -1,
                    (_cbLatLevel.Checked) ? Convert.ToInt32(_numLatLevel.Value) : -1,
                    (_cbLatCoef.Checked) ? Convert.ToInt32(_numLatCoef.Value * 100) : -1,
                    type,
                    flags);

                command.Run(runImage);

                _viewer.Image = runImage;
            }
            catch (System.Exception ex)
            {
                Messager.ShowError(this, ex);
            }
        }
예제 #7
0
        private async void GalleryButton_Tapped(object sender, EventArgs e)
        {
            bool canClickButton = true;

            try
            {
                // Prevent fast clicking
                await Device.InvokeOnMainThreadAsync(() => GalleryButton.IsEnabled = false);

                // Try to load an image
                using (Stream stream = await DependencyService.Get <IPicturePicker>().GetImageStreamAsync())
                {
                    if (stream != null)
                    {
                        using (RasterImage image = await RasterImageLoader.RasterImageFromStream(stream))
                        {
                            OnPageClosing(image.Clone());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error", $"Unable to load image: {ex.Message}", "OK");
            }
            finally
            {
                // Allow the user to click again
                if (canClickButton)
                {
                    await Device.InvokeOnMainThreadAsync(() => GalleryButton.IsEnabled = true);
                }
            }
        }
예제 #8
0
        protected override void Run()
        {
            IsLoadingError = false;
            Progress(101, "Generating...");

            Progress(101, "Creating components...");

            int step = 100 / loadedImage.PageCount;

            step = step > 0 ? step : 1;
            int ticker = 0;

            for (int i = 0; i < loadedImage.PageCount; i++)
            {
                loadedImage.Page = i + 1;
                ticker          += step;
                Progress(ticker, string.Format("Adding page {0}...", loadedImage.Page));
                try
                {
                    Page pg = templateForm.Pages.AddPage(loadedImage.Clone());

                    IsLoadingError = IsLoadingError || pg == null;
                }
                catch (System.Exception)
                {
                    IsLoadingError = true;
                    continue;
                }
            }


            base.Run();
        }
예제 #9
0
        private void LoadImage(object data)
        {
            DicomDataSet ds    = data as DicomDataSet;
            int          count = 0;
            RasterImage  image = null;

            if (Dataset == null)
            {
                Cell.Image = null;
                return;
            }

            count = ds.GetImageCount(null);
            SetLoadProgress(count > 0, count);
            for (int i = 0; i < count; i++)
            {
                RasterImage img = ds.GetImage(null, i, 0, RasterByteOrder.Rgb | RasterByteOrder.Gray, DicomGetImageFlags.AutoApplyVoiLut | DicomGetImageFlags.AutoScaleModalityLut);

                if (image == null)
                {
                    image = img.Clone();
                }
                else
                {
                    image.AddPage(img);
                }
                SetProgressValue(i + 1);
                Thread.Sleep(0);
            }

            SetCellImage(image);
        }
예제 #10
0
        public static RasterImage OptimizeImageForBarcode(this RasterImage image)
        {
            var clone = image.Clone();

            new AutoColorLevelCommand().Run(clone);
            return(clone);
        }
예제 #11
0
 // Add an item to the undo list
 private void AddUndoItem(RasterImage image)
 {
     if (image != null)
     {
         _undo.Add(image.Clone()); // add a copy of the image
     }
 }
예제 #12
0
        public static RasterImage Tranform(this RasterImage originalImage, Transform transformProperties)
        {
            var image = originalImage.Clone();

            Transform(transformProperties, image);

            return(image);
        }
예제 #13
0
        private void _btnRetry_Click(object sender, EventArgs e)
        {
            RasterImage image = this.rasterImageViewer1.Image;

            if (image != null)
            {
                ProcessImage(image.Clone());
            }
        }
예제 #14
0
        private void cboxValues_SelectedIndexChanged(object sender, EventArgs e)
        {
            OmrBubbleLabel label = (OmrBubbleLabel)cboxValues.SelectedItem;

            txtValue.Text = label.Value;
            if (!label.Bounds.IsEmpty)
            {
                imageViewer.Image = fieldImage.Clone(label.Bounds);
            }
        }
예제 #15
0
        public void SetDocument(PDFDocument document)
        {
            _rasterImageList.BeginUpdate();
            _bookmarksTreeView.BeginUpdate();
            _signaturesTreeView.BeginUpdate();

            _rasterImageList.Items.Clear();
            _bookmarksTreeView.Nodes.Clear();
            _signaturesTreeView.Nodes.Clear();

            // This is the image we will load till the thumbnails are loaded
            using (Bitmap loadingThumbnailBitmap = global::PDFDocumentDemo.Properties.Resources.LoadingThumbnail)
            {
                using (RasterImage itemImage = RasterImageConverter.ConvertFromImage(loadingThumbnailBitmap, ConvertFromImageOptions.None))
                {
                    if (document != null && document.Pages.Count >= 1)
                    {
                        for (int page = 1; page <= document.Pages.Count; page++)
                        {
                            // We need to clone itemImage since the image list has AutoDisposeImages set to true
                            ImageViewerItem item = new ImageViewerItem();
                            item.Image      = itemImage.Clone();
                            item.PageNumber = page;
                            item.Text       = "Page " + page.ToString();
                            _rasterImageList.Items.Add(item);
                        }
                    }
                }
            }

            // Add the bookmarks (if any)
            if (document != null && document.Bookmarks != null)
            {
                AddBookmarks(document.Bookmarks);
            }
            // Add the signatures (if any)
            if (document != null)
            {
                AddSignatures(document);
            }

            _rasterImageList.EndUpdate();
            _bookmarksTreeView.EndUpdate();
            _signaturesTreeView.EndUpdate();


            if (document != null && document.Pages.Count >= 1)
            {
                // Start reading the thumbnails
                _generateThumbnailsWorker.Start(document, _rasterImageList.GetItemImageSize(_rasterImageList.ActiveItem, true).Width, _rasterImageList.GetItemImageSize(_rasterImageList.ActiveItem, true).Height);
            }

            UpdateUIState();
        }
        private void RunCommand()
        {
            _command.Contrast   = _contrastTrackBar.Value * 10;
            _command.Brightness = _brightnessTrackBar.Value * 10;
            _command.Intensity  = _intensityTrackBar.Value * 10;

            _contrastValueLabel.Text   = _command.Contrast.ToString();
            _brightnessValueLabel.Text = _command.Brightness.ToString();
            _intensityValueLabel.Text  = _command.Intensity.ToString();

            _viewer.Image = _originalImage.Clone();
            _command.Run(_viewer.Image);
        }
예제 #17
0
        private void InitClass(RasterImage image, ConversionColorFormat srcFormat)
        {
            _viewer           = new ImageViewer();
            _viewer.BackColor = Color.DarkGray;
            _viewer.ViewHorizontalAlignment = ControlAlignment.Near;
            _viewer.Dock = DockStyle.Fill;
            _pnlViewer.Controls.Add(_viewer);
            _viewer.BringToFront();
            _viewer.Zoom(ControlSizeMode.Fit, 1, _viewer.DefaultZoomOrigin);

            _cbFit.Checked = _viewer.SizeMode == ControlSizeMode.Fit;

            // Start up the Color conversion toolkit.
            RasterColorConverterEngine.Startup();
            RasterImage tempImage = image.Clone();

            if (tempImage.ViewPerspective != RasterViewPerspective.TopLeft)
            {
                tempImage.ChangeViewPerspective(RasterViewPerspective.TopLeft);
            }

            _width        = tempImage.Width;
            _height       = tempImage.Height;
            _bytesPerLine = tempImage.BytesPerLine;

            _orgBuffer = new byte[_bytesPerLine * _height];

            tempImage.Access();

            for (int y = 0; y < _height - 1; y++)
            {
                tempImage.GetRow(y, _orgBuffer, (y * _width * 3), _width * 3);
            }

            _viewer.Image = tempImage;

            tempImage.Release();

            _srcFormat = srcFormat;

            foreach (ConvertItem i in _convertItems)
            {
                _cbColorFormat.Items.Add(i);
                if (i.Format == ConversionColorFormat.Yuv)
                {
                    _cbColorFormat.SelectedItem = i;
                }
            }

            UpdateMyControls();
        }
        public override byte[] GetImageData(AnnContainer container, LeadRectD bounds)
        {
            if (_image == null)
            {
                return(null);
            }

            using (var image = _image.Clone(bounds.ToLeadRect()))
            {
                using (var codecs = new RasterCodecs())
                {
                    using (var ms = new MemoryStream())
                    {
                        codecs.Save(image, ms, RasterImageFormat.Png, Image.BitsPerPixel);

                        return(ms.ToArray());
                    }
                }
            }
        }
예제 #19
0
        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);
        }
        public ContrastBrightnessIntensityDialog(ImageViewer viewer)
        {
            InitializeComponent();

            _contrastValueLabel.Text   = _contrastTrackBar.Value.ToString();
            _brightnessValueLabel.Text = _brightnessTrackBar.Value.ToString();
            _intensityValueLabel.Text  = _intensityTrackBar.Value.ToString();

            _viewer = viewer;

            // Make a copy of the image in viewer and save it
            _originalImage = _viewer.Image;

            // Set a copy in the viewer, this is the image we will change here
            _saveAutoDisposeImages    = _viewer.AutoDisposeImages;
            _viewer.AutoDisposeImages = false;
            _viewer.Image             = _originalImage.Clone();
            _viewer.AutoDisposeImages = true;

            RunCommand();
        }
예제 #21
0
        private void FillImageList(RasterImage image)
        {
            using (RasterCodecs codecs = new RasterCodecs())
            {
                ImageListControl.Items.Clear();

                for (int index = 1; index <= image.PageCount; index++)
                {
                    image.Page = index;
                    // Create the item of the image list
                    ImageViewerItem item = new ImageViewerItem();
                    item.Size  = LeadSize.Create(120, 120);
                    item.Text  = "Page: " + (index - 1).ToString();
                    item.Image = image.Clone();
                    item.Tag   = index;

                    // Add the item to the image list
                    ImageListControl.Items.Add(item);
                }

                ImageListControl.Items[0].IsSelected = true;
                _viewer.Image = ImageListControl.Items[0].Image;
            }
        }
예제 #22
0
        public override byte[] GetImageData(AnnContainer container, LeadRectD bounds)
        {
            if (_image == null)
            {
                return(null);
            }

            LeadRect rect = bounds.ToLeadRect();

            rect = _image.RectangleToImage(RasterViewPerspective.TopLeft, rect);

            using (var image = _image.Clone(rect))
            {
                using (var codecs = new RasterCodecs())
                {
                    using (var ms = new MemoryStream())
                    {
                        codecs.Save(image, ms, RasterImageFormat.Png, Image.BitsPerPixel);

                        return(ms.ToArray());
                    }
                }
            }
        }
예제 #23
0
        private void UpdateData()
        {
            var recognitionEngineVersion = FormRecognitionEngine.Version;

#if FOR_DOTNET4
            var originalFullTextSearchManager = recognitionEngine.FullTextSearchManager;
#endif

            try
            {
                if (!Directory.Exists(_txtSrcFolder.Text))
                {
                    Invoke((MethodInvoker) delegate { Messager.Show(this, "Please select valid folder", MessageBoxIcon.Error, MessageBoxButtons.OK); });
                    return;
                }

                // Set the data version to latest, we want to update the data to use the latest
                FormRecognitionEngine.Version = FormRecognitionEngine.LatestVersion;

                // Set the full text search engine
                DiskMasterFormsRepository workingRepository = new DiskMasterFormsRepository(_codecs, _txtSrcFolder.Text);

#if FOR_DOTNET4
                if (_cbUseFullTextSearch.Checked)
                {
                    DiskFullTextSearchManager fullTextSearchManager = new DiskFullTextSearchManager();
                    fullTextSearchManager.IndexDirectory    = Path.Combine(workingRepository.Path, "index");
                    recognitionEngine.FullTextSearchManager = fullTextSearchManager;
                }
#endif
                IMasterFormsCategory parentCategory = workingRepository.RootCategory;
                Invoke((MethodInvoker) delegate { _prgbar.Maximum = parentCategory.MasterForms.Count; });

                for (int i = 0; i < _prgbar.Maximum; i++)
                {
                    if (!_isRunning)
                    {
                        return;
                    }

                    Invoke((MethodInvoker) delegate { _prgbar.Value++; });

                    //Get the Original Attributes
                    DiskMasterForm            originalMasterForm = parentCategory.MasterForms[i] as DiskMasterForm;
                    FormRecognitionAttributes originalAttributes = originalMasterForm.ReadAttributes();
                    recognitionEngine.OpenMasterForm(originalAttributes);
                    recognitionEngine.CloseMasterForm(originalAttributes);

                    FormRecognitionOptions    options    = new FormRecognitionOptions();
                    FormRecognitionAttributes attributes = recognitionEngine.CreateMasterForm(parentCategory.MasterForms[i].Name, new Guid(), options);
                    recognitionEngine.CloseMasterForm(attributes);

                    IMasterForm newForm = parentCategory.AddMasterForm(attributes, null, (RasterImage)null);

                    DiskMasterForm currentMasterForm = parentCategory.MasterForms[i] as DiskMasterForm;
                    attributes = currentMasterForm.ReadAttributes();
                    FormPages   formPages = currentMasterForm.ReadFields();
                    RasterImage formImage = currentMasterForm.ReadForm();

                    for (int j = 0; j < formImage.PageCount; j++)
                    {
                        //Get the Page Recognition Options for the original Attributes
                        PageRecognitionOptions pageOptions = GetPageOptions(j, originalAttributes);

                        //Add each new page to the masterform by creating attributes for each page
                        formImage.Page = j + 1;
                        recognitionEngine.OpenMasterForm(attributes);
                        recognitionEngine.DeleteMasterFormPage(attributes, j + 1);
                        recognitionEngine.InsertMasterFormPage(j + 1, attributes, formImage.Clone(), pageOptions, null);
#if FOR_DOTNET4
                        if (_cbUseFullTextSearch.Checked)
                        {
                            recognitionEngine.UpsertMasterFormToFullTextSearch(attributes, "index", null, null, null, null);
                        }
#endif

                        recognitionEngine.CloseMasterForm(attributes);
                    }

                    FormProcessingEngine tempProcessingEngine = new FormProcessingEngine();
                    tempProcessingEngine.OcrEngine     = ocrEngine;
                    tempProcessingEngine.BarcodeEngine = barcodeEngine;

                    for (int j = 0; j < recognitionEngine.GetFormProperties(attributes).Pages; j++)
                    {
                        tempProcessingEngine.Pages.Add(new FormPage(j + 1, formImage.XResolution, formImage.YResolution));
                    }

                    formPages = tempProcessingEngine.Pages;
                    currentMasterForm.WriteAttributes(attributes);

                    currentMasterForm.WriteFields(parentCategory.MasterForms[i].ReadFields());
                }
#if FOR_DOTNET4
                if (recognitionEngine.FullTextSearchManager != null)
                {
                    recognitionEngine.FullTextSearchManager.Index();
                }
#endif
                System.Diagnostics.Process.Start(_txtSrcFolder.Text);
            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker) delegate { Messager.Show(this, ex, MessageBoxIcon.Error); });
            }
            finally
            {
                // Restore the original version
                FormRecognitionEngine.Version = recognitionEngineVersion;
#if FOR_DOTNET4
                recognitionEngine.FullTextSearchManager = originalFullTextSearchManager;
#endif
                _isRunning = false;
                Invoke((MethodInvoker) delegate
                {
                    _prgbar.Value = 0;
                    UpdateControls();
                });
            }
        }
예제 #24
0
        private void AddMasterFormPages(RasterImage imagesToAdd, DiskMasterForm currentform, string folderName)
        {
            try
            {
                DiskMasterForm            currentMasterForm = currentform;
                FormRecognitionAttributes attributes        = currentMasterForm.ReadAttributes();
                FormPages   formPages = currentMasterForm.ReadFields();
                RasterImage formImage = currentMasterForm.ReadForm();

                for (int i = 0; i < imagesToAdd.PageCount; i++)
                {
                    //Add each new page to the masterform by creating attributes for each page
                    imagesToAdd.Page = i + 1;
                    AddPageToMasterForm(imagesToAdd.Clone(), attributes, -1, null);
                }

                //Add image
                if (formImage != null)
                {
                    formImage.AddPages(imagesToAdd.CloneAll(), 1, imagesToAdd.PageCount);
                }
                else
                {
                    formImage = imagesToAdd.CloneAll();
                }

                //Only add processing pages for the new pages
                if (formPages != null)
                {
                    for (int i = 0; i < imagesToAdd.PageCount; i++)
                    {
                        formPages.Add(new FormPage(formPages.Count + 1, imagesToAdd.XResolution, imagesToAdd.YResolution));
                    }
                }
                else
                {
                    //No processing pages exist so we must create them
                    FormRecognitionEngine recognitionEngine    = SetupRecognitionEngine();
                    FormProcessingEngine  tempProcessingEngine = new FormProcessingEngine();
                    tempProcessingEngine.OcrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false);
                    //tempProcessingEngine.BarcodeEngine = barcodeEngine;

                    for (int i = 0; i < recognitionEngine.GetFormProperties(attributes).Pages; i++)
                    {
                        tempProcessingEngine.Pages.Add(new FormPage(i + 1, imagesToAdd.XResolution, imagesToAdd.YResolution));
                    }

                    formPages = tempProcessingEngine.Pages;
                }

                //FormField newField = null;
                //AnnHiliteObject newObject = new AnnHiliteObject();
                //newField = new TextFormField();
                //newField.Name = "test";
                //newField.Bounds = new LogicalRectangle(50, 50, 50, 50, LogicalUnit.Pixel);

                //FormField newField1 = null;
                //AnnHiliteObject newObject1 = new AnnHiliteObject();
                //newField1 = new OmrFormField();
                //newField1.Name = "test1";
                //newField1.Bounds = new LogicalRectangle(50, 50, 50, 50, LogicalUnit.Pixel);

                //newObject.Tag = newField;
                //newObject1.Tag = newField1;
                //FormField currentField = newObject.Tag as FormField;
                //FormField currentField1 = newObject1.Tag as FormField;

                //formPages[0].Add(currentField);
                //formPages[0].Add(currentField1);

                currentMasterForm.WriteForm(formImage);
                currentMasterForm.WriteAttributes(attributes);
                currentMasterForm.WriteFields(formPages);
                DBHelper.UpdateTifPageCount(formImage.PageCount.ToString(), folderName);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #25
0
        private void _miFileSaveAllPagesAsTIFF_Click(object sender, System.EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();

            saveDlg.FileName        = _fileName.Remove(_fileName.Length - 4, 4);
            saveDlg.OverwritePrompt = true;

            string formatString = _quality;

            formatString = (formatString.Trim()).Substring(1, formatString.Length - 3);

            saveDlg.FileName += "_M_" + formatString + ".tif";
            saveDlg.Title     = "Save All Pages (TIFF LEAD ABC Format)";
            saveDlg.Filter    = "TIFF LEAD ABC Format (*.tif)|*.tif";

            using (WaitCursor wait = new WaitCursor())
            {
                try
                {
                    if (saveDlg.ShowDialog() == DialogResult.OK)
                    {
                        if (File.Exists(saveDlg.FileName))
                        {
                            File.Delete(saveDlg.FileName);
                        }

                        int            index;
                        CombineCommand cmd      = new CombineCommand();
                        int            loopStep = (_miQualityCombineTwoImages.Checked) ? 2 : 1;

                        RasterImage fullImage = _codecs.Load(_fileName, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);
                        if (fullImage.HasRegion)
                        {
                            fullImage.MakeRegionEmpty();
                        }

                        StopSaving = false;

                        for (index = 1; index <= fullImage.PageCount && !StopSaving; index += loopStep)
                        {
                            _sbMainStatus.Text = string.Format("Saving page {0}/{1}. Press Esc to cancel.", index, fullImage.PageCount);

                            fullImage.Page = index;
                            int newWidth  = fullImage.Width;
                            int newHeight = fullImage.Height;

                            if (index + 1 > fullImage.PageCount || !_miQualityCombineTwoImages.Checked)
                            {
                                RasterImage newImage = fullImage.Clone();
                                _codecs.Save(newImage, saveDlg.FileName, RasterImageFormat.TifAbc, 1, 1, 1, 1, CodecsSavePageMode.Append);
                            }
                            else
                            {
                                fullImage.Page = index + 1;
                                newWidth       = Math.Max(newWidth, fullImage.Width);
                                newHeight     += fullImage.Height;
                                RasterImage newImage = new RasterImage(RasterMemoryFlags.Conventional, newWidth, newHeight, 24, RasterByteOrder.Bgr, RasterViewPerspective.TopLeft, null, IntPtr.Zero, 0);

                                fullImage.Page = index;

                                cmd.SourceImage          = fullImage;
                                cmd.DestinationRectangle = new LeadRect(0, 0, fullImage.Width, fullImage.Height);
                                cmd.Run(newImage);

                                fullImage.Page = index + 1;

                                cmd.SourceImage          = fullImage;
                                cmd.DestinationRectangle = new LeadRect(0, newHeight - fullImage.Height, fullImage.Width, fullImage.Height);
                                cmd.Run(newImage);

                                _codecs.Save(newImage, saveDlg.FileName, RasterImageFormat.TifAbc, 1, 1, 1, 1, CodecsSavePageMode.Append);
                            }
                            Application.DoEvents();
                        }
                        fullImage.Page = 1;
                    }
                }
                catch (Exception ex)
                {
                    Messager.ShowFileSaveError(this, saveDlg.FileName, ex);
                }
                _sbMainStatus.Text = "";
            }
        }
예제 #26
0
        private void LoadImage(object data)
        {
            DicomDataSet ds    = data as DicomDataSet;
            int          count = 0;
            RasterImage  image = null;

            if (Dataset == null)
            {
                Cell.Image = null;
                return;
            }

            bool         isStructuredDisplay = IsStructuredDisplay(ds);
            DicomElement pixelData           = ds.FindFirstElement(null, DicomTag.PixelData, true);

            if (pixelData == null)
            {
                if (isStructuredDisplay)
                {
                    count = 1;
                }
            }
            else
            {
                count = ds.GetImageCount(pixelData);
            }

            SetLoadProgress(count > 0, count);
            string exceptionMessage = string.Empty;

            for (int i = 0; i < count; i++)
            {
                RasterImage img = null;

                try
                {
                    if (pixelData != null)
                    {
                        img = ds.GetImage(pixelData, i, 0, RasterByteOrder.Rgb | RasterByteOrder.Gray, DicomGetImageFlags.AutoApplyModalityLut | DicomGetImageFlags.AutoApplyVoiLut | DicomGetImageFlags.AutoScaleModalityLut | DicomGetImageFlags.AutoScaleVoiLut | DicomGetImageFlags.AutoDetectInvalidRleCompression);
                    }
                    else if (isStructuredDisplay)
                    {
                        StructuredDisplayImageOptions sdOptions = new StructuredDisplayImageOptions();
                        sdOptions.ShowOverlay = _optionsAgent.Get <bool>("ExportLayoutIncludeMetadata", true);
                        DicomGetImageFlags getImageFlags = DicomGetImageFlags.AutoScaleModalityLut | DicomGetImageFlags.AutoScaleVoiLut | DicomGetImageFlags.AutoApplyModalityLut | DicomGetImageFlags.AutoApplyVoiLut;
                        img = ds.GetStructuredDisplayImage(GetSopInstanceCallBack, getImageFlags, sdOptions);;
                    }
                }
                catch (Exception ex)
                {
                    exceptionMessage = ex.Message;
                }

                if (img != null)
                {
                    if (image == null)
                    {
                        image = img.Clone();
                    }
                    else
                    {
                        image.AddPage(img);
                    }
                }
                SetProgressValue(i + 1);
                Thread.Sleep(0);
            }

            string photometricInterpretation = GetDicomTag(ds, DicomTag.PhotometricInterpretation);

            if (!string.IsNullOrEmpty(photometricInterpretation))
            {
                Cell.PhotometricInterpretation = photometricInterpretation;
            }

            SetCellInfo(image,
                        ds.GetValue <string>(DicomTag.PatientID, string.Empty),
                        ds.GetValue <string>(DicomTag.PatientName, string.Empty),
                        ds.GetValue <string>(DicomTag.WindowWidth, string.Empty),
                        ds.GetValue <string>(DicomTag.WindowCenter, string.Empty),
                        isStructuredDisplay);

            if (!string.IsNullOrEmpty(exceptionMessage))
            {
                string errorMessage = string.Format("Failed to show image.\n{0}", exceptionMessage);

                if (count > 1)
                {
                    errorMessage = string.Format("Failed to load one or more image frames.\n{0}", exceptionMessage);
                }
                Messager.ShowError(this, errorMessage);
            }
        }
예제 #27
0
        private void LoadUniqueFieldValueInstanceImages()
        {
            string zoneFile, sql, imageFile = "", imagePath;
            int    page = 0, zoneID = 1;

            if (ocrPageZones != null)
            {
                ocrPageZones.Dispose();
                ocrPageZones = null;
            }

            if (uniqueFieldValueRowNumber >= dataTableUniqueFieldValues.Rows.Count)
            {
                return;
            }

            OcrZone     zone;
            LeadRect    zoneRect;
            RasterImage pageImage = null, zoneImage;

            textBoxValue.Text = dataTableUniqueFieldValues.Rows[uniqueFieldValueRowNumber][0].ToString();
            sql              = "select Page, ZoneID from Field where Batch = '" + BatchName + "' and FieldID = " + fieldIndex.ToString() + " and (ValueAdvantage = '" + textBoxValue.Text.Replace("'", "''") + "') order by Page, Line";
            oleDbCommand     = new OleDbCommand(sql, oleDbConnection);
            oleDbDataAdapter = new OleDbDataAdapter(oleDbCommand);
            dataTableUniqueFieldValueInstances = new DataTable();
            oleDbDataAdapter.Fill(dataTableUniqueFieldValueInstances);
            images = new List <RasterImage>();

            foreach (DataRow instanceRow in dataTableUniqueFieldValueInstances.Rows)
            {
                zoneID = int.Parse(instanceRow["ZoneID"].ToString());

                if (page != int.Parse(instanceRow[0].ToString()))
                {
                    page             = int.Parse(instanceRow[0].ToString());
                    sql              = "select top 1 Srcfile from " + BatchTableName + " where Batch = '" + BatchName + "' and Page = " + page.ToString();
                    oleDbCommand     = new OleDbCommand(sql, oleDbConnection);
                    oleDbDataAdapter = new OleDbDataAdapter(oleDbCommand);
                    DataTable dataTableSrcfile = new System.Data.DataTable();
                    oleDbDataAdapter.Fill(dataTableSrcfile);

                    if (dataTableSrcfile.Rows.Count > 0)
                    {
                        imageFile = dataTableSrcfile.Rows[0][0].ToString();
                        imagePath = @"I:\" + BatchName.Split(' ')[0] + @"\" + imageFile;

                        if (imageFile.Split('\\').Length == 3)
                        {
                            imageFile = imageFile.Split('\\')[2];
                        }
                        else
                        {
                            imageFile = imageFile.Split('\\')[1];
                        }

                        zoneFile = imagePath.Substring(0, imagePath.LastIndexOf(".")) + ".ozf";

                        if (File.Exists(zoneFile))
                        {
                            try
                            {
                                pageImage = codecs.Load(imagePath);

                                if (pageImage.XResolution < 150)
                                {
                                    pageImage.XResolution = 150;
                                }

                                if (pageImage.YResolution < 150)
                                {
                                    pageImage.YResolution = 150;
                                }

                                ocrPageZones = OcrEngine.CreatePage(pageImage, OcrImageSharingMode.AutoDispose);
                                ocrPageZones.LoadZones(zoneFile);
                            }
                            catch (Exception ex)
                            {
                                if (showedMemoryMessage == false)
                                {
                                    Messager.ShowInformation(this, "Could not open " + imagePath + ". " + ex.Message);
                                    showedMemoryMessage = true;
                                }
                                pageImage = null;
                            }
                        }
                    }
                }

                if (pageImage != null)
                {
                    zone      = GetPageZone(ocrPageZones, zoneID);
                    zoneRect  = zone.Bounds.ToRectangle(150, 150);
                    zoneImage = pageImage.Clone(zoneRect);
                    zoneImage.CustomData.Add("Page", page.ToString());
                    zoneImage.CustomData.Add("ZoneID", instanceRow["ZoneID"].ToString());
                    zoneImage.CustomData.Add("FieldID", fieldIndex.ToString());
                    images.Add(zoneImage);
                }

                if (images.Count > 59)
                {
                    break;
                }
            }

            DisplayUniqueFieldValueInstanceImagePage();
        }
예제 #28
0
        public void Add(string key, RasterImage image)
        {
            Remove(key);

            _images[key] = image != null?image.Clone() : null;
        }
예제 #29
0
        private void ApplyFilter()
        {
            try
            {
                RasterImage runImage = _originalBitmap.Clone();

                if (_cbInvert.Checked)
                {
                    runImage.UseLookupTable = false;
                    InvertCommand invComd = new InvertCommand();
                    invComd.Run(runImage);
                }

                BackGroundRemovalCommand backgroundRemovalCommand = new BackGroundRemovalCommand(Convert.ToInt32(_numRemovalFactor.Value));
                backgroundRemovalCommand.Run(runImage);

                MinMaxValuesCommand minMaxCmd = new MinMaxValuesCommand();
                minMaxCmd.Run(runImage);
                int min = minMaxCmd.MinimumValue;
                int max = minMaxCmd.MaximumValue;

                if (_cbEnableEnhancements.Checked)
                {
                    AverageCommand avrcmd = new AverageCommand();
                    avrcmd.Dimension = 5;
                    avrcmd.Run(runImage);

                    MultiscaleEnhancementCommand MSECommand = new MultiscaleEnhancementCommand();
                    MSECommand.Contrast            = Convert.ToInt32(_numContrast.Value * 100);
                    MSECommand.EdgeCoefficient     = Convert.ToInt32(_numEdgeCoef.Value * 100);
                    MSECommand.EdgeLevels          = Convert.ToInt32(_numEdgeLevel.Value);
                    MSECommand.LatitudeCoefficient = 140;
                    MSECommand.LatitudeLevels      = 5;
                    MSECommand.Flags = MultiscaleEnhancementCommandFlags.EdgeEnhancement | MultiscaleEnhancementCommandFlags.LatitudeReduction;
                    MSECommand.Type  = MultiscaleEnhancementCommandType.Gaussian;
                    MSECommand.Run(runImage);
                }
                else
                {
                    AverageCommand avrcmd = new AverageCommand();
                    avrcmd.Dimension = 3;
                    avrcmd.Run(runImage);
                }

                ApplyLinearVoiLookupTableCommand voiCmd = new ApplyLinearVoiLookupTableCommand();
                voiCmd.Center = (min + max) / 2;
                voiCmd.Width  = max - min;
                voiCmd.Flags  = VoiLookupTableCommandFlags.UpdateMinMax;
                voiCmd.Run(runImage);

                GetLinearVoiLookupTableCommand voiLutCommand = new GetLinearVoiLookupTableCommand(GetLinearVoiLookupTableCommandFlags.None);
                voiLutCommand.Run(runImage);
                _form.WindowLevelWidth  = (int)voiLutCommand.Width;
                _form.WindowLevelCenter = (int)voiLutCommand.Center;

                _viewer.Image = runImage;
            }
            catch (System.Exception /*ex*/)
            {
            }
        }