Category: DICOM

  • DICOM 파일 수정 후 업로드

    DICOM을 제대로 취급하는 곳이라면 DICOM 파일을 생성시에 UID를 제대로 만들기 때문에 중복되는 일이 없다. 그런데 이전에 언급한 가짜 DICOM 이미지 파일을 만들기 위해서는 UID 를 적절하게 변경해 주어야 한다. 1명의 환자에서 2개의 검사가 시행되었는데 UID를 수정해 주지 않으면 2번째 입력한 것부터 입력이 되지 않는다.

    여러 시행 착오 끝에 Orthanc 에서는 StudyInstanceUID를 고유하게 지정해 주면 된다는 것을 알게 되었다. DICOM의 UID는 보통 숫자와 마침표로 구성되어 있지만 사실 어떤 형식이라도 상관 없다. 그래서 UUID를 이용하였다.

    for idx in range(len(echo_result)):
    
        UUID = str(uuid.uuid4())
    
        ds = pydicom.dcmread('/root/US_ECHO_TEMPLATE.dcm')
        ds.StudyInstanceUID = UUID
    
        ds.save_as("/tmp/RAW/echo_new.dcm")
        os.system("storescu rcc02.work 4242 /tmp/RAW/echo_new.dcm")
    
  • Downsize DICOM file

    심장 초음파 결과가 Orthanc에 없다보니 결과 처리할 때 항상 따로 해주어야 하는 불편함이 있었다. 그렇다고 심장 초음파 이미지를 DICOM 서버로 등록시켜봐야 심장 초음파 결과지 내용을 볼 수 있는 것도 아니고, 이미지 1장당 18메가 정도 하는데 이것이 수십장 씩 있다 보니 경제적이지도 않다. 그래서 현재 필요한 것은 EF 뿐이니 이것을 분석에 사용하지 않는 DICOM tag로 입력시키고, 저해상도 이미지 파일을 등록시키는 식으로 하기로 했다.

    # authors : Guillaume Lemaitre <g.lemaitre58@gmail.com>
    # license : MIT
    
    import pydicom
    from pydicom.data import get_testdata_file
    
    print(__doc__)
    
    # FIXME: add a full-sized MR image in the testing data
    filename = get_testdata_file('MR_small.dcm')
    ds = pydicom.dcmread(filename)
    
    # get the pixel information into a numpy array
    data = ds.pixel_array
    print('The image has {} x {} voxels'.format(data.shape[0],
                                                data.shape[1]))
    data_downsampling = data[::8, ::8]
    print('The downsampled image has {} x {} voxels'.format(
        data_downsampling.shape[0], data_downsampling.shape[1]))
    
    # copy the data back to the original data set
    ds.PixelData = data_downsampling.tobytes()
    # update the information regarding the shape of the data array
    ds.Rows, ds.Columns = data_downsampling.shape
    
    # print the image information given in the dataset
    print('The information of the data set after downsampling: \n')
    print(ds)

    downsampling 부분을 보면 이미지 파일에서 일정 간격으로 (여기서는 1/8로 줄이기 위하여) 값들을 선택하여 크기 자체를 줄이고 .tobytes 를 이용해서 변환하는 것을 볼 수 있다. 그래서 그렇게 했다. 난 용량이 작은 것이 필요하니 :8대신에 :200으로 했다.

    ds = pydicom.dcmread('/root/US_ECHO_TEMPLATE.dcm')
    data = ds.pixel_array
    data_downsampling = data[:,::200, ::200,:]
    ds.PixelData = data_downsampling.tobytes()
    _, ds.Rows, ds.Columns,_ = data_downsampling.shape
    ...
    ds.save_as("/tmp/RAW/echo_new.dcm")
    os.system("storescu rcc02.work 4242 /tmp/RAW/echo_new.dcm")
  • DCMTK  

    DICOM 서버에 파일을 직접 전송해야 할 경우가 있다. 이럴 경우에 사용하는 패키지이다.

    apt install dcmtk

    파일을 전송할 때 사용하는 프로그램은 storescu 이다.

    storescu [options] peer port dcmfile-in...

    사용방법은 매우 단순하다. 나의 경우에는 다음과 같이 사용한다.

    storescu rcc02.work 4242 /tmp/RAW/echo_new.dcm
  • Orthanc

    최근 버전 업그레이드 됨에 따라서 원격 접속이 매우 제한된 것 같다. HTTPS를 지원하지 못하면 원격 접속을 이용할 수 없게 된다. Orthanc 에서는 리버스 프록시와 자체적으로 지원하는데 자체적으로 지원하는 방법을 이용을 아무리 해봐도 안되었다. 그래서 익숙한 nginx 를 이용하여 리버스 프록시로 구현하였다.

    Web 화면보다는 Rest API가 더 중요하기 때문이 이를 이용할 수 있도록 설정을 하는 것을 목표로 했다.

    늘 하듯이 도커 이미지를 이용하여 컨테이너를 생성하고 orthanc와 필요한 패키지들을 설치한다. Orthanc 도움말을 보면 성능을 위해서는 SQLite가 아닌 MySQL이나 PostgreSQL을 이용하라고 한다. PostgreSQL을 좋아하기 때문에 이를 이용하기 위해서 설치한다.

    sudo docker run -it -p 8042:8042 -p 4242:4242 -p 443:443 --name orthanc --restart always -v /home/ysrcc/ext:/root/OrthancStorage debian
    
    echo 'Acquire::http::Proxy "http://rcc.work:3142";' > /etc/apt/apt.conf
    rm -rf /etc/localtime
    ln -s /usr/share/zoneinfo/Asia/Seoul /etc/localtime 
    apt -y update && apt -y upgrade
    
    apt -y install locales
    sed -i 's/^# *\(en_US.UTF-8\)/\1/' /etc/locale.gen
    locale-gen
    
    apt -y install orthanc orthanc-postgresql \
            procps nano ftp curl postgresql nginx sudo

    웹 접속에서는 문제가 생기지 않는데 curl 명령어를 이용할 경우 주소가 일치하지 않으면 인증서와 관련된 오류가 생긴다. -k 를 이용하여 검증을 안함으로 해도 되기는 하지만, 정석대로 인증서를 이용하는 것을 전제로 한다.

    인증서는 다음과 같이 생성한다.

    openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /tmp/private.key -out /tmp/certificate.crt -subj "/CN=10.10.10.171"
    cat /tmp/private.key /tmp/certificate.crt > /tmp/certificate.pem

    /etc/orthanc/orthanc.json 에서 다음의 내용을 수정한다. 리버스 프록시를 이용하여 접속을 할 것이기 때문에 설정을 건드릴 부분이 별로 없다.

    "StorageDirectory" : "/root/OrthancStorage",
    ...
    "DefaultEncoding" : "Korean",
    
    or
    
    sed -i 's/Latin1/Korean/g' /etc/orthanc/orthanc.json

    /etc/orthanc/postgresql.json 파일에서 다음을 수정한다. username과 password 부분을 수정한다.

    "EnableIndex" : true,
    "Username" : "postgres",
    "Password" : "postgres",

    설정을 했으면 PostgreSQL 에서도 수정해야 한다는 것을 알 수 있다.

    $ service postgresql start
    $ sudo -u postgres psql
    # \password postgres
    # create database orthanc_db;
    # \q

    nginx.conf 파일에서 gzip off로 설정한다. 미리 작성한 파일을 가져와도 된다.

    http {
          ...
          gzip off;
          ...
    }
    
    or
    
    curl -s http://rcc.work:3143/nginx_orthanc.conf > /etc/nginx/nginx.conf

    /etc/nginx/sites-available/default 를 다음과 같이 수정한다.

    server {
            listen 80 default_server;
            listen [::]:80 default_server;
    
            listen 443 ssl default_server;
            listen [::]:443 ssl default_server;
            ssl_certificate /tmp/certificate.crt;
            ssl_certificate_key /tmp/private.key;
            ssl_protocols TLSv1.3;
            ssl_prefer_server_ciphers on;
            ssl_ciphers "TLS-AES-128-GCM-SHA256:ECDHE-RSA-AES128-SHA256";
    
            root /var/www/blog;
    
            index index.html index.htm index.nginx-debian.html;
    
            server_name _;
    
            location / {
                    proxy_pass http://localhost:8042;
                    proxy_set_header HOST $host;
                    proxy_set_header X-Real-IP $remote_addr;
            }
    
    or
    
    curl -s http://rcc.work:3143/default_orthanc > /etc/nginx/sites-available/default

    컨테이너가 예기치 않게 종료될 수 있으므로 .bashrc 에 다음을 추가해서 실행시에 문제가 없도록 한다.

    echo "cd /root" >> /root/.bashrc
    echo "service postgresql start" >> /root/.bashrc
    echo "service nginx start" >> /root/.bashrc
    echo "Orthanc /etc/orthanc/ &" >> /root/.bashrc