convert DICOM xray images

So a doctor gave me a CD with xray images on it. Turns out they are in DICOM format.
I tried many things to convert them to "normal" png or jpegs, but the path is not that clear.

There are many free DICOM or MRI related tools available on linux, e.g. in the Debian
package feed.

GIMP allegedly supports DICOM, but it doesn't decode the image properly when I open it.
I also tried the raw image data import, which strangely enough has very limited options:
I would need a simple 16bit grayscale import, but only RGB and indexed seem available.

dicomscope displays the images correctly, but it is a Java based tool and appears to have
no "save as jpg" option. I can show the image and take a screenshot, but that sucks if
the DICOM image is in fact larger than my screen resolution.

In the end I came up with this convoluted way to get a plain PNG file that is easy to
work with in GIMP and on the net:

Install dcmtk from debian package:

  sudo apt-get install dcmtk

All I need is *dcmdump*, and all this does is strip the header off the raw pixel data.
If I had a way to find out the header size, I wouldn't need this at all.
To dump the raw pixels, call:

  dcmdump path/to/dicom/file +W ./

This dumps some description to the terminal and writes a file to the current folder.
From the textual output I gather the image size:

  (0028,0010) US 3460                                     #   2, 1 Rows
  (0028,0011) US 2868                                     #   2, 1 Columns

3460 rows and 2868 columns means an image size of 2868x3460 (columns is the width)

I also note the pixel format:

  (0028,0100) US 16                                       #   2, 1 BitsAllocated
  (0028,0101) US 12                                       #   2, 1 BitsStored
  (0028,0102) US 11                                       #   2, 1 HighBit

BitsAllocated = 16 tells me each pixel has 16 bits, i.e. two bytes. The rest says
that only 12 bits of the range are actually used.

To convert this raw image to a PNG, I install ImageMagick, also from a Debian package,
and use its convert tool:

  convert -depth 16 -size 2868x3460 gray:I0000001.0.raw -auto-level I0000001.0.png

Explained:

  "-depth 16" corresponds to BitsAllocated.
  "-size 2868x3460" comes from Columns x Rows.
  "gray:" says the image is in grayscale, with only one color value per pixel.
  "I0000001.0.raw" is the file output by dcmdump with the "+W ." command.
  "-auto-level" makes it so that the brightness range is autodetected, i.e. the
                12 used bits are stretched out to give a nice image.
  "I0000001.0.png" is the output file I choose, and indicated PNG file format.

I've put all this in a shell script that also extracts image size, body part and date from the
DICOM dump to form a sensible file name.
937 b convert_dicom.sh 2017-06-13 22:21
login 2017-06-13 22:23