Click here to Skip to main content
15,881,898 members
Articles / Desktop Programming / MFC

Converting a DICOM Image to a Common Graphic Format and Vice Versa with DCMTK and CxImage

Rate me:
Please Sign up or sign in to vote.
4.56/5 (20 votes)
10 Nov 2005CPOL3 min read 345.9K   12.3K   68   52
Converting a DICOM file to BMP/JPG and vice versa
Image 1

Introduction

This article presents a minimum runnable toy application as a starting point to show how to convert a DICOM image to common graphic formats (i.e. BMP, JPG, TIF, etc.) and vice versa. Our sample application is based on two open source libraries, they are DCMTK and CxImage.

Background

The DICOM standard (Digital Imaging and Communications in Medicine) is a standard created by the National Electrical Manufacturers Association (NEMA) to ease the distribution and exchange of medical images, such as CT scans, MRIs and ultrasound. In this article, we will focus on file format conversions. The file format is described in Part 10 of the DICOM standard, which you can download from here[^]. There is also a brief introduction to the file format available here.

DCMTK is a widely used open source implementation of the DICOM standard; it is a collection of C/C++ libraries and applications with complete source code. To compile the sample in this article, you need to download DCMTK first. If you have trouble building the downloaded DCMTK package, please refer to DCMTK for Dummies.

Another library used in this article is CxImage, it is a C++ class that can load, save, display and transform images in a very simple and fast way. It supports almost all the common graphic types, such as BMP, JPG, TIF, PNG, etc. In this article, we will expand this library to support displaying and transforming DICOM images by using the DICOM format encoding/decoding features provided by DCMTK. Download CxImage and follow its usage guidance to make sure it can be compiled successfully on your machine.

Using the Code

We simply derive our CxImageDCM class from the base class CxImage. Doing so enables CxImageDCM class to load and decode common graphics using the methods inherited from the base class. There are three extra methods in the derived class, LoadDCM(…), SaveAsDCM(…), SaveAsJPG(…), they are used to decode, encode and convert a DICOM image, respectively.

C++
//
class CxImageDCM : public CxImage  
{
public:
    CxImageDCM();
    virtual ~CxImageDCM();
    
    bool LoadDCM(const TCHAR* filename);
    bool SaveAsDCM(const TCHAR* filename);
    bool SaveAsJPG(const TCHAR* fileName);

};//

Load DCM

In the sample application, a DICOM image is loaded and decoded with the classes provided by DCMTK, then it is converted to a temporary bitmap file for later manipulations:

C++
//
bool CxImageDCM::LoadDCM(const TCHAR* filename)
{  
    DcmFileFormat *dfile = new DcmFileFormat();
    OFCondition cond = dfile->loadFile(filename, EXS_Unknown,
                      EGL_withoutGL,DCM_MaxReadLength,OFFalse);
    
    if (cond.bad()) {
        AfxMessageBox(cond.text());
    }
    
    E_TransferSyntax xfer = 
            dfile->getDataset()->getOriginalXfer();
    DicomImage *di = new DicomImage(dfile, xfer, 
                         CIF_AcrNemaCompatibility, 0, 1);
    
    if (di->getStatus() != EIS_Normal)
        AfxMessageBox(DicomImage::getString(di->getStatus()));
    
    di->writeBMP("c:\\from_dicom.bmp",24);
    
    return CxImage::Load("c:\\from_dicom.bmp",CXIMAGE_FORMAT_BMP);
    
}//

Converting from DCM

After loading a DCM file, you can save it as a common graphic file using the encoding features provided by CxImage, or you may also use DCMTK’s encoding plugins to do the conversion (however, CxImage supports more formats):

C++
//
bool CxImageDCM::SaveAsJPG(const TCHAR* fileName)
{//you may also use DCMTK's JPG encoding plug-in
    return CxImage::Save(fileName,CXIMAGE_FORMAT_JPG);

}//

Converting to DCM

To convert a common graphic file to a DCM file, you need to load the common graphic first, then set the necessary tag and copy the pixel data to the destination DCM file:

C++
//
bool CxImageDCM::SaveAsDCM(const TCHAR* filename)
{
    CxImageDCM::IncreaseBpp(24);
    char uid[100]; 
    DcmFileFormat fileformat; 
    DcmDataset *dataset = fileformat.getDataset(); 
    dataset->putAndInsertString(DCM_SOPClassUID, 
               UID_SecondaryCaptureImageStorage); 
    /* ... */
    //dataset->putAndInsertUint32(DCM_MetaElementGroupLength,128);
    dataset->putAndInsertUint16(DCM_FileMetaInformationVersion,
                                                          0x0001);
    /* ... */    
    dataset->putAndInsertString(DCM_UID,
        UID_MultiframeTrueColorSecondaryCaptureImageStorage);
    dataset->putAndInsertString(DCM_PhotometricInterpretation,
                                                        "RGB"); 
    //add more tags here
    /* ... */ 
    BYTE* pData=new BYTE[GetHeight()*info.dwEffWidth];
    BYTE* pSrc=GetBits(head.biHeight-1);
    BYTE* pDst=pData;
    for(long y=0; y < head.biHeight; y++){
        memcpy(pDst,pSrc,info.dwEffWidth);
        pSrc-=info.dwEffWidth;
        pDst+=info.dwEffWidth;
    }
    dataset->putAndInsertUint8Array(DCM_PixelData, 
                 pData, GetHeight()*info.dwEffWidth); 
    delete[] pData;
    
    OFCondition status = fileformat.saveFile(filename, 
                           EXS_LittleEndianImplicit,
                           EET_UndefinedLength,EGL_withoutGL); 
    if (status.bad()) 
        AfxMessageBox("Error: cannot write DICOM file ");
    
    return true;     
}//

Points of Interest

In this article, the encoding feature provided by CxImage is used to convert a DICOM image to a JPG file (or other formats that CxImage supports). Actually, DCMTK already has a full-fledged utility called dcmj2pnm to convert a DICOM image to a BMP, PNG, TIF or JPG image. For other formats, that dcmj2pnm doesn’t support, such as GIF, TGA, PCX, WBMP, etc., you may use CxImage’s encoding features to write your own converting functions. One thing that I need to clarify here is that our sample application is only a toy utility to give you a starting point. To write a decent DICOM image converter, you need to consider many more DICOM related options. For more information, you can refer to the implementation of dcmj2pnm. (It is included in the DCMTK source code package.)

From my experience, CxImage is easy to use; it "can load, save, display and transform images in a simple and fast way". However, I find it annoying when you have to derive a new image encoder/decoder from the base class, CxImage. The base class must know all the derived classes to give a polymorphic behavior. Fortunately, in our sample, the derived class CxImageDCM needs only the encoding/decoding functions it inherits from the base class, so I didn’t bother to touch the source code of CxImage.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
China China
liuxiaoweide # gmail.com

Comments and Discussions

 
GeneralRe: help convert DICOM file to bmp, png... Pin
loitls19-Oct-06 9:30
loitls19-Oct-06 9:30 
QuestionConersion to Dicom Pin
Harpreet Kaur18-Sep-06 0:08
Harpreet Kaur18-Sep-06 0:08 
AnswerRe: Conersion to Dicom Pin
lxwde18-Sep-06 2:09
lxwde18-Sep-06 2:09 
GeneralRe: Conersion to Dicom Pin
Harpreet Kaur18-Sep-06 17:57
Harpreet Kaur18-Sep-06 17:57 
GeneralRe: Conersion to Dicom Pin
Christian Graus19-Oct-06 6:10
protectorChristian Graus19-Oct-06 6:10 
GeneralI hardly see my dicom files Pin
Dabe4-Sep-06 7:47
Dabe4-Sep-06 7:47 
GeneralRe: I hardly see my dicom files Pin
Christian Graus19-Oct-06 6:10
protectorChristian Graus19-Oct-06 6:10 
Generalhelp! Pin
loitls11-Aug-06 11:46
loitls11-Aug-06 11:46 
Hi!
I need use DCMTK in visual c++ 6.0, in windows XP.

I install successfully DCMTK, and I run a test used c++,but I need made a test use MFC project, so


How do I use the DCMTK libraries in my application? [MSVC]) in in visual c++ 6.0,



I added the libraries. I selected in the menu of visual: Tools->Options, so I selected the option Ligrary files, and put the path of libraries. But I can't work.

Anybody can I help me, how adde the libraries? or what is the problem?


these is the headeres:

#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dctk.h"

these is a part of code:

void CDcmDlg::OnButton1()
{//Boton abrir dcm


// Visualizar carpetas y archivos "Abrir"
CFileDialog Archivo_dcm( true, "dcm", "*.dcm" );
if (Archivo_dcm.DoModal() != IDOK) return;

//guardando el nombre del archivo

m_StrArchivo = Archivo_dcm.GetFileName();

//trabajando con DCMTK

DcmFileFormat fileformat;
OFCondition status = fileformat.loadFile( m_StrArchivo );

these is the error
}
-------------------Configuration: dcm - Win32 Debug--------------------
Linking...
dcmDlg.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall DcmFileFormat::~DcmFileFormat(void)" (??1DcmFileFormat@@UAE@XZ)
dcmDlg.obj : error LNK2001: unresolved external symbol "public: __thiscall DcmFileFormat::DcmFileFormat(void)" (??0DcmFileFormat@@QAE@XZ)
Debug/dcm.exe : fatal error LNK1120: 2 unresolved externals
Error executing link.exe.

dcm.exe - 3 error(s), 0 warning(s)

Estoy desarrollando ni tesis en visual c++ y me gustaria que si alguien tiene informacion de dICOM me ayude proporcionandomela, ya uqe estoy realizando un visor de imagenes medicas.
gracias

GeneralRe: help! Pin
Christian Graus19-Oct-06 6:11
protectorChristian Graus19-Oct-06 6:11 
Questionhow to set pixels of image Pin
khushi_muskan18-Jun-06 23:01
khushi_muskan18-Jun-06 23:01 
AnswerRe: how to set pixels of image Pin
Christian Graus19-Oct-06 6:12
protectorChristian Graus19-Oct-06 6:12 
AnswerRe: how to set pixels of image [modified] Pin
glibly18-Sep-07 8:54
glibly18-Sep-07 8:54 
GeneralLINK : warning LNK4049: locally defined symbol "_malloc" imported Pin
khushi_muskan12-Jun-06 19:14
khushi_muskan12-Jun-06 19:14 
GeneralRe: LINK : fatal error LNK1104: cannot open file "cximaged.lib" Pin
lxwde10-May-06 3:53
lxwde10-May-06 3:53 
GeneralRe: LINK : fatal error LNK1104: cannot open file "cximaged.lib" Pin
khushi_muskan10-May-06 21:10
khushi_muskan10-May-06 21:10 
GeneralRe: LINK : fatal error LNK1104: cannot open file &quot;cximaged.lib&quot; Pin
lxwde10-May-06 21:47
lxwde10-May-06 21:47 
GeneralRe: LINK : fatal error LNK1104: cannot open file &quot;cximaged.lib&quot; Pin
khushi_muskan10-May-06 23:21
khushi_muskan10-May-06 23:21 
GeneralRe: LINK : fatal error LNK1104: cannot open file &quot;cximaged.lib&quot; Pin
lxwde11-May-06 23:05
lxwde11-May-06 23:05 
GeneralRe: LINK : fatal error LNK1104: cannot open file &quot;cximaged.lib&quot; Pin
khushi_muskan12-May-06 0:56
khushi_muskan12-May-06 0:56 
GeneralRe: LINK : fatal error LNK1104: cannot open file &quot;cximaged.lib&quot; Pin
lxwde12-May-06 1:20
lxwde12-May-06 1:20 
GeneralUnable to run the application Pin
alwittta13-Mar-06 2:18
alwittta13-Mar-06 2:18 
GeneralRe: Unable to run the application Pin
lxwde13-Mar-06 22:01
lxwde13-Mar-06 22:01 
GeneralSome points about conversion to DICOM Pin
marvinbbb15-Nov-05 6:07
marvinbbb15-Nov-05 6:07 
GeneralRe: Some points about conversion to DICOM Pin
lxwde15-Nov-05 14:25
lxwde15-Nov-05 14:25 
GeneralThank you very much! Pin
khler14-Nov-05 15:26
khler14-Nov-05 15:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.