Extract, Edit, and Replace DICOM Images - Console C#

This tutorial shows how to extract DICOM images as PNG files and then replace the DICOM images in a C# Windows Console application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to extract and replace DICOM images in a C# Windows Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (4 KB)
Platform C# Windows Console Application
IDE Visual Studio 2019, 2022
Development License Download LEADTOOLS

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Extract, Edit, and Replace DICOM Images - Console C# tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added by one or the other of the following two methods (but not both). For this project, the following references are needed:

If using NuGet references, this tutorial requires the following NuGet package:

If local DLL references are used, the following DLLs are needed. The DLLs are located at <INSTALL_DIR>\LEADTOOLS22\Bin\Dotnet4\x64:

For a complete list of which DLL files are required for your application, refer to Files to be Included in your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Add the DICOM Image Extraction Code

With the project created, the references added, and the license set, coding can begin.

In the Solution Explorer, open Program.cs. Add the following statements to the using block at the top of Program.cs:

C#
using System; 
using System.Collections.Generic; 
using System.IO; 
using Leadtools; 
using Leadtools.Codecs; 
using Leadtools.Dicom; 

Add the below global RasterCodecs variable inside the Program class.

C#
static RasterCodecs codecs = new RasterCodecs(); 

Add a new method named ExtractPngFromDicom(string dicomFile, string outDir) inside the Program class. This method will be called inside the Main() method, as shown below, to return a string array of the DICOM images extracted as PNG files.

Ensure the Main() method includes the code below up to this point.

C#
static void Main(string[] args) 
{ 
   string dicomFile = @"C:\LEADTOOLS22\Resources\Images\DICOM\image3.dcm"; 
   // Create a local output directory for the files to be saved 
   string outDir = @"OUTPUT DIRECTORY"; 
 
   SetLicense(); 
   DicomEngine.Startup(); 
   var extractedFrames = ExtractPngFromDicom(dicomFile, outDir); 
} 

Add the code below to extract the DICOM images as PNG files.

C#
private static string[] ExtractPngFromDicom(string dicomFile, string outDir) 
{ 
   // Create a list of output files 
   var outputFiles = new List<string>(); 
   if (!Directory.Exists(outDir)) 
         Directory.CreateDirectory(outDir); 
   // Load the DICOM pixel data 
   var ds = new DicomDataSet(); 
   ds.Load(dicomFile, DicomDataSetLoadFlags.None); 
   var pixelDataElement = ds.FindFirstElement(null, DicomTag.PixelData, true); 
   if (pixelDataElement == null) throw new Exception("This dataset is missing the pixel data element"); 
 
   var imageCount = ds.GetImageCount(pixelDataElement); 
   var imageInformation = ds.GetImageInformation(pixelDataElement, 0); 
 
   if (imageCount == 0) throw new Exception("This dataset has no images"); 
   if (imageInformation == null) throw new Exception("Can't retrieve image information"); 
   // Get all the images based on pixel data and image information 
   using (var image = ds.GetImages(pixelDataElement, 0, imageInformation.FrameCount, 0, RasterByteOrder.Gray, DicomGetImageFlags.AllowRangeExpansion | DicomGetImageFlags.AutoApplyModalityLut | DicomGetImageFlags.AutoApplyVoiLut)) 
         for (int i = 1; i <= image.PageCount; i++) 
         { 
             
            var outFileName = Path.Combine(outDir, Path.GetFileNameWithoutExtension(dicomFile) + ".png"); 
            // Save the image as a PNG file 
            codecs.Save(image, outFileName, RasterImageFormat.Png, 0, i, i, 1, CodecsSavePageMode.Overwrite); 
            // Add the output file name to the list of output files 
            outputFiles.Add(outFileName); 
         } 
 
   return outputFiles.ToArray(); 
} 

Add the Replace DICOM Images Code

Add a new method named ReplaceDicomImages(string dicomFile, string outDir, params string[] imageFiles) inside the Program class. This method will be called inside the Main() method, below the call to the ExtractPngFromDicom() method, as shown below. Also add the line of code at the bottom of the Main() method to shutdown the DicomEngine.

C#
static void Main(string[] args) 
{ 
   string dicomFile = @"C:\LEADTOOLS22\Resources\Images\DICOM\image3.dcm"; 
   // Create a local output directory for the files to be saved 
   string outDir = @"OUTPUT DIRECTORY"; 
 
   SetLicense(); 
   DicomEngine.Startup(); 
   var extractedFrames = ExtractPngFromDicom(dicomFile, outDir); 
 
   // Apply Redaction, anonymization, etc. to PNG 
   ReplaceDicomImages(dicomFile, outDir, extractedFrames); 
   DicomEngine.Shutdown(); 
} 

Add the code below to take the PNGs created in the ExtractPngFromDicom() method and add them back as DICOM images.

C#
private static string ReplaceDicomImages(string dicomFile, string outDir, params string[] imageFiles) 
{ 
   // Load the DICOM pixel data 
   var ds = new DicomDataSet(); 
   ds.Load(dicomFile, DicomDataSetLoadFlags.None); 
 
   // Changing ImageType to DERIVED to meet DICOM standards, since we are changing the image 
   List<string> it = ds.GetValue<List<string>>(DicomTag.ImageType, null); 
   if (it.Contains("ORIGINAL")) 
   { 
      it.Remove("ORIGINAL"); 
      it.Insert(0, "DERIVED"); 
   } 
   ds.InsertElementAndSetValue(DicomTag.ImageType, it.ToArray()); 
 
   var pixelDataElement = ds.FindFirstElement(null, DicomTag.PixelData, true); 
   if (pixelDataElement == null) 
         pixelDataElement = ds.InsertElement(null, false, DicomTag.PixelData, DicomVRType.UN, false, 0); 
   // Create a new RasterImage set to null 
   RasterImage img = null; 
   foreach (var imageFile in imageFiles) 
   { 
         // Load the image file 
         if (img == null) 
            img = codecs.Load(imageFile); 
         else 
            img.AddPage(codecs.Load(imageFile)); 
   } 
   // Set the image back to a DICOM file 
   ds.SetImages(pixelDataElement, img, DicomImageCompressionType.J2kLossless, DicomImagePhotometricInterpretationType.Monochrome2, 0, 2, DicomSetImageFlags.AutoSetVoiLut); 
   var outFileName = Path.Combine(outDir, Path.GetFileNameWithoutExtension(dicomFile) + "_replaced.dcm"); 
   ds.Save(outFileName, DicomDataSetSaveFlags.None); 
   return outFileName; 
} 

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the console appears and confirms that the license was set correctly. Then the application extracts a PNG from a DICOM image, replaces it, and saves it to the specified location.

Wrap-up

This tutorial showed how to create a simple console-based image extraction application that initializes the LEAD DICOM Engine, extracts a PNG from a DICOM file and replaces it.

See Also

Help Version 22.0.2022.9.29
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2022 LEAD Technologies, Inc. All Rights Reserved.


Products | Support | Contact Us | Intellectual Property Notices
© 1991-2022 LEAD Technologies, Inc. All Rights Reserved.