Showing posts with label SimpleITK. Show all posts
Showing posts with label SimpleITK. Show all posts

Sunday, January 16, 2022

Update the Dicom image metadata using Java

In this tutorial, we are going to learn how we can update the Dicom image metadata for the Dicom file.

We are using the SimpleITK library for this. SimpleITK library is very handy while working on medical image manipulation, processing, and analysis. Please follow our previous tutorial before starting this tutorial.

Simple Itk Installation for Java Application.

Read the Dicom Image metadata using Java

Let's create a sample java class ModifyMetaData.java. Create a main method that runs the update metadata code.

public static void main(String[] args) {
        String dcmImagePath = "input_dicom_image_path/N2D_0001.dcm";
        String metaDataKeyToUpdate = "0010|0020"; // Patient Id
        String metaDataValueToUpdate = "02L3000";
        String outputDcmPath = "output_dicom_image_path/output.dcm";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(dcmImagePath);
            Image image = imageFileReader.execute(); // Read image
            updateMetaData(image, metaDataKeyToUpdate, metaDataValueToUpdate);
            writeImage(image, outputDcmPath);
        } catch (Exception e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }

Here, we are defining the input Dicom image path, metadata key to update. The metadata tag must be in the format of 0010|0020. Metadata value to update and the output Dicom image path to save the update Dicom image.

First, we are reading the Dicom image then we are updating the image with the tag value for the tag. Here we are using the patient Id tag to update. Please visit the Dicom library for the universal Dicom tag and its description.

Let's implement the method used in the main method.

private static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }

This method reads the Dicom image using the SimpleItk library.

private static void updateMetaData(Image image, String metaDataKey, String metaDataValue) {
        image.setMetaData(metaDataKey, metaDataValue);
    }

Here, we are simply updating the patient id provided with the value

private static void writeImage(Image image, String outputImagePath) {
        SimpleITK.writeImage(image, outputImagePath);
    }

Here, we are writing the updated Dicom image to the output file path. If we verify the file then the Dicom image, the Patient Id value is changed.

The overall code implementation looks as below:

package simpleitk;

import org.itk.simple.Image;
import org.itk.simple.ImageFileReader;
import org.itk.simple.SimpleITK;

public class ModifyMetaData {

    public static void main(String[] args) {
        String dcmImagePath = "input_dicom_image_path/N2D_0001.dcm";
        String metaDataKeyToUpdate = "0010|0020"; // Patient Id
        String metaDataValueToUpdate = "02L3000";
        String outputDcmPath = "output_dicom_image_path/output.dcm";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(dcmImagePath);
            Image image = imageFileReader.execute(); // Read image
            updateMetaData(image, metaDataKeyToUpdate, metaDataValueToUpdate);
            writeImage(image, outputDcmPath);
        } catch (Exception e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }

    private static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }

    private static void updateMetaData(Image image, String metaDataKey, String metaDataValue) {
        image.setMetaData(metaDataKey, metaDataValue);
    }

    private static void writeImage(Image image, String outputImagePath) {
        SimpleITK.writeImage(image, outputImagePath);
    }
}
Share:

Saturday, January 8, 2022

How to convert Dicom file into PNG or JPG using Java

In this tutorial, we are going to learn how to convert the Dicom file into Png or Jpg.

If we want to present the Dicom image in the browser or sometimes it might be required to convert it to the desired png or jpg image to manipulate process and analysis.

For this, we can use a very useful library called SimpleItk. Please go over the installation process from this tutorial. If we are dealing with medical images like Dicom, the library is very useful for image processing, manipulation, and analysis. So we suggest using the library.

For reading Dicom metadata please follow this tutorial.

Now, let's begin with the conversion of the Dicom file, for this let's create a sample Java class called DicomConverter.java and create a method for reading the Dicom file

import org.itk.simple.*;
public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }

Now, let's add the method for converting the Dicom

public static void convert(ImageFileReader imageFileReader, String outputPath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputPath);
    }

Create the main method to run the conversion

 public static void main(String[] args) {
        String inputDicomPath = "inputdicom_path/N2D_0001.dcm";
        String outputPath = "output_path/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(inputDicomPath);
            convert(imageFileReader, outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
For Jpg use the .jpg output path.

The overall implementation looks like below:

package dicom;

import org.itk.simple.*;


public class DicomConverter {
    public static void main(String[] args) {
        String inputDicomPath = "/N2D_0001.dcm";
        String outputPath = "/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(inputDicomPath);
            convert(imageFileReader, outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }
    public static void convert(ImageFileReader imageFileReader, String outputPath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputPath);
    }
}
Share:

Read the Dicom Image metadata using Java

In this tutorial, we are going to learn how we can read Dicom image metadata. 

A Dicom metadata generally contains:

  •  A tag that identifies the attribute, usually in the format (XXXX,XXXX) with hexadecimal numbers.
  • A DICOM Value Representation (VR) that describes the data type and format of the attribute value

We are using SimpleITK library to extract metadata. The library is very handy when used for medical Image analysis. So, please refer SimpleITK library installation from this tutorail.

Once installed and load the library, let's write some Java code that reads metadata. Create a Java file called DicomReader.java

Read the Dicom file using SimpleITK:

import org.itk.simple.ImageFileReader;
public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }
This will read the Dicom file. This example uses the standard SimpleITK native library.

Let's create an actual method that read the metadata from the Dicom Image file

import org.itk.simple.VectorString;
import java.util.LinkedHashMap;
import java.util.Map;
public static Map<String, String> readMetadata(ImageFileReader imageFileReader) {
        Map<String, String> metaData = new LinkedHashMap<>();
        imageFileReader.loadPrivateTagsOn();
        imageFileReader.readImageInformation();
        VectorString metaDataKeys = imageFileReader.getMetaDataKeys(); // get metadata keys
        long metaDataKeySize = metaDataKeys.size();
        System.out.println("Total meta data found: " + metaDataKeySize);
        for (int metaDataKeyIndex = 0; metaDataKeyIndex < metaDataKeySize; metaDataKeyIndex++) {
            String metaDataKey = metaDataKeys.get(metaDataKeyIndex);
            String metaDataValue = imageFileReader.getMetaData(metaDataKey);
            System.out.println("Key: " + metaDataKey + " Value: " + metaDataValue);
            metaData.put(metaDataKey, metaDataValue);
        }
        return metaData;
    }
Here, we are passing the ImageFileReader object, which is obtained from the previous method. And it will extract the metadata and loop through the metadata keys and print key values. pair in the console.

Here is the sample GitHub repo for getting sample test Dicom. Let's add the main method to run the code

 public static void main(String[] args) {
        String imagePath = "path_to_dicom/N2D_0001.dcm";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(imagePath);
            Map<String, String> metadata = readMetadata(imageFileReader);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

The output of the above example will be similar to like this:

Total meta data found: 53
Key: 0008|0008 Value: DERIVED\SECONDARY 
Key: 0008|0016 Value: 1.2.840.10008.5.1.4.1.1.4
Key: 0008|0018 Value: 1.2.826.0.1.3680043.2.1143.1590429688519720198888333603882344634
Key: 0008|0020 Value: 20130717
Key: 0008|0021 Value: 20130717
Key: 0008|0022 Value: 20130717
Key: 0008|0023 Value: 20130717
Key: 0008|0030 Value: 141500
Key: 0008|0031 Value: 142035.93000
Key: 0008|0032 Value: 132518
Key: 0008|0033 Value: 142035.93 
Key: 0008|0050 Value: 
Key: 0008|0060 Value: MR
Key: 0008|0070 Value: BIOLAB
Key: 0008|0080 Value: 
Key: 0008|0090 Value: 
Key: 0008|1030 Value: Hanke_Stadler^0024_transrep 
Key: 0008|103e Value: anat-T1w
Key: 0008|1090 Value: nifti2dicom 
Key: 0010|0010 Value: Jane_Doe
Key: 0010|0020 Value: 02
Key: 0010|0030 Value: 19660101
Key: 0010|0040 Value: F 
Key: 0010|1000 Value: 
Key: 0010|1010 Value: 42
Key: 0010|1030 Value: 75
Key: 0010|21c0 Value: 4
Key: 0018|0050 Value: 0.666666686534882 
Key: 0018|0088 Value: 0.666666686534882 
Key: 0018|1020 Value: 0.4.11
Key: 0018|1030 Value: anat-T1w
Key: 0020|000d Value: 1.2.826.0.1.3680043.2.1143.2592092611698916978113112155415165916
Key: 0020|000e Value: 1.2.826.0.1.3680043.2.1143.515404396022363061013111326823367652
Key: 0020|0010 Value: 433724515 
Key: 0020|0011 Value: 401 
Key: 0020|0012 Value: 1 
Key: 0020|0013 Value: 1 
Key: 0020|0020 Value: L\R 
Key: 0020|0032 Value: -91.4495864331908\-160.06035870244\-142.505487236053
Key: 0020|0037 Value: 0.999032176441525\-0.0217883751691557\0.0382096472372976\0.026519476938784\0.991413870277297\-0.128043957939
Key: 0020|0052 Value: 1.2.826.0.1.3680043.2.1143.6856184167807409206647724161920598374
Key: 0028|0002 Value: 1
Key: 0028|0004 Value: MONOCHROME2 
Key: 0028|0010 Value: 384
Key: 0028|0011 Value: 274
Key: 0028|0030 Value: 0.666666686534882\0.699987828731537 
Key: 0028|0100 Value: 16
Key: 0028|0101 Value: 16
Key: 0028|0102 Value: 15
Key: 0028|0103 Value: 1
Key: 0028|1052 Value: 0 
Key: 0028|1053 Value: 1 
Key: 0028|1054 Value: US

In the above output, the key is the standard metadata key and the corresponding values are the metadata value of Dicom. 

You can find the standard Dicom tags from DICOM Tags. For e.g metadata key 0008|0008 denotes name as Image Type. Please check the link to get all the information on these keys.

The sample Dicom file used here is:


Convert the Dicom into png or jpg using SimpleITK:

Let's write the method which will convert the Dicom to PNG or JPG

 public static void convert(ImageFileReader imageFileReader, String outputImagePath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputImagePath);
    }
 public static void main(String[] args) {
        String imagePath = "input_path/N2D_0001.dcm";
        String outputImagePath = "output_path/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(imagePath);
            Map<String, String> metadata = readMetadata(imageFileReader);
            convert(imageFileReader, outputImagePath);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

The overall implementation looks as below:

package simpleitk;

import org.itk.simple.Image;
import org.itk.simple.ImageFileReader;
import org.itk.simple.SimpleITK;
import org.itk.simple.VectorString;

import java.util.LinkedHashMap;
import java.util.Map;

public class DicomReader {
    public static void main(String[] args) {
        String imagePath = "input_path/N2D_0001.dcm";
        String outputImagePath = "output_path/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(imagePath);
            Map<String, String> metadata = readMetadata(imageFileReader);
            convert(imageFileReader, outputImagePath);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }

    public static Map<String, String> readMetadata(ImageFileReader imageFileReader) {
        Map<String, String> metaData = new LinkedHashMap<>();
        imageFileReader.loadPrivateTagsOn();
        imageFileReader.readImageInformation();
        VectorString metaDataKeys = imageFileReader.getMetaDataKeys();
        long metaDataKeySize = metaDataKeys.size();
        System.out.println("Total meta data found: " + metaDataKeySize);
        for (int metaDataKeyIndex = 0; metaDataKeyIndex < metaDataKeySize; metaDataKeyIndex++) {
            String metaDataKey = metaDataKeys.get(metaDataKeyIndex);
            String metaDataValue = imageFileReader.getMetaData(metaDataKey);
            System.out.println("Key: " + metaDataKey + " Value: " + metaDataValue);
            metaData.put(metaDataKey, metaDataValue);
        }
        return metaData;
    }

    public static void convert(ImageFileReader imageFileReader, String outputImagePath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputImagePath);
    }
}

For SimpleITK tutorial, please refer to these docs.

Share:

Friday, January 7, 2022

Install SimpleITK on Linux/Ubuntu for Java Application

In this tutorial, we are going to learn how to install SimpleITK which is very handy for medical image analysis.

SimpleITK is a simplified programming interface to the algorithms and data structures of the Insight Toolkit (ITK). It supports bindings for multiple programming languages including C++, Python, R, Java, C#, Lua, Ruby, and TCL. These bindings enable scientists to develop image analysis workflows in the programming language they are most familiar with. The toolkit supports more than 15 different image file formats, provides over 280 image analysis filters, and implements a unified interface to the ITK intensity-based registration framework. you can check out official documentation from here.

For the windows system, we can find the prebuilt library where we can simply download and install it. But for Linux os, we need to build by ourselves.

Installation:

Download SimpleItk: 

Clone the SimpleITK from the github.  We can select the desired version from release and download or clone it.


git clone https://github.com/SimpleITK/SimpleITK.git

Now change to the SimpleITK directory:

cd SimpleITK

Install Cmake:

sudo apt-get  install cmake
Install Java:
sudo apt install openjdk-8-jdk

Build SimpleITK

mkdir SimpleITK-build
cd SimpleITK-build
sudo cmake ../SuperBuild

The SuperBuild generates make files that take care of downloading and building ITK. Now start the build

make -j4

Note: Be careful not to run out of memory during the build. We need 4GB of memory per core. For example, if we compile with 4 cores (e.g. make -j4) we need a machine with at least 16GB of RAM.

It will take some time. After the installation, you can find the .so library file which we are going to use. Also, you can find the .jar file for java under the created build folder.

First, we need to load the ITK .jar file in our project and .so file by providing the JVM argument as
Djava.library.path=/path/to/SimpleITKRuntime
Where, /path/to/SimpleITKRuntime is the directory that contains the .so file. Otherwise, you will get the following error
Exception in thread "main" java.lang.UnsatisfiedLinkError: no SimpleITKJava in java.library.path
	at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860)
	at java.lang.Runtime.loadLibrary0(Runtime.java:871)
	at java.lang.System.loadLibrary(System.java:1124)
	at org.itk.simple.SimpleITKJNI.<clinit>(SimpleITKJNI.java:226)
	at org.itk.simple.SimpleITK.readImage(SimpleITK.java:475)
	at simpleitk.SimpleItkTest.main(SimpleItkTest.java:8)

Run the sample Java example

package simpleitk;

import org.itk.simple.Image;
import org.itk.simple.SimpleITK;

public class SimpleItkTest {
    public static void main(String[] args) {
		String inputImagePath = "/path/to/image";
		String outputImagePath = "/path/to/output/image";
        Image image = SimpleITK.readImage(inputImagePath);
        SimpleITK.writeImage(image, outputImagePath);
    }
}

This is a sample example for reading and writing images using simpleITK library.

Note if we are using the Gradle project, then we can add the .so library path as below

bootRun {
    jvmArgs('-Djava.library.path=/opt/SimpleItk/')
}
Where, /opt/SimpleItk/ is the directory which contains the .so file.

Share: