• Stars
    star
    170
  • Rank 223,357 (Top 5 %)
  • Language
    Python
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Converts medical images to more displayable formats, e.g. NIfTI to jpg.

med2image 2.6.6

Quick Overview

  • Convert DICOM or NIfTI inputs to jpg or png outputs.

Overview

med2image is a simple Python3 utility that converts medical image formatted files (such as DICOM and NifTI) to more web friendly ones, such as png and jpg.

Currently, NIfTI and DICOM input formats are understood, while any graphical output type that is supported by matplotlib can be generated.

At present med2image does not convert DICOM to NifTI, but this is planned for a future release.

Dependencies

Make sure that the following dependencies are installed on your host system (or even better, a python3 virtual env):

  • pfmisc : (a general miscellaneous module for color support, etc)
  • nibabel : (to read NIfTI files)
  • pydicom : (to read DICOM files)
  • matplotlib : (to save data in various image formats)
  • pillow : (to save data in jpg format)

Assumptions

This document assumes UNIX conventions and a bash shell. The script should work fine under Windows, but we have not actively tested on that platform -- our dev envs are Linux Ubuntu and macOS.

Installation

Python module

One method of installing this script and all of its dependencies is by fetching it from PyPI.

pip3 install med2image

Should you get an error about python3-tk not installed, simply do (for example on Ubuntu):

sudo apt-get update
sudo apt-get install -y python3-tk

Docker container

We also offer a docker container of med2image as a ChRIS-conformant platform plugin here https://github.com/FNNDSC/pl-med2img (see also the closely related https://github.com/FNNDSC/pl-dcm2img that performs conversions down a directory tree recursively) -- please that reference for information on running the dockerized container. The containerized version exposes a similar CLI and functionality as this module.

How to Use

med2image needs at a minimum (some of) the following required command line arguments:

  • -i | --inputFile <inputFile> : Input file to convert. Typically a DICOM file or a NifTI volume.
  • --inputFileSubStr <substr> : A short hand trick to specify the inputFile. By only specifying a sub string that identifies the file, the first file in the inputDir that contains the sub string is tagged as the inputFile. This saves a user from needing to specify long and cumbersome file names, esp in the case of many DICOM filenames.
  • -d | --outputDir <outputDir> : The directory to contain the converted output image files.

Example:

# Convert a NifTI file 'vol.nii' to JPEG and store
# the results in a dirctory called 'out'.
# The 'out' dir will contain a set of JPEG
# images of form 'output-sliceXXX.jpg'.

med2image -i vol.nii -d out
# Convert a DICOM file 'file.dcm' to JPEG and store
# the results in a dirctory called 'out'.
# The 'out' dir will contain a set of JPEG
# images of form 'output-sliceXXX.jpg'.

# NOTE! If the directory containing 'file.dcm' contains
# multiple DICOM files, *ALL* of these will be converted
# to JPEG. See later for only converting a *single*
# DICOM file.

med2image -i file.dcm -d out

NIfTI details

NOTE: NifTI is typically a volume format. One NIfTI (.nii) volume contains multiple slices. Converting a NifTI volume results in multiple .jpg or .png results.

  • NIfTI input data can be in 2 forms:
    • 3D : The .nii volume contains multiple 2D slices
    • 4D : The .nii file contains multiple 3D volumes that each contain multiple 2D slices
  • med2image understands both types of inputs.

Pull NIfTI

The input should be a NIfTI volume with extension .nii. We provide a sample volume here https://github.com/FNNDSC/SAG-anon-nii.git

  • Clone this repository (SAG-anon-nii) to your local computer.
git clone https://github.com/FNNDSC/SAG-anon-nii.git

Convert NIfTI

NOTE:

  • If --outputDir | -d is not provided, outputs are created in the current directory.
  • if --sliceToConvert is not provided, all the slices of the .nii volume are converted.

Both 3D and 4D NIfTI input data are understood. In the case of 4D NIfTI, a specific frame (--frameToConvert) can be additionally provided in conjunction with a specific slice index. Conversion options include:

  • all slices (default)
  • middle slice only, with the CLI --sliceToConvert m
  • someSpecificSlice, with the CLI --sliceToConvert <N>

CASE 1: All slices in a volume

Now, let's convert all slices in the input NIfTI volume SAG-anon.nii, and save the results to a nested subdir nifti-results/all-slices. We'll use as output file name stem sample and convert to jpg.

Assuming you have cloned the SAG-anon-nii repo and assuming that you have med2image on your UNIX shell path,

med2image -i SAG-anon-nii/SAG-anon.nii                 \
          -d nifti-results/all-slices                  \
          -o sample.jpg -s -1

or equivalently and more verbosely,

med2image --inputFile SAG-anon-nii/SAG-anon.nii         \
          --outputDir nifti-results/all-slices          \
          --outputFileStem sample  --outputFileType jpg \
          --sliceToConvert -1

resulting in

nifti-results/all-slices/sample-slice000.jpg
nifti-results/all-slices/sample-slice001.jpg
nifti-results/all-slices/sample-slice002.jpg
nifti-results/all-slices/sample-slice003.jpg
...
nifti-results/all-slices/sample-slice188.jpg
nifti-results/all-slices/sample-slice189.jpg
nifti-results/all-slices/sample-slice190.jpg
nifti-results/all-slices/sample-slice191.jpg

Note that even if the nested output directory structure does not exist, med2image will create it for you.

Case 2: Convert only a single slice

Often times, you might only want to convert the "middle" slice in a volume (for example to generate a representative thumbnail of the volume). To do this, simply specify an m to --sliceToConvert (or -s m):

med2image -i SAG-anon-nii/SAG-anon.nii    \
          -d nifti-results/middle-slice   \
          -o sample --outputFileType jpg  \
          --sliceToConvert m

resulting in

nifti-results/middle-slice/sample-slice096.jpg

Alternatively a specific slice index can be converted. Use

med2image -i SAG-anon-nii/SAG-anon.nii    \
          -d nifti-results/specific-slice \
          -o sample                       \
          --outputFileType jpg            \
          --sliceToConvert 20

to convert only the 20th slice of the volume.

resulting in

nifti-results/specific-slice/sample-slice020.jpg

DICOM

NOTE: One DICOM (.dcm) file typically corresponds to one .png or .jpg file (slice).

Pull DICOM

The input should be a DICOM file usually with extension .dcm

We provide a sample directory of .dcm images here FNNDSC/SAG-anon. (https://github.com/FNNDSC/SAG-anon.git)

  • Clone this repository (SAG-anon) to your local computer.
git clone https://github.com/FNNDSC/SAG-anon.git

Convert DICOM

NOTE:

  • If --outputDir | -d is not provided, any output(s) are created in the current directory.
  • if --sliceToConvert argument is not specified and if mutiple dcm files are contained in the input directory with the DICOM input, then all the .dcm files are converted.
  • alternatively, specifying a --convertOnlySingleDICOM will only convert the DICOM file specified with the --inputFile flag.

Convert all DICOMS in a directory/series

To convert all the DICOM files in a directory, simply specify either --sliceToConvert -1 (or just leave out the argument/value pair completely):

med2image -i SAG-anon/0001-1.3.12.2.1107.5.2.19.45152.2013030808110258929186035.dcm   \
          -d dicom-results/all-slices      \
          -o sample                        \
          --outputFileType jpg             \
          --sliceToConvert -1

# OR equivalently

med2image -i SAG-anon/0001-1.3.12.2.1107.5.2.19.45152.2013030808110258929186035.dcm  \
          -d dicom-results/all-slices      \
          -o sample                        \
          --outputFileType jpg

resulting in

dicom-results/all-slices/sample-slice000.jpg
dicom-results/all-slices/sample-slice001.jpg
dicom-results/all-slices/sample-slice002.jpg
dicom-results/all-slices/sample-slice003.jpg
...
dicom-results/all-slices/sample-slice188.jpg
dicom-results/all-slices/sample-slice189.jpg
dicom-results/all-slices/sample-slice190.jpg
dicom-results/all-slices/sample-slice191.jpg

Convert a single DICOM file

Mostly, you'll probably only want to convert the "middle" slice in a DICOM directory (for example to generate a representative thumbnail of the directory). To do this, simply specify a m to --sliceToConvert (or -s m)

med2image -i SAG-anon/0001-1.3.12.2.1107.5.2.19.45152.2013030808110258929186035.dcm    \
          -d dicom-results/middle-slice  \
          -o sample --outputFileType jpg \
          --sliceToConvert m

resulting in

dicom-results/middle-slice/sample.jpg

Note that even though the first slice in the SAG-anon directory was supplied to the script, med2image nonetheless found and converted the middle slice in the directory.

Alternatively a specific slice index can be converted. Use

med2image -i SAG-anon/0001-1.3.12.2.1107.5.2.19.45152.2013030808110258929186035.dcm     \
          -d dicom-results/specific-slice  \
          -o sample --outputFileType jpg   \
          --sliceToConvert 20

resulting in

dicom-results/specific-slice/sample.jpg

Again, even though the first slice was supplied to the script, med2image selected and converted the 20th slice in the directory.

Special Cases

For DICOM data, the <outputFileStem> can optionally be set to the value of an internal DICOM tag. The tag is specified by preceding the tag name with a percent character %, so

  • -o %PatientID

will use the DICOM PatientID to name the output file. Note that special characters (like spaces) in the DICOM value are replaced by underscores '_'.

med2image -i SAG-anon/0001-1.3.12.2.1107.5.2.19.45152.2013030808110258929186035.dcm   \
          -d dicom-results/tags         \
          -o %PatientID.jpg -s m

This will create the following file in the tags sub-directory within dicom-results directory.

dicom-results/tags/1449c1d.jpg

Multiple tags can be specified, for example

  • -o %PatientName%PatientID%ProtocolName

and the output filename will have each DICOM tag string as specified in order, connected with dashes.

med2image -i SAG-anon/0001-1.3.12.2.1107.5.2.19.45152.2013030808110258929186035.dcm \
          -d dicom-results/tags                        \
          -o %PatientName%PatientID%ProtocolName.jpg   \
          -s m

This will create the following file in the tags sub-directory within dicom-results directory.

dicom-results/tags/anonymized-1449c1d-SAG_MPRAGE_220_FOV.jpg

Multiple Direction Reslicing

By default, only the slice (or slices) in the acquisition direction are converted. However, by passing a --reslice to the script, all dimensions are converted. Since the script does not know the anatomical orientation of the image, the directions are simply labeled x, y, and z.

The z direction is the original acquistion (slice) direction, while x and y correspond to planes normal to the row and column directions. Converted images are stored in subdirectories labeled x, y, and z.

No interpolation in the x and y directions is performed. This often results in ugly images!

NOTE: In case of DICOM images, the --reslice option will work only if all slices in the directory are converted, i.e. converting with --sliceToConvert -1

Special Operations

med2image also supports some very basic image processing through a --func <functionName> CLI, which applies some canned transformation on the image. Currently supported is

--func invertIntensities

which simply inverts the contrast intensity of the source image. Additional functions are planned for future releases.

Command Line Arguments

[-i|--inputFile <inputFile>]
Input file to convert. Typically a DICOM file or a nifti volume.

[--inputFileSubStr <substr>]
As a convenience, the input file can be determined via a substring
search of all the files in the <inputDir> using this flag. The first
filename hit that contains the <substr> will be assigned the
<inputFile>.

This flag is useful is input names are long and cumbersome, but
a short substring search would identify the file. For example, an
input file of

   0043-1.3.12.2.1107.5.2.19.45152.2013030808110149471485951.dcm

can be specified using ``--inputFileSubStr 0043-``

[-I|--inputDir <inputDir>]
If specified, a directory containing the <inputFile>. In this case
<inputFile> should be specified as relative to <inputDir>.

[-d|--outputDir <outputDir>]
The directory to contain the converted output image files.

-o|--outputFileStem <outputFileStem>
The output file stem to store conversion. If this is specified
with an extension, this extension will be used to specify the
output file type.

SPECIAL CASES:
For DICOM data, the <outputFileStem> can be set to the value of
an internal DICOM tag. The tag is specified by preceding the tag
name with a percent character '%', so

    -o %ProtocolName

will use the DICOM 'ProtocolName' to name the output file. Note
that special characters (like spaces) in the DICOM value are
replaced by underscores '_'.

Multiple tags can be specified, for example

    -o %PatientName%PatientID%ProtocolName

and the output filename will have each DICOM tag string as
specified in order, connected with dashes.

[--convertOnlySingleDICOM]
If specified, will only convert the single DICOM specified by the
'--inputFile' flag. This is useful for the case when an input
directory has many DICOMS but you specifially only want to convert
the named file. By default the script assumes that multiple DICOMS
should be converted en mass otherwise.

[--preserveDICOMinputName]
If specified, use the input DICOM name as the stem of the output
filename, with the specified type ('jpg' or 'png') as the extension.
In the case where [--reslice] is additionally specified, only the
slice or 'z' direction will preserve original DICOM names.

[-t|--outputFileType <outputFileType>]
The output file type. If different to <outputFileStem> extension,
will override extension in favour of <outputFileType>.

[-s|--sliceToConvert <sliceToConvert>]
In the case of volume files, the slice (z) index to convert. Ignored
for 2D input data. If a '-1' is sent, then convert *all* the slices.
If an 'm' is specified, only convert the middle slice in an input
volume.

[-f|--frameToConvert <sliceToConvert>]
In the case of 4D volume files, the volume (V) containing the
slice (z) index to convert. Ignored for 3D input data. If a '-1' is
sent, then convert *all* the frames. If an 'm' is specified, only
convert the middle frame in the 4D input stack.

[--showSlices]
If specified, render/show image slices as they are created.

[--rot <3DbinVector>]
A per dimension binary rotation vector. Useful to rotate individual
dimensions by an angle specified with [--rotAngle <angle>]. Default
is '110', i.e. rotate 'x' and 'y' but not 'z'. Note that for a
non-reslice selection, only the 'z' (or third) element of the vector
is used.

[--rotAngle <angle>]
Default 90 -- the rotation angle to apply to a given dimension of the
<3DbinVector>.

[--func <functionName>]
Apply the specified transformation function before saving. Currently
support functions:

    * invertIntensities
      Inverts the contrast intensity of the source image.

[--reslice]
For 3D data only. Assuming [x,y,z] coordinates, the default is to save
along the 'z' direction. By passing a --reslice image data in the 'x'
and 'y' directions are also saved. Furthermore, the <outputDir> is
subdivided into 'slice' (z), 'row' (x), and 'col' (y) subdirectories.

[-x|--man]
Show full help.

[-y|--synopsis]
Show brief help.

[--verbosity <level=1>]
Control how chatty med2image is. Set to '0' for blissful silence, '1'
for sane progress and '3' for full information.

More Repositories

1

pypx

Python wrapper to interact with a PACS (based off DCMTK and PyDicom)
Python
81
star
2

ChRIS_ui

UI for ChRIS
TypeScript
53
star
3

ChRIS_store_ui

UI for the ChRIS Store
JavaScript
49
star
4

ubuntu-python3

Source for a slim Ubuntu-based Python3 image
Dockerfile
44
star
5

ChRIS_ultron_backEnd

Backend for ChRIS
Python
31
star
6

matlab

Matlab Projects and Snippets
MATLAB
25
star
7

pman

A process management system written in python
Python
23
star
8

CHRIS_docs

Documentation for CHRIS
Shell
11
star
9

ChRIS_store

Backend for ChRIS plugin apps store
Python
11
star
10

ami-viewer

AMI Viewer Polymer element
HTML
11
star
11

pfcon

Data / Compute manager
Python
9
star
12

chrisreloaded

Python
9
star
13

ChRIS_ultron_frontEnd

Front end for ChRIS Ultron
HTML
9
star
14

pypx-repack-codecarbon-datalad

Comparing energy efficiency of a Rust rewrite of a program for DICOM management.
Python
7
star
15

medview

Standalone web-based medical data viewer
JavaScript
7
star
16

cookiecutter-chrisapp

A cookiecutter template for Chris app plugins
Python
7
star
17

miniChRIS-docker

Easiest way to run ChRIS locally.
Shell
7
star
18

fnndsc

Mono repo for FNNDSC's Javascript projects.
JavaScript
6
star
19

viewerjs

A reusable medical image javascript viewer
JavaScript
6
star
20

ami-loader

HTML
5
star
21

cube-design

All CUBE related designs
5
star
22

website-old

ChRIS Project Website
JavaScript
5
star
23

swarm

A swarm cluster manager based on the Python docker API
Python
4
star
24

pl-fetal-surface-extract

Inner cortical plate surface extraction using CIVET
Python
4
star
25

scripts

Various Scripts
Shell
4
star
26

KWWidgets

KWWidgets migrated to git for ease
C++
4
star
27

fetalMoco

Fetal Motion Reconstruction
C++
4
star
28

gcjs

Collaboration module based on Google Drive Realtime Api
JavaScript
4
star
29

TrackVisUtilities

Some handy utilities for working with TrackVis (*.trk) files
4
star
30

pl-infantfs

Infant FreeSurfer
Python
4
star
31

fmjs

File manager that implements file reading and saving operations on diverse cloud filesystems.
JavaScript
4
star
32

oxidicom

DICOM receiver for ChRIS backend
Rust
3
star
33

cjs

the collaboration module!
JavaScript
3
star
34

_common

The FNNDSC common library
Python
3
star
35

conda-multiarch

Multi-architecture docker images with Conda
Dockerfile
3
star
36

dck-dicom-listener

Shell
3
star
37

mi2b2

Medical image viewer for mi2b2
JavaScript
3
star
38

projectman

FNNDSC project manager
3
star
39

pl-med2img

A ChRIS DS plugin to convert from medical image data files to display-friendly formats (like png and jpg).
Python
3
star
40

data

3
star
41

python-poetry

Container images for poetry
Dockerfile
3
star
42

fetal-brain-segmentation

Jupyter Notebook
3
star
43

playwright-test-coverage-native

Extends Playwright test to measure code coverage using Playwright's built-in features
JavaScript
3
star
44

tcl_misc

Miscellaneous tcl packages -- command line interpreter, "class" analogue, tape device controller.
Tcl
2
star
45

pfdo_med2image

Perform a med2image at multiple locations in a directory tree
Python
2
star
46

tinycudann-docker-build

Dockerfile
2
star
47

pl-fshack

A quick "hack" plugin for freesurfer
Python
2
star
48

pl-surfaces-fetus

Extract surface meshes from in-utero MRI
Perl
2
star
49

python-chrisclient

A python client for the ChRIS API.
Python
2
star
50

polyami

Polymer-styled AMI
HTML
2
star
51

mdh_apps

Medical Data Header Apps
2
star
52

gpu

GPU Coding
C
2
star
53

dmd2b

DICOM Meta Data DataBase
Python
2
star
54

dmd2b-dock

A dock around the dmd2b project
2
star
55

dmd2b_web

An search program for DICOM database (next step : make the search dynamic)
Python
2
star
56

fsjs

FreeSurfer javascript related tools
JavaScript
2
star
57

wheels

The nipypeWheels interface for easy pypelining..
Python
2
star
58

cortical-thickness

Cortical surface extraction and calculation of cortical thickness. Process made using an initial deeplearning segmentations of GM and WM. It implements a method of homotopic skeletonizatios to find CSF in the sulcus and another method of soft clustering is implemented for intensity refinement of GM boundary.
Python
2
star
59

rendererjs

A renderer window JS object to render and visualize medical images
JavaScript
2
star
60

meg.babymri.org

HTML
1
star
61

thbarjs

A thumbnail bar
JavaScript
1
star
62

pl-freesurfer_simplereport

A ChRIS DS plugin that can generate a simple report (in several formats) of a FreeSurfer annotation/segmentation volume
Python
1
star
63

centos-python3

Source for a slim Centos-based Python3 image
1
star
64

gridautomaton

Cellular Automaton Grid: Simulates cellular automaton evolution on simple grids
Python
1
star
65

pybicpl

Python interface for basic MNI .obj file format. Supports read, write, and calculations on a vertex neighbor graph.
Python
1
star
66

chris-utils

A reusable ChRIS utility JS library
JavaScript
1
star
67

python-chrisapp-template

Batteries-included template for Python ChRIS plugins.
Shell
1
star
68

ChRIS_on_MOC

A collection of wiki to deploy/access ChRIS services on Mass Open Cloud
1
star
69

fetal

The fetal atlas explorer based on Slice:Drop.
CSS
1
star
70

WebMeg.net

The web content for WebMeg.net/.org
JavaScript
1
star
71

delayedpuberty.babymri.org

delayedpuberty.babymri.org
HTML
1
star
72

Fetal_Brain_MRI_Reconstruction_Pipeline

Fetal brain reconstruction pipeline
1
star
73

pl-to31

Fetal brain MRI alignment using FSL FLIRT
Shell
1
star
74

ChRIS_API

The API specification of ChRIS
Python
1
star
75

hplocons-wine

Run HPLOCONS in a container using Podman or Docker.
Dockerfile
1
star
76

aiochris

ChRIS python client built on aiohttp
Python
1
star
77

pypx-listener

A DICOM instance handler for storescp which reorganizes incoming DICOM files for the pypx+pfdcm+ChRIS ecosystem.
Rust
1
star
78

pfioh

Path File IO Handler
Python
1
star
79

pfdicom

A "base" class module common to a family of DICOM processing.
Python
1
star
80

miniChRIS-podman

Run ChRIS using Podman or Kubernetes
Shell
1
star
81

cloneGHO

Convenience script to clone a github organization
Python
1
star
82

centroid_cloud

Determines centroid of cluster of points, and shaped areas-of-significance
Python
1
star
83

ami-data

1
star
84

ChRIS_collab

Red Hat / BU / MOC collaboration page
Roff
1
star
85

cutl

ChRIS utility library in javascript
JavaScript
1
star
86

cruntesting

A stripped down ChRIS workflow that is used for testing crun remote scheduling and behaviour
Python
1
star
87

ChRIS_contributor-support

Repo for collecting docs, help, etc to get new contribs up and helping with the ChRIS project
1
star
88

pman_fileio

REST API for file io in pman
Python
1
star
89

fyborg

The ultimate scalar mapping framework for TrackVis (.trk) files.
Python
1
star
90

pfurl

Path-File-URL client.
Python
1
star
91

SurfView

A FreeSurfer surface viewer based on XTK.
JavaScript
1
star
92

C_utils

Simple C++ Utilities.
C++
1
star
93

pl-mricnn_predict

An app to predict segmented brain MRI images from a given unsegmented brain MRI
Python
1
star
94

rav

Radiology Viewer
HTML
1
star
95

web

Web-based Projects
JavaScript
1
star
96

pl-s3retrieve

A Chris 'ds' plugin to retrieve file/folders from Amazon S3 service.
Python
1
star
97

pl-fetal-brain-mask

Automatic masking of fetal brain images using deep learning
Python
1
star
98

babybrain

CSS
1
star
99

chrisapp

The base module for Chris' plugins
Python
1
star
100

pl-image_textRemove

A chris plugin to identify and remove text from images
Python
1
star