public static void Run()
 {
     // ExStart:DICOMSimpleResizing
     // The path to the documents directory.
     string dataDir = RunExamples.GetDataDir_DICOM();
    
     // Load an existing image.
     using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
     {
         image.Resize(200, 200);
         image.Save(dataDir + "DICOMSimpleResizing_out.bmp", new BmpOptions());
     }
     // ExEnd:DICOMSimpleResizing
 }
        public static void Run()
        {
            // ExStart:RotatingDICOMImage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            // Load an existing image, Rotate Image & Save the resultant image.
            using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
            {               
                image.Rotate(10);
                image.Save(dataDir + "RotatingDICOMImage_out.bmp", new BmpOptions());
            }
            // ExEnd:RotatingDICOMImage
        }
        public static void Run()
        {
            // ExStart:ApplyFilterOnDICOMImage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            // Load an image          
            using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
            {
                // Supply the filters to DICOM image and Save the results to output path.
                image.Filter(image.Bounds, new MedianFilterOptions(8));
                image.Save(dataDir + "ApplyFilterOnDICOMImage_out.bmp", new BmpOptions());
            }
            // ExEnd:ApplyFilterOnDICOMImage
        }
        public static void Run()
        {
            // ExStart:DICOMCroppingByShifts
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            // Load an existing image.
            using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
            {
                // Call and supply the four values to Crop method and Save the results to disk
                image.Crop(1, 1, 1, 1);              
                image.Save(dataDir + "DICOMCroppingByShifts_out.bmp", new BmpOptions());
            }
            // ExEnd:DICOMCroppingByShifts
        }
        public static void Run()
        {
            // ExStart:BinarizationWithOtsuThresholdOnDICOMImage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            // Load an existing image.
            using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
            {
                // Binarize image with Otsu Thresholding and Save the resultant image.
                image.BinarizeOtsu();
                image.Save(dataDir + "BinarizationWithOtsuThresholdOnDICOMImage_out.bmp", new BmpOptions());
            }
            // ExEnd:BinarizationWithOtsuThresholdOnDICOMImage
        }
 public static void Run()
 {
     // ExStart:DitheringForDICOMImage
     // The path to the documents directory.
     string dataDir = RunExamples.GetDataDir_DICOM();
    
     // Load an existing image.
     using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
     {
         // Peform Threshold dithering on the image and  Save the resultant image.
         image.Dither(DitheringMethod.ThresholdDithering, 1);               
         image.Save(dataDir + "DitheringForDICOMImage_out.bmp", new BmpOptions());
     }
     // ExEnd:DitheringForDICOMImage
 }
 public static void Run()
 {
     // ExStart:GrayscalingOnDICOM
     // The path to the documents directory.
     string dataDir = RunExamples.GetDataDir_DICOM();
    
     // Load an existing image.
     using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
     {
         // Transform image to its grayscale representation and Save the resultant image.
         image.Grayscale();
         image.Save(dataDir + "GrayscalingOnDICOM_out.bmp", new BmpOptions());
     }
     // ExEnd:GrayscalingOnDICOM
 }
        public static void Run()
        {
            // ExStart:AdjustGammaDICOM
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            // Load a DICOM image in an instance of DicomImage
            using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
            {
                // Adjust the gamma and Create an instance of BmpOptions for the resultant image and Save the resultant image
                image.AdjustGamma(50);
                image.Save(dataDir + "AdjustGammaDICOM_out.bmp", new BmpOptions());
            }
            // ExEnd:AdjustGammaDICOM
        }
        public static void Run()
        {
            //ExStart:AdjustBrightnessDICOM
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            Console.WriteLine("Running example AdjustBrightnessDicom");
            using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
                using (DicomImage image = new DicomImage(fileStream))
                {
                    // Adjust the brightness and Create an instance of BmpOptions for the resultant image and Save the resultant image
                    image.AdjustBrightness(50);
                    image.Save(dataDir + "AdjustBrightnessDICOM_out.bmp", new BmpOptions());
                }

            Console.WriteLine("Finished example AdjustBrightnessDicom");
            //ExEnd:AdjustBrightnessDICOM
        }
        /// <summary>
        /// Loads images as writablebitmaps to list - consumes a lot of memory but works fast
        /// Frames support added
        /// </summary>
        /// <param name="series"></param>
        public void LoadBitmapsFromStudy(DicomSeries series)
        {
            //load dicom files from series
            _loadedBitmapSources = new List <BitmapSource>();
            _loadedDicomImages   = new List <DicomImage>();

            NumberOfImages = 0;

            foreach (var dicomFile in series.Instances)
            {
                try
                {
                    if (dicomFile.Dataset.Contains(DicomTag.PixelData))
                    {
                        var dicomImage = new DicomImage(dicomFile.Dataset);

                        CurrentWindowWidth  = dicomImage.WindowWidth;
                        CurrentWindowCentre = dicomImage.WindowCenter;

                        for (int i = 0; i < dicomImage.NumberOfFrames; i++)
                        {
                            var frame = dicomImage.RenderImage(i).AsWriteableBitmap();
                            _loadedBitmapSources.Add(frame);
                            _loadedDicomImages.Add(dicomImage);
                        }

                        // var frames = Enumerable.Range(0, dicomImage.NumberOfFrames).Select(frame => dicomImage.RenderImage(frame).As<WriteableBitmap>());

                        //WriteableBitmap dicomBitmap = dicomImage.RenderImage(0).As<WriteableBitmap>();
                        // _loadedBitmapSources.Add(dicomBitmap);

                        //_loadedBitmapSources.AddRange(frames.ToList());
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    System.Diagnostics.Debug.WriteLine(ex.InnerException);
                }
            }

            NumberOfImages = _loadedBitmapSources.Count;
            //NumberOfImages = _loadedDicomImages.Count;
        }
Example #11
0
        private DicomDataSet readDicom()
        {
            DicomImage            dImage        = Viewer.Images.Read(path + "\\00010001");
            DicomDataSet          dDSet         = Viewer.Images.Read(path + "\\00010001");
            List <DicomAttribute> allAttributes = dDSet.ToList();
            String toShow = "";

            for (int i = 0; i < allAttributes.Count; i++)
            {
                string group   = allAttributes[i].Group.ToString("X4");   //first 4 numbers
                string element = allAttributes[i].Element.ToString("X4"); //second 4 numbers
                string key     = allAttributes[i].Keyword;                //textual
                string value   = allAttributes[i].ToString();
                toShow = toShow + group + "-" + element + ";  " + key
                         + "--->" + value + "\n";
            }
            MessageBox.Show(toShow);
            return(dDSet);
        }
        public Slice(DicomFile dF)
        {
            data       = dF.Dataset;
            dicomImage = new DicomImage(data);
            Width      = dicomImage.PixelData.Width;
            Height     = dicomImage.PixelData.Height;

            // TODO: Read image depth
            Depth          = 16;
            sliceLocation  = dF.Dataset.GetValue <decimal>(DicomTag.SliceLocation, 0);
            sliceThickness = dF.Dataset.GetValue <decimal>(DicomTag.SliceThickness, 0);

            // TODO: Account for dicom files with more then one Frame
            pixelData = dicomImage.PixelData.GetFrame(0).Data;

            LoadLUT(@".\HotRed.lut");

            LoadPixels();
        }
Example #13
0
        public Stream getImageFile()
        {
            string filePath = string.Format("{0}{1}", Path.Combine(rootPath, studyInstanceUid, seriesInstanceUid, sopInstanceUid), ".dcm");

            if (File.Exists(filePath))
            {
                DicomImage imagedicom  = new DicomImage(filePath);
                var        bitmapImage = imagedicom.RenderImage().As <Bitmap>();
                filePath = sopInstanceUid + ".jpg";
                bitmapImage.Save(filePath);
                // Stream BmpStream = new MemoryStream();
                // bitmapImage.Save(BmpStream,ImageFormat.Icon);
                return(File.Open(filePath, FileMode.Open));
            }
            else
            {
                return(null);// string.Empty;
            }
        }
Example #14
0
        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                DicomFile dcmFile = new DicomFile();
                dcmFile = ((DicomIcon)(e.Item.Tag)).m_DicomFile;
                int        frames       = dcmFile.Dataset.Get(DicomTag.NumberOfFrames, 0);//如果该字段不存在,则默认值为1
                DicomFile  tmpFile      = dcmFile.Clone();
                DicomImage dcmSingleImg = new DicomImage(tmpFile.Dataset);
                Image      img          = dcmSingleImg.RenderImage(0);
                Image      process_img  = ZoomPicture(img, pictureBox_Display.Width, pictureBox_Display.Height);
                pictureBox_Display.Image = process_img;
                _image = dcmSingleImg;
                dcmFile.Dataset.Get(DicomTag.NumberOfFrames, 0);
                _grayscale = !_image.PhotometricInterpretation.IsColor;
                if (_grayscale)
                {
                    _windowWidth  = _image.WindowWidth;
                    _windowCenter = _image.WindowCenter;
                }

                int nRate = GetFrameRate(dcmSingleImg);//设置默认播放速度
                numericUpDown1.Value = nRate;

                ushort group   = ushort.Parse("0028", System.Globalization.NumberStyles.HexNumber);
                ushort element = ushort.Parse("0008", System.Globalization.NumberStyles.HexNumber);

                int frame_count = Convert.ToInt16(_image.Dataset.Get <string>(new DicomTag(group, element)));//设置进度条
                trackBar1.Maximum = frame_count;

                StartPlay();//开启播放
            }

            if (radiobtn1.Checked)  //设置标签
            {
                ShowDicomInfo(false);
            }

            else
            {
                ShowDicomInfo(true);
            }
        }
Example #15
0
        public static void Dcm2Jpg(Dcm2JpgOptions options)
        {
            var file      = DicomFile.Open(@options.dcmPath);
            var image     = new DicomImage(file.Dataset);
            var patientid = file.Dataset.Get <string>(DicomTag.PatientID);

            if (string.IsNullOrEmpty(patientid))
            {
                patientid = GetTimeStamp();
            }
            int x = file.Dataset.Get <int>(DicomTag.NumberOfFrames);

            for (var i = 0; i < x; i++)
            {
                var fileName = options.outJpgDir + "/" + patientid + "_" + (i + 1) + ".jpg";
                image.RenderImage(i).AsBitmap().Save(@fileName);
            }
            Console.WriteLine("success: dcm转jpg成功");
        }
        public static void Run()
        {
            //ExStart:BinarizationWithBradleysAdaptiveThreshold
            // The path to the documents directory.
            string dataDir   = RunExamples.GetDataDir_DICOM();
            string inputFile = dataDir + "image.dcm";

            Console.WriteLine("Running example BinarizationWithBradleysAdaptiveThreshold");
            using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
                using (DicomImage image = new DicomImage(fileStream))
                {
                    // Binarize image with bradley's adaptive threshold and Save the resultant image.
                    image.BinarizeBradley(10);
                    image.Save(dataDir + "BinarizationWithBradleysAdaptiveThreshold_out.bmp", new BmpOptions());
                }

            Console.WriteLine("Finished example BinarizationWithBradleysAdaptiveThreshold");
            //ExEnd:BinarizationWithOtsuThresholdOnDICOMImage
        }
Example #17
0
        protected override void Upload
        (
            fo.DicomDataset dicomObject,
            int frame,
            IStorageLocation storeLocation,
            DicomMediaProperties mediaProperties
        )
        {
            var frameIndex = frame - 1;
            var dicomImage = new DicomImage(dicomObject, frameIndex);
            var bitmap     = dicomImage.RenderImage(frameIndex).AsBitmap();
            var stream     = new MemoryStream( );

            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

            stream.Position = 0;

            storeLocation.Upload(stream, MediaType);
        }
Example #18
0
        public static void Run()
        {
            //ExStart:ApplyFilterOnDICOMImage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            Console.WriteLine("Running example ApplyFilterDicom");

            using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
                using (DicomImage image = new DicomImage(fileStream))
                {
                    // Supply the filters to DICOM image and Save the results to output path.
                    image.Filter(image.Bounds, new MedianFilterOptions(8));
                    image.Save(dataDir + "ApplyFilterOnDICOMImage_out.bmp", new BmpOptions());
                }

            Console.WriteLine("Finished example ApplyFilterDicom");
            //ExEnd:ApplyFilterOnDICOMImage
        }
Example #19
0
        private async void ButtonDebugOnClick(object sender, EventArgs e)
        {
            lock (_output)
            {
                if (_output.Count <= SelectedIndex)
                {
                    return;
                }
            }

            ImageProcessorOutput output     = _output[SelectedIndex];
            DicomFile            sourceFile = await DicomFile.OpenAsync(output.SourceFile.FullName);

            using (Bitmap original = new DicomImage(sourceFile.Dataset).RenderImage().AsClonedBitmap())
            {
                ImageProcessor ip = new ImageProcessor(original, debug: true);
                ip.Process();
            }
        }
Example #20
0
        public void RenderRTWithDoubleValues()
        {
            var myDicomFile = DicomFile.Open(TestData.Resolve("RI6XDosiGap.dcm"));

            myDicomFile.Dataset.AddOrUpdate(DicomTag.VOILUTFunction, "LINEAR_EXACT");

            var    myDicomImage = new DicomImage(myDicomFile.Dataset);
            IImage myImg        = myDicomImage.RenderImage(0);

            //var image = myImg.AsSharpImage();
            //using (var fs = new FileStream("d:\\image.png", FileMode.OpenOrCreate))
            //{
            //    image.Save(fs, new SixLabors.ImageSharp.Formats.Png.PngEncoder());
            //}

            var col1 = myImg.GetPixel(myImg.Width / 2, myImg.Height / 2);

            Assert.True(col1.R > 0);
        }
        public async Task OpenFiles()
        {
            var files = await _readerService.GetFilesAsync();

            if (files == null || files.Count == 0)
            {
                return;
            }

            _images        = null;
            File           = null;
            NumberOfImages = 0;

            if (files.Count == 1)
            {
                File = files.Single();
            }

            var imageFiles = files.Where(f => f.Dataset.Contains(DicomTag.PixelData)).ToList();

            if (imageFiles.Count > 0)
            {
                _images = imageFiles.SelectMany(
                    imageFile =>
                {
                    try
                    {
                        var dicomImage = new DicomImage(imageFile.Dataset);
                        var frames     =
                            Enumerable.Range(0, dicomImage.NumberOfFrames)
                            .Select(frame => dicomImage.RenderImage(frame).As <ImageSource>());
                        return(frames);
                    }
                    catch
                    {
                        return(new ImageSource[0]);
                    }
                }).ToList();

                NumberOfImages = _images.Count;
            }
        }
Example #22
0
 protected override void OnLoad(EventArgs e)
 {
     // execute on ThreadPool to avoid STA WaitHandle.WaitAll exception
     ThreadPool.QueueUserWorkItem(delegate(object s) {
         try {
             _image     = new DicomImage(_file.Dataset);
             _grayscale = !_image.PhotometricInterpretation.IsColor;
             if (_grayscale)
             {
                 _windowWidth  = _image.WindowWidth;
                 _windowCenter = _image.WindowCenter;
             }
             _frame = 0;
             Invoke(new WaitCallback(SizeForImage), _image);
             Invoke(new WaitCallback(DisplayImage), _image);
         } catch (Exception ex) {
             OnException(ex);
         }
     });
 }
Example #23
0
        public void LoadDicomFile(string fileName)
        {
            var dicomImage = new DicomImage(fileName);

            for (var i = 0; i < dicomImage.NumberOfFrames; i++)
            {
                seriesInformation.AddFrames(dicomImage);
            }
            imageBox.Image      = seriesInformation[0];
            imageBox.Width      = seriesInformation[0].Width;
            imageBox.Height     = seriesInformation[0].Height;
            imageBox.FrameIndex = currentFrameIndex;
            vScrollBar.Maximum  = seriesInformation.FramesCount - 1;
            vScrollBar.Value    = currentFrameIndex;
            SetWindowLevel(40, 400);
            if (seriesInformation.FramesCount == 1)
            {
                SetLabel();
            }
        }
Example #24
0
        // extract all frames from a .dcm file
        // overloaded for use with progress bar
        public static void dcm_to_png(string dcmFile, string pngTempDir, ProgressWindow progform)
        {
            var image  = new DicomImage(dcmFile);
            int frames = image.NumberOfFrames;

            // number format, making sure its prefixed with appropriate number of zeros
            // currently guarantees a four digit number
            // (dont think ive see dicom files with thousands of frames?)
            string fmt = "0000";

            for (int i = 0; i < frames; i++)
            {
                // render each frame as png
                image.RenderImage(i).Save(pngTempDir + i.ToString(fmt) + ".png");

                int iout = (((i + 1) * 100) / frames);

                progform.setProgress(iout);
            }
        }
        public static void Run()
        {
            // ExStart:DICOMSOtherImageResizingOptions
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();
           
            // Load an existing image.
            using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
            {
                image.ResizeHeightProportionally(100, ResizeType.AdaptiveResample);
                image.Save(dataDir + "DICOMSOtherImageResizingOptions_out.bmp", new BmpOptions());
            }

            using (DicomImage image1 = new DicomImage(dataDir + "image.dcm"))
            {
                image1.ResizeWidthProportionally(150, ResizeType.AdaptiveResample);
                image1.Save(dataDir + "DICOMSOtherImageResizingOptions1_out.bmp", new BmpOptions());
            }
            // ExEnd:DICOMSOtherImageResizingOptions
        }
Example #26
0
        public static void Run()
        {
            // ExStart:DICOMSOtherImageResizingOptions
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DICOM();

            // Load an existing image.
            using (DicomImage image = new DicomImage(dataDir + "image.dcm"))
            {
                image.ResizeHeightProportionally(100, ResizeType.AdaptiveResample);
                image.Save(dataDir + "DICOMSOtherImageResizingOptions_out.bmp", new BmpOptions());
            }

            using (DicomImage image1 = new DicomImage(dataDir + "image.dcm"))
            {
                image1.ResizeWidthProportionally(150, ResizeType.AdaptiveResample);
                image1.Save(dataDir + "DICOMSOtherImageResizingOptions1_out.bmp", new BmpOptions());
            }
            // ExEnd:DICOMSOtherImageResizingOptions
        }
Example #27
0
        private static void Main(string[] args)
        {
            // Initialize log manager.
            LogManager.SetImplementation(ConsoleLogManager.Instance);

            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();

            var printJob = new PrintJob("DICOM PRINT JOB")
            {
                RemoteAddress = "localhost",
                RemotePort    = 8000,
                CallingAE     = "PRINTSCU",
                CalledAE      = "PRINTSCP"
            };

            printJob.StartFilmBox("STANDARD\\1,1", "PORTRAIT", "A4");

            printJob.FilmSession.IsColor = false; //set to true to print in color

            //greyscale
            var dicomImage = new DicomImage(@"Data\1.3.51.5155.1353.20020423.1100947.1.0.0.dcm");

            //color
            //var dicomImage = new DicomImage(@"Data\US-RGB-8-epicard.dcm");

            var bitmap = dicomImage.RenderImage().As <Bitmap>();

            printJob.AddImage(bitmap, 0);

            bitmap.Dispose();

            printJob.EndFilmBox();

            printJob.Print();

            stopwatch.Stop();
            Console.WriteLine();
            Console.WriteLine(stopwatch.Elapsed);
        }
Example #28
0
        /// <summary>
        /// open and show dicom file
        /// </summary>
        /// <param name="dicmFile"></param>
        /// <returns></returns>
        public bool OpenImage(string dicomFile)
        {
            try
            {
                var image = new DicomImage(dicomFile);
#pragma warning disable CS0618
                var pixelData = image.PixelData.GetFrame(0).Data;

                this.bits   = image.Dataset.Get <int>(DicomTag.BitsStored);
                this.width  = image.Width;
                this.height = image.Height;
                this.ww     = image.WindowWidth;
                this.wl     = image.WindowCenter;

                SetWindowInfo(ww, wl);

                if (bits > 8)
                {
                    raw16BitBuffer = new byte[width * height * 2];
                    Array.Copy(pixelData, raw16BitBuffer, pixelData.Length);
                }
                else
                {
                    raw8BitBuffer = new byte[width * height];
                    Array.Copy(pixelData, raw8BitBuffer, pixelData.Length);
                }

                var writeableBitmap = ConvertUtil.GetWriteableBitmap(pixelData, this.width, this.height, this.bits);
                var imageSource     = ConvertUtil.GetImageSource(writeableBitmap);

                this.image.Source = imageSource;

                HasImage = true;
                ResetZoomPoint();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #29
0
        public void DrawImageBox(ImageBox imgBox, Graphics graphics, RectangleF box, int imageResolution)
        {
            var imageSequence = imgBox.ImageSequence;
            var state         = graphics.Save();

            FillBox(box, graphics);

            var imageBox = box;

            if (_currentFilmBox.Trim == "YES")
            {
                imageBox.Inflate(-Hundredths, -Hundredths);
            }

            if (imageSequence != null && imageSequence.Contains(DicomTag.PixelData))
            {
                Image bitmap = null;
                try
                {
                    var image = new DicomImage(imageSequence);
                    var frame = image.RenderImage();

                    bitmap = frame;
                    if (imgBox.Polarity == "REVERSE")
                    {
                        bitmap = Transform((Bitmap)bitmap);
                    }

                    DrawBitmap(graphics, box, bitmap, imageResolution);
                }
                finally
                {
                    if (bitmap != null)
                    {
                        bitmap.Dispose();
                    }
                }
            }

            graphics.Restore(state);
        }
        public byte[] GetImageBytes(DicomFile file, int frame)
        {
            if (file != null)
            {
                Debug.WriteLine(file.GetType().ToString());

                var name = file.Dataset.Get<string>(DicomTag.PatientName);

                if (name != null)
                    Debug.WriteLine(name);

                var dicomImage = new DicomImage(file.Dataset);

                var image = dicomImage.RenderImage(frame);

                return image.AsUIImage().AsPNG().ToArray();
                
            }

            return null;
        }
Example #31
0
        public void DicomPixelData_TestDefaultWindowing()
        {
            // an image, that contains several values in 0028,1050 and 0028,1051
            var img = new DicomImage(@"Test Data\IM-0001-0001-0001.dcm");

            img.RenderImage(0);
            Assert.Equal(img.Dataset.GetValue <double>(DicomTag.WindowWidth, 0), img.WindowWidth);
            Assert.Equal(img.Dataset.GetValue <double>(DicomTag.WindowCenter, 0), img.WindowCenter);

            // an image, that contains one windowing-setting
            img = new DicomImage(@"Test Data\CR-MONO1-10-chest");
            img.RenderImage(0);
            Assert.Equal(img.Dataset.GetSingleValue <double>(DicomTag.WindowWidth), img.WindowWidth);
            Assert.Equal(img.Dataset.GetSingleValue <double>(DicomTag.WindowCenter), img.WindowCenter);

            // an image with no windowing-setting
            img = new DicomImage(@"Test Data\GH227.dcm");
            img.RenderImage(0);
            Assert.Equal(255, img.WindowWidth);
            Assert.Equal(127.5, img.WindowCenter);
        }
Example #32
0
 private void onDicomArrived(object sender, FileSystemEventArgs e)
 {
     try
     {
         var dicomImage = new DicomImage(Path.Combine(watcher.Path, Constants.tempFileName));
         extractData(dicomImage);
         try
         {
             seriesThumb = dicomImage.RenderImage().AsClonedBitmap();
             manualResetEvent.Set();
         }
         catch (Exception exc)
         {
             isImage = false;
         }
     }
     catch (Exception exc)
     {
         Console.WriteLine("got this exception: " + exc.Message);
     }
 }
Example #33
0
        /// <summary>
        /// Process click of convert to PNG menu item in process menu.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void ConvertToPngToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var openFolderDialog = new FolderBrowserDialog
            {
                SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };

            if (openFolderDialog.ShowDialog().Equals(DialogResult.OK))
            {
                var paths = (from DataGridViewRow dataGridViewRow in this.dataGridView.Rows
                             select dataGridViewRow.Cells["FilePathColumn"].Value as string).ToList();
                Parallel.ForEach(paths, path =>
                {
                    var newPath = Path.Combine(openFolderDialog.SelectedPath,
                                               Path.GetFileNameWithoutExtension(path) + ".png");
                    var image = new DicomImage(path);
                    image.RenderImage().Save(newPath, ImageFormat.Png);
                    image = null;
                });
            }
        }
Example #34
0
        private void loadDicomButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog()
            {
                Filter = "DICOM|*.dcm"
            };

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DicomFile file = DicomFile.Open(ofd.FileName);
                Bitmap    img  = new DicomImage(ofd.FileName).RenderImage().AsClonedBitmap();
                globalOutBitmap                 = img;
                pictureOut.Image                = img;
                pictureSinogram.Image           = null;
                pictureIn.Image                 = null;
                buttonStart.Enabled             = false;
                scrollProgress.Enabled          = false;
                buttonSaveSinogram.Enabled      = false;
                textBoxName.Enabled             = true;
                textBoxName.Text                = file.Dataset.GetSingleValue <string>(DicomTag.PatientName);
                textBoxID.Enabled               = true;
                textBoxID.Text                  = file.Dataset.GetSingleValue <string>(DicomTag.PatientID);
                dateTimePickerBirthDate.Enabled = true;
                dateTimePickerBirthDate.Value   = DateTime.Parse(file.Dataset.GetSingleValue <string>(DicomTag.PatientBirthDate));
                String gender = file.Dataset.GetSingleValue <string>(DicomTag.PatientSex);
                radioButtonGenderF.Enabled = true;
                radioButtonGenderM.Enabled = true;
                if (gender == "M")
                {
                    radioButtonGenderM.Checked = true;
                    radioButtonGenderF.Checked = false;
                }
                else
                {
                    radioButtonGenderM.Checked = false;
                    radioButtonGenderF.Checked = true;
                }
                saveDicomButton.Enabled = true;
            }
        }
Example #35
0
        private void OnClickSave(object sender, EventArgs e)
        {
            var sfd = new SaveFileDialog();

            sfd.Filter = "DICOM (*.dcm)|*.dcm|Image (*.bmp;*.jpg;*.png;*.gif)|*.bmp;*.jpg;*.png;*.gif";

            if (sfd.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            if (sfd.FilterIndex == 1)
            {
                var file = new DicomFile(_file.Dataset);
                file.Save(sfd.FileName);
            }
            else
            {
                var image = new DicomImage(_file.Dataset);
                image.RenderImage().As <Image>().Save(sfd.FileName);
            }
        }
Example #36
0
        public MemoryStream Render(float scale, int offsetX, int offsetY, int canvasWidth, int canvasHeight)
        {
            if (m_Bitmap == null)
            {
                var image = new DicomImage(m_File.Dataset);
                using (var renderedImage = image.RenderImage())
                {
                    m_Bitmap = renderedImage.AsClonedBitmap();
                }
            }

            using (var canvasBitmap = new Bitmap(canvasWidth, canvasHeight))
            {
                using (var graphics = Graphics.FromImage(canvasBitmap))
                {
                    graphics.DrawImage(m_Bitmap, GetRenderedRect(scale, offsetX, offsetY, m_Bitmap.Size, canvasBitmap.Size));
                }
                var stream = new MemoryStream();
                canvasBitmap.Save(stream, ImageFormat.Jpeg);
                return(stream);
            }
        }
Example #37
0
        /// <summary>
        /// Dicomファイルの読み込み
        /// </summary>
        /// <returns></returns>
        private bool ReadDicom()
        {
            if (_DicomDir.Length < 1)
            {
                return(false);
            }
            var dicomFiles = Directory.GetFiles(_DicomDir, @"*", SearchOption.TopDirectoryOnly);

            _Slices.Clear();
            foreach (var f in dicomFiles)
            {
                var dicomImg = new DicomImage(f);
                if (dicomImg == null)
                {
                    continue;
                }
                if (_Slices.Count < 1)
                {
                    _SliceThickness = dicomImg.Dataset.GetValue <double>(new DicomTag(0x18, 0x50), 0);
                    _PixelSpacingX  = dicomImg.Dataset.GetValue <double>(new DicomTag(0x28, 0x30), 0);
                    _PixelSpacingY  = dicomImg.Dataset.GetValue <double>(new DicomTag(0x28, 0x30), 1);
                    _ImgW           = dicomImg.Width;
                    _ImgH           = dicomImg.Height;
                    _LineSheet      = new Mat(new Size(_ImgW, _ImgH), MatType.CV_8UC3, new Scalar(0, 0, 255));
                }
                _Slices.Add(new Mat(_ImgH, _ImgW, MatType.CV_16SC1, dicomImg.PixelData.GetFrame(0).Data));
                _LineVolume.Add(new Mat(_ImgH, _ImgW, MatType.CV_8UC1, new Scalar(0)));
            }
            if (_Slices.Count < 1)
            {
                MessageBox.Show("Can't find Dicom image");
                return(false);
            }
            TbrSliceIdx.Minimum = 0;
            TbrSliceIdx.Maximum = _Slices.Count - 1;
            TbrSliceIdx.Value   = 0;

            return(true);
        }
Example #38
0
        public static RawData FromDicom(string filename)
        {
            RawData raw = new RawData
            {
                SourceFileName = Path.GetFileName(filename),
                SourcePath     = filename,
            };

            try
            {
                var dicomImage = new DicomImage(raw.SourcePath);
                raw.Width          = dicomImage.Width;
                raw.Height         = dicomImage.Height;
                raw.FrameCount     = dicomImage.NumberOfFrames;
                raw.PixelsPerFrame = raw.Width * raw.Height;
                raw.Size           = raw.PixelsPerFrame * raw.FrameCount;
                raw.Data           = new ushort[raw.Size];

                byte[] buffer = dicomImage.Dataset.GetDicomItem <DicomElement>(DicomTag.PixelData).Buffer.Data;

                for (int frameIdx = 0; frameIdx < raw.FrameCount; frameIdx++)
                {
                    int dataOffset   = frameIdx * raw.PixelsPerFrame;
                    int sourceOffset = dataOffset * 2;
                    for (int i = 0; i < raw.PixelsPerFrame; i++)
                    {
                        int  bufferOffset = sourceOffset + i * 2;
                        byte low          = buffer[bufferOffset];
                        byte high         = buffer[bufferOffset + 1];
                        raw.Data[dataOffset + i] = (ushort)(high * 256 + low);
                    }
                }
            }
            catch
            {
                return(null);
            }
            return(raw);
        }
Example #39
0
        internal static async Task <IImage> GetLocalImageAsyn(string sOPInstanceUID, int frameIndex)
        {
            var tmp = Sqlhelper.Exesql($"Select * FROM Local_Frame WHERE SOPInstanceUID=\'{sOPInstanceUID}\' and FrameIndex = {frameIndex}");

            if (tmp.Rows.Count != 0)
            {
                String FilePath = tmp.Rows[0]["LocalFilePath"].ToString();
                //var df = DicomFile.Open(@"D:\ProjectHub\WSILIB\WSILIB\bin\Debug\1.dcm");
                int LocalFrameIndex = int.Parse(tmp.Rows[0]["LocalFrameIndex"].ToString());
                var dcmFile         = DicomFile.Open(FilePath);
                var ans             = new DicomImage(dcmFile.Dataset);
                var my = ans.RenderImage(LocalFrameIndex);
                return(my);
            }
            else
            {
                NetWork netWork = new NetWork();
                await netWork.SaveTargetFramesAsyn(sOPInstanceUID, frameIndex);

                return(null);
            }
        }