<jupyter_start><jupyter_text>第４章　医用画像の標準規格DICOMを理解する 4.1 はじめに<jupyter_code>from google.colab import drive
drive.mount('/content/drive')
!pip install pydicom<jupyter_output>Collecting pydicom
[?25l  Downloading https://files.pythonhosted.org/packages/d3/56/342e1f8ce5afe63bf65c23d0b2c1cd5a05600caad1c211c39725d3a4cc56/pydicom-2.0.0-py3-none-any.whl (35.4MB)
[K     |████████████████████████████████| 35.5MB 1.3MB/s 
[?25hInstalling collected packages: pydicom
Successfully installed pydicom-2.0.0<jupyter_text>Memo  ・PydicomのインストールはColaboratoryのインスタンス起動するたびに行う必要がある 4.1.1<jupyter_code>import pydicom
from matplotlib import pyplot as plt

dcmfnm="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/Brain01"

ds=pydicom.dcmread(dcmfnm)

print(ds)<jupyter_output>Dataset.file_meta -------------------------------
(0002, 0000) File Meta Information Group Length  UL: 204
(0002, 0001) File Meta Information Version       OB: b'\x00\x01'
(0002, 0002) Media Storage SOP Class UID         UI: CT Image Storage
(0002, 0003) Media Storage SOP Instance UID      UI: 1.2.392.200036.9116.172.16.31.10.1613469034.1289543971.629951
(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian
(0002, 0012) Implementation Class UID            UI: 1.2.392.200036.9116.2.6.1.100
(0002, 0013) Implementation Version Name         SH: 'TM_CT_CMW_V3.00'
-------------------------------------------------
(0008, 0008) Image Type                          CS: ['ORIGINAL', 'PRIMARY', 'AXIAL']
(0008, 0016) SOP Class UID                       UI: CT Image Storage
(0008, 0018) SOP Instance UID                    UI: 1.2.392.200036.9116.2.6.1.16.1613469034.1289543971.629951
(0008, 0020) Study Date                          DA: '20101112'
(0008, 0021) Series Date         [...]<jupyter_text>Memo  ・前の4桁：グループ番号  ・後の4桁：エレメント番号 4.1.2<jupyter_code>pn=ds.PatientName
wc=ds.WindowCenter
ww=ds.WindowWidth
img=ds.pixel_array
print("PatientName:",pn)
print("wc=",wc)
print("ww=",ww)
print(type(img))<jupyter_output>PatientName: Joho^Taro
wc= 40
ww= 80
<class 'numpy.ndarray'><jupyter_text>Memo  ・キーワードには空白を含まないこと 4.1.3<jupyter_code>max=wc+ww/2
min=wc-ww/2
print("max=",max)
print("min=",min)

plt.imshow(img,cmap='gray',vmax=max,vmin=min)
plt.show()<jupyter_output>max= 80.0
min= 0.0<jupyter_text>4.2 DICOMとPydicom Memo  ・VR(Value Representation)  　値表現という  　VF(Value Field)に格納されている情報の形式や長さを2文字  　(2バイト)のコードで表現  ・VL(Value Length)  　VFに記載されている情報の長さが記述されている  ・IOD(Information Object Definition)  　データエレメントの構成はモダリティごとに必要な情報の集合に  　より組み合わされる  ・SOPインスタンスUIDの変更はリスクを伴うことを十分に認識   4.2.1<jupyter_code>import os
import pydicom
from pydicom.tag import Tag

dcmfnm="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/Brain01"
ds=pydicom.dcmread(dcmfnm)

print("SOP Instance UID   :",Tag("SOPInstanceUID"), ds.SOPInstanceUID)
print("Study Date         :",Tag("StudyDate"),      ds.StudyDate)
print("Study Time         :",Tag("StudyTime"),      ds.StudyTime)
print("アクセッション番号 :",Tag("AccessionNumber"),ds.AccessionNumber)
print("画像診断装置       :",Tag("Modality"),       ds.Modality)<jupyter_output>SOP Instance UID   : (0008, 0018) 1.2.392.200036.9116.2.6.1.16.1613469034.1289543971.629951
Study Date         : (0008, 0020) 20101112
Study Time         : (0008, 0030) 153820.000
アクセッション番号 : (0008, 0050) 838
画像診断装置       : (0008, 0060) CT<jupyter_text>4.2.2<jupyter_code>print("患者名         :",Tag("PatientName"),ds.PatientName)
print("患者ID         :",Tag("PatientID"),ds.PatientID)
print("検査部位       :",Tag("BodyPartExamined"),ds.BodyPartExamined)
print("スライス厚     :",Tag("SliceThickness"),ds.SliceThickness)
print("画像再構成関数 :",Tag("ConvolutionKernel"),ds.ConvolutionKernel)<jupyter_output>患者名         : (0010, 0010) Joho^Taro
患者ID         : (0010, 0020) 12345678
検査部位       : (0018, 0015) HEAD
スライス厚     : (0018, 0050) 8.0
画像再構成関数 : (0018, 1210) FC21<jupyter_text>4.2.3<jupyter_code>print("Study Instance UID      :",Tag("StudyInstanceUID"),ds.StudyInstanceUID)
print("Series Instance UID     :",Tag("SeriesInstanceUID"),ds.SeriesInstanceUID)
print("Series Number           :",Tag("SeriesNumber"),ds.SeriesNumber)
print("Image Position(Patient) :",Tag("ImagePositionPatient"),ds.ImagePositionPatient)
print("Acquisition Number      :",Tag("AcquisitionNumber"),ds.AcquisitionNumber)
print("Instance Number         :",Tag("InstanceNumber"),ds.InstanceNumber)
print("Slice Location          :",Tag("SliceLocation"),ds.SliceLocation)<jupyter_output>Study Instance UID      : (0020, 000d) 1.2.392.200036.9116.172.16.31.10.1613469034.1289543900.390492
Series Instance UID     : (0020, 000e) 1.2.392.200036.9116.172.16.58.36.1613469034.1289543929.202106
Series Number           : (0020, 0011) 1
Image Position(Patient) : (0020, 0032) [-120.000, -119.7761, -462.6741]
Acquisition Number      : (0020, 0012) 17
Instance Number         : (0020, 0013) 17
Slice Location          : (0020, 1041) +430.00<jupyter_text>4.2.4<jupyter_code>print("光度測定解釈         :",Tag("PhotometricInterpretation"),ds.PhotometricInterpretation)
print("画像の行列(高さ)     :",Tag("Rows"),ds.Rows)
print("画像の列数(幅)       :",Tag("Columns"),ds.Columns)
print("画素間隔             :",Tag("PixelSpacing"),ds.PixelSpacing)
print("Bits Allocated       :",Tag("BitsAllocated"),ds.BitsAllocated)
print("Bits Stored          :",Tag("BitsStored"),ds.BitsStored)
print("High Bit             :",Tag("HighBit"),ds.HighBit)
print("Pixel Representation :",Tag("PixelRepresentation"),ds.PixelRepresentation)
print("Window Center        :",Tag("WindowCenter"),ds.WindowCenter)
print("Window Width         :",Tag("WindowWidth"),ds.WindowWidth)
print("Rescale Intercept    :",Tag("RescaleIntercept"),ds.RescaleIntercept)
print("Rescale Slope        :",Tag("RescaleSlope"),ds.RescaleSlope)<jupyter_output>光度測定解釈         : (0028, 0004) MONOCHROME2
画像の行列(高さ)     : (0028, 0010) 512
画像の列数(幅)       : (0028, 0011) 512
画素間隔             : (0028, 0030) [0.468, 0.468]
Bits Allocated       : (0028, 0100) 16
Bits Stored          : (0028, 0101) 16
High Bit             : (0028, 0102) 15
Pixel Representation : (0028, 0103) 1
Window Center        : (0028, 1050) 40
Window Width         : (0028, 1051) 80
Rescale Intercept    : (0028, 1052) 0
Rescale Slope        : (0028, 1053) 1<jupyter_text>4.3 2つのDICOM画像のデータエレメントを比較する 4.3.1<jupyter_code>import pydicom

fnm1="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/Brain01"
fnm2="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/Lung01"

ds1=pydicom.dcmread(fnm1)
print(ds1)<jupyter_output>Dataset.file_meta -------------------------------
(0002, 0000) File Meta Information Group Length  UL: 204
(0002, 0001) File Meta Information Version       OB: b'\x00\x01'
(0002, 0002) Media Storage SOP Class UID         UI: CT Image Storage
(0002, 0003) Media Storage SOP Instance UID      UI: 1.2.392.200036.9116.172.16.31.10.1613469034.1289543971.629951
(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian
(0002, 0012) Implementation Class UID            UI: 1.2.392.200036.9116.172.16.31.10
(0002, 0013) Implementation Version Name         SH: 'TM_CT_CMW_V3.00'
-------------------------------------------------
(0008, 0008) Image Type                          CS: ['ORIGINAL', 'PRIMARY', 'AXIAL']
(0008, 0016) SOP Class UID                       UI: CT Image Storage
(0008, 0018) SOP Instance UID                    UI: 1.2.392.200036.9116.2.6.1.16.1613469034.1289543971.629951
(0008, 0020) Study Date                          DA: '20101112'
(0008, 0021) Series Date         [...]<jupyter_text>4.3.2<jupyter_code>allTag=[]
for i,tag in enumerate(ds1):
  tg=str(tag) #DataElement->String
  print(i,">1>tag type=",type(tag))
  print("   -->tg type=",type(tg))
  grpelm=tg[:12]
  print("\t>>>>#",i,":",grpelm)
  allTag+=[grpelm]
print(">1>len=",len(allTag))
print(allTag)<jupyter_output>0 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 0 : (0008, 0008)
1 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 1 : (0008, 0016)
2 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 2 : (0008, 0018)
3 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 3 : (0008, 0020)
4 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 4 : (0008, 0021)
5 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 5 : (0008, 0022)
6 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 6 : (0008, 0023)
7 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 7 : (0008, 0030)
8 >1>tag type= <class 'pydicom.dataelem.DataElement'>
   -->tg type= <class 'str'>
	>>>># 8 : (0008, 0031)
9 >1>tag type= <class 'pydicom.datael[...]<jupyter_text>4.3.3<jupyter_code>ds2=pydicom.dcmread(fnm2)
for i,tag in enumerate(ds2):
  tg=str(tag)
  grpelm=tg[:12]
  #print(">2>#",i,":",grpelm)
  if grpelm not in allTag:
    print(">2>",grpelm)
    allTag+=[grpelm]
print(allTag)
print(">2>len=",len(allTag))<jupyter_output>>2> (0018, 1160)
>2> (0018, 9323)
>2> (0018, 9324)
>2> (7005, 1007)
>2> (7005, 100a)
>2> (7005, 1021)
>2> (7005, 1022)
>2> (7005, 1023)
['(0008, 0008)', '(0008, 0016)', '(0008, 0018)', '(0008, 0020)', '(0008, 0021)', '(0008, 0022)', '(0008, 0023)', '(0008, 0030)', '(0008, 0031)', '(0008, 0032)', '(0008, 0033)', '(0008, 0050)', '(0008, 0060)', '(0008, 0070)', '(0008, 0080)', '(0008, 0090)', '(0008, 1010)', '(0008, 103e)', '(0008, 1040)', '(0008, 1090)', '(0010, 0010)', '(0010, 0020)', '(0010, 0030)', '(0010, 0040)', '(0010, 1010)', '(0018, 0015)', '(0018, 0022)', '(0018, 0050)', '(0018, 0060)', '(0018, 0090)', '(0018, 1000)', '(0018, 1020)', '(0018, 1100)', '(0018, 1120)', '(0018, 1130)', '(0018, 1140)', '(0018, 1150)', '(0018, 1151)', '(0018, 1152)', '(0018, 1170)', '(0018, 1210)', '(0018, 5100)', '(0018, 9345)', '(0020, 000d)', '(0020, 000e)', '(0020, 0010)', '(0020, 0011)', '(0020, 0012)', '(0020, 0013)', '(0020, 0020)', '(0020, 0032)', '(0020, 0037)', '(0020, 0052)', '(0020, 1040)',[...]<jupyter_text>Memo  ・データセット(ds)からタグ番号(groupとelement)を指定して値を  　取得するには次のようにする  　ds[group,element].value   4.3.4<jupyter_code>allTag=sorted(allTag)
print("sort:",allTag)
for tg in allTag:
  val1="value None"
  val2="Value None"
  kywd=""
  vr=""
  grp=tg[1:5]  #Group
  elm=tg[7:11] #Elemnt

  if tg in str(ds1):   #もしタグ番号tgがデータセットds1にあれば
    val1=ds1[grp,elm].value
    kywd=ds1[grp,elm].keyword
    vr=ds1[grp,elm].VR
  if tg in str(ds2):   #もしタグ番号tgがデータセットds1にあれば
    val1=ds2[grp,elm].value
    kywd=ds2[grp,elm].keyword
    vr=ds2[grp,elm].VR
  
  if val1==val2:      #もし同じ値があれば
    print(">3>",grp,elm,vr,kywd,"\t Same Value:",val1)
  else:
    val1=str(val1)
    val2=str(val2)
    print("\n>3>",grp,elm,vr,kywd,"\t Not Same Value:")
    print("\tfile1:",val1[:50])
    print("\tfile2:",val2[:50])
    print()<jupyter_output>sort: ['(0008, 0008)', '(0008, 0016)', '(0008, 0018)', '(0008, 0020)', '(0008, 0021)', '(0008, 0022)', '(0008, 0023)', '(0008, 0030)', '(0008, 0031)', '(0008, 0032)', '(0008, 0033)', '(0008, 0050)', '(0008, 0060)', '(0008, 0070)', '(0008, 0080)', '(0008, 0090)', '(0008, 1010)', '(0008, 103e)', '(0008, 1040)', '(0008, 1090)', '(0010, 0010)', '(0010, 0020)', '(0010, 0030)', '(0010, 0040)', '(0010, 1010)', '(0018, 0015)', '(0018, 0022)', '(0018, 0050)', '(0018, 0060)', '(0018, 0090)', '(0018, 1000)', '(0018, 1020)', '(0018, 1100)', '(0018, 1120)', '(0018, 1130)', '(0018, 1140)', '(0018, 1150)', '(0018, 1151)', '(0018, 1152)', '(0018, 1160)', '(0018, 1170)', '(0018, 1210)', '(0018, 5100)', '(0018, 9323)', '(0018, 9324)', '(0018, 9345)', '(0020, 000d)', '(0020, 000e)', '(0020, 0010)', '(0020, 0011)', '(0020, 0012)', '(0020, 0013)', '(0020, 0020)', '(0020, 0032)', '(0020, 0037)', '(0020, 0052)', '(0020, 1040)', '(0020, 1041)', '(0028, 0002)', '(0028, 0004)', '(0028, 0010)', '(0028, 0011)', '[...]<jupyter_text>4.4 DICOM画像を匿名化する Memo  ・匿名化による値の変更はDICOM違反やデータの改ざんにならな  　いよう十分注意する 4.4.1<jupyter_code>import os
import pydicom

orgdir="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/"
dstdir="/content/drive/My Drive/result/"

if not os.path.isdir(dstdir):
  os.mkdir(dstdir)
  print("新しくディレクトリ"+dstdir+"を作成しました")
else:
  print("既にディレクトリ"+dstdir+"は存在します")<jupyter_output>既にディレクトリ/content/drive/My Drive/result/は存在します<jupyter_text>4.4.2<jupyter_code>anonyInfo=[["00100010","no name"],
           ["00100020","no ptid"],]
print(anonyInfo)
files=os.listdir(orgdir)
print(files)<jupyter_output>[['00100010', 'no name'], ['00100020', 'no ptid']]
['Brain02', 'Abdomen03', 'Brain01', 'Abdomen01', 'Abdomen02', 'Lung03', 'Lung02', 'Lung01']<jupyter_text>Memo  ・データセット(ds)のタグ番号(tag_number)のデータエレメント  　の値を新しい値(new_value)に変更する際は次のように行う  　ds[tag_number].value=new_value 4.4.3<jupyter_code>for i,fnm in enumerate(files):
  path=orgdir+fnm
  ds=pydicom.dcmread(path)
  for j,info in enumerate(anonyInfo):
    tag=info[0]
    print(tag)
    val=info[1]
    print(val)
    print(">>1>>",i,j,tag,fnm)
    print(">>2>>",ds[tag])
    ds[tag].value=val
    print(">>3>>",ds[tag])
  savefnm=dstdir+"anony."+fnm 
  pydicom.dcmwrite(savefnm,ds)
brain="/content/drive/My Drive/result/anony.Brain01"

ds=pydicom.dcmread(brain)
print(ds)
wc=ds.WindowCenter
ww=ds.WindowWidth
img=ds.pixel_array
max=wc+ww/2
min=wc-ww/2
plt.imshow(img,cmap="gray",vmax=max,vmin=min)
plt.show()<jupyter_output>Dataset.file_meta -------------------------------
(0002, 0000) File Meta Information Group Length  UL: 204
(0002, 0001) File Meta Information Version       OB: b'\x00\x01'
(0002, 0002) Media Storage SOP Class UID         UI: CT Image Storage
(0002, 0003) Media Storage SOP Instance UID      UI: 1.2.392.200036.9116.2.6.1.16.1613469034.1289543971.629951
(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian
(0002, 0012) Implementation Class UID            UI: 1.2.392.200036.9116.2.6.1.100
(0002, 0013) Implementation Version Name         SH: 'TM_CT_CMW_V3.00'
-------------------------------------------------
(0008, 0008) Image Type                          CS: ['ORIGINAL', 'PRIMARY', 'AXIAL']
(0008, 0016) SOP Class UID                       UI: CT Image Storage
(0008, 0018) SOP Instance UID                    UI: 1.2.392.200036.9116.2.6.1.16.1613469034.1289543971.629951
(0008, 0020) Study Date                          DA: '20101112'
(0008, 0021) Series Date         [...]<jupyter_text>4.5 DICOM画像をPNGに変換する 4.5.1<jupyter_code>import numpy as np
import cv2
import pydicom

dcmfnm="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/Brain01"

ds=pydicom.dcmread(dcmfnm)   #DICOM画像を読み込む
#print(ds)
wc=ds.WindowCenter           #ウィンドウセンター値に代入
ww=ds.WindowWidth            #ウィンドウ幅を代入
ri=ds.RescaleIntercept       #リスケール切片
rs=ds.RescaleSlope           #リスケール勾配
img1=ds.pixel_array           #画素値を代入

print("Window Center   :",wc)
print("Window Width    :",ww)
print("RescaleIntercept:",ri)
print("RescaleSlope    :",rs)<jupyter_output>Window Center   : 40
Window Width    : 80
RescaleIntercept: 0
RescaleSlope    : 1<jupyter_text>4.5.2<jupyter_code>#img=img*rs+ri
max=wc+ww/2
min=wc-ww/2
print("wc=",wc,"ww=",ww,"→max=",max,"min=",min)<jupyter_output>wc= 40 ww= 80 →max= 80.0 min= 0.0<jupyter_text>4.5.3<jupyter_code>img2=255*(img1-min)/(max-min)
img2=np.clip(img1,0,255)
'''
for data in img:
  print(data)
'''
cv2.imwrite("/content/drive/My Drive/Brain01.png",img2)

plt.imshow(img2,cmap="gray")
plt.show()<jupyter_output><empty_output><jupyter_text>4.6 DICOM画像を画像位置でソートする 4.6.1<jupyter_code>import os
import pydicom

dirname="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/"

files=os.listdir(dirname)
for i,filename in enumerate(files):
  d=pydicom.dcmread(dirname+filename)
  print("Original>>",i,filename,"\t",d.ImagePositionPatient)
a={"b":3,"c":1,"a":2}
sorted(a)
sorted(a.items())
sorted(a.items(),key=lambda x:x[1])<jupyter_output><empty_output><jupyter_text>4.6.2<jupyter_code>filedic={}   #ファイル名とImagePositionを代入する辞書
filelist=[]  #ソートされた順でファイル名を代入するリスト

for i,filename in enumerate(files):
  d=pydicom.dcmread(dirname+filename)
  filedic[filename]=d.ImagePositionPatient[2]
  print("MakeDic>>",i,filename,"\t",filedic[filename])
fileSorted=sorted(filedic.items(),key=lambda x:-x[1])
for i,fname_imgPos in enumerate(fileSorted):
  filelist.append(fname_imgPos[0])
  print("Sorted>>",i,fname_imgPos[0],"\t:",fname_imgPos[1])
print("Result>>",filelist)<jupyter_output>Sorted>> 0 Brain01 	: -462.6741
Sorted>> 1 Brain02 	: -508.6741
Sorted>> 2 Lung01 	: -789.0000
Sorted>> 3 Lung02 	: -814.0000
Sorted>> 4 Lung03 	: -904.0000
Sorted>> 5 Abdomen01 	: -949.0000
Sorted>> 6 Abdomen02 	: -954.0000
Sorted>> 7 Abdomen03 	: -1024.000
Result>> ['Brain01', 'Brain02', 'Lung01', 'Lung02', 'Lung03', 'Abdomen01', 'Abdomen02', 'Abdomen03']<jupyter_text>4.7 DICOM画像をシリーズ毎に整理する 4.7.1<jupyter_code>import os
import pydicom

dirnm="/content/drive/My Drive/DATASET/dataset/ct_dcmdir/"
dstdir="/content/drive/My Drive/result"

if not os.path.isdir(dstdir):
  os.mkdir(dstdir)
  print("新しくディレクトリ"+dstdir+"を作成しました。")

files=os.listdir(dirnm)
print(">>1>>",files)

for fnm in files:
  ds=pydicom.dcmread(dirnm+fnm)
  print("-"*50)
  print("File Name:",ds.SeriesInstanceUID)
  print("Seiris No",ds.SeriesNumber)<jupyter_output>>>1>> ['Brain02', 'Abdomen03', 'Brain01', 'Abdomen01', 'Abdomen02', 'Lung03', 'Lung02', 'Lung01']
--------------------------------------------------
File Name: 1.2.392.200036.9116.172.16.31.10.1613469034.1289543929.202106
Seiris No 1
--------------------------------------------------
File Name: 1.2.392.200036.9116.2.6.1.16.1613469034.1289544231.883115
Seiris No 2
--------------------------------------------------
File Name: 1.2.392.200036.9116.2.6.1.16.1613469034.1289543929.202106
Seiris No 1
--------------------------------------------------
File Name: 1.2.392.200036.9116.2.6.1.16.1613469034.1289544231.883115
Seiris No 2
--------------------------------------------------
File Name: 1.2.392.200036.9116.172.16.58.36.1613469034.1289544231.883115
Seiris No 2
--------------------------------------------------
File Name: 1.2.392.200036.9116.2.6.1.16.1613469034.1289544291.542320
Seiris No 3
--------------------------------------------------
File Name: 1.2.392.200036.9116.172.16.58.36.1613469034.12895442[...]<jupyter_text>4.7.2<jupyter_code>for fnm in files:
  ds=pydicom.dcmread(dirnm+fnm)
  subdir=str(ds.SeriesNumber)
  #print(subdir)
  if not os.path.isdir(dstdir+subdir):
    os.mkdir(dstdir+subdir)
    print("サブディレクトリ",subdir,"を作成しました。")
  pydicom.dcmwrite(dstdir+subdir+"/"+fnm,ds)
  print("\tファイル",fnm,"をコピーしました。")<jupyter_output>ファイル Brain02 をコピーしました。
	ファイル Abdomen03 をコピーしました。
	ファイル Brain01 をコピーしました。
	ファイル Abdomen01 をコピーしました。
	ファイル Abdomen02 をコピーしました。
	ファイル Lung03 をコピーしました。
	ファイル Lung02 をコピーしました。
	ファイル Lung01 をコピーしました。<jupyter_text>4.8 DICOM画像をひとつのディレクトリに集める 4.8.1<jupyter_code>import os 
import datetime
import pydicom

orgdir="/content/drive/My Drive/result2/"
dstdir="/content/drive/My Drive/result3/"

if not os.path.isdir(dstdir):
  os.mkdir(dstdir)
  print("新しいディレクトリ"+dstdir+"を作成しました。")<jupyter_output><empty_output><jupyter_text>4.8.2<jupyter_code>def searchsubdir(dirnm):
  print(">>0>>",dirnm)
  dirs=os.listdir(dirnm)
  print(">>1>>",dirs)
  dirs=[dirnm+dir for dir in dirs]
  print(">>2>>",dirs)
  filelist=[]
  for dr in dirs:
    if os.path.isdir(dr):
      print(">>3>>",dr,"is Directory")
      dirs+=searchsubdir(dr+'/')
    else:
      print(">>4>>",dr,"is File")
      filelist+=[dr]

  return filelist

files=searchsubdir(orgdir)
print(files)<jupyter_output>>>0>> /content/drive/My Drive/result2/
>>1>> ['Abdomen03', 'Abdomen02', 'Abdomen01']
>>2>> ['/content/drive/My Drive/result2/Abdomen03', '/content/drive/My Drive/result2/Abdomen02', '/content/drive/My Drive/result2/Abdomen01']
>>4>> /content/drive/My Drive/result2/Abdomen03 is File
>>4>> /content/drive/My Drive/result2/Abdomen02 is File
>>4>> /content/drive/My Drive/result2/Abdomen01 is File
['/content/drive/My Drive/result2/Abdomen03', '/content/drive/My Drive/result2/Abdomen02', '/content/drive/My Drive/result2/Abdomen01']<jupyter_text>4.8.3<jupyter_code>dt=str(datetime.datetime.now())
print('>>6>>',dt)
print('>>7>>',dt.replace(' ','_'))
print(">>8>>",dt.replace(' ','_').replace(':','.'))<jupyter_output>>>6>> 2020-06-23 12:19:27.703036
>>7>> 2020-06-23_12:19:27.703036
>>8>> 2020-06-23_12.19.27.703036<jupyter_text>4.8.4<jupyter_code>for dcmfnm in files:
  ds=pydicom.dcmread(dcmfnm)
  dt=str(datetime.datetime.now()).replace(' ','_').replace(':','.')
  newfnm=dstdir+str(dt)
  pydicom.dcmwrite(newfnm,ds)
  print(">>time>>",dcmfnm,"->",newfnm)<jupyter_output>>>time>> /content/drive/My Drive/result2/Abdomen03 -> /content/drive/My Drive/result3/2020-06-23_12.19.27.718529
>>time>> /content/drive/My Drive/result2/Abdomen02 -> /content/drive/My Drive/result3/2020-06-23_12.19.27.735007
>>time>> /content/drive/My Drive/result2/Abdomen01 -> /content/drive/My Drive/result3/2020-06-23_12.19.27.748541<jupyter_text>4.8.5<jupyter_code>print(">>9>>",files[0])
print(">>10>>",files[0].replace('/','_'))
print(">>11>>",files[0].replace('/','_').lstrip('.'))
print(">>12>>",files[0].replace('/','_').lstrip('.').lstrip("_"))<jupyter_output>>>9>> /content/drive/My Drive/result2/Abdomen03
>>10>> _content_drive_My Drive_result2_Abdomen03
>>11>> _content_drive_My Drive_result2_Abdomen03
>>12>> content_drive_My Drive_result2_Abdomen03<jupyter_text>4.8.6<jupyter_code>for dcmfnm in files:
  ds=pydicom.dcmread(dcmfnm)
  newfnm=dstdir+dcmfnm.replace("/","_").lstrip(".").lstrip("_")
  pydicom.dcmwrite(newfnm,ds)
  print(">>pathname>>",dcmfnm,'->',newfnm)<jupyter_output>>>pathname>> /content/drive/My Drive/result2/Abdomen03 -> /content/drive/My Drive/result3/content_drive_My Drive_result2_Abdomen03
>>pathname>> /content/drive/My Drive/result2/Abdomen02 -> /content/drive/My Drive/result3/content_drive_My Drive_result2_Abdomen02
>>pathname>> /content/drive/My Drive/result2/Abdomen01 -> /content/drive/My Drive/result3/content_drive_My Drive_result2_Abdomen01<jupyter_text>4.8.7<jupyter_code>for dcmfnm in files:
  ds=pydicom.dcmread(dcmfnm)
  newfnm=dstdir+ds.SOPInstanceUID
  pydicom.dcmwrite(newfnm,ds)
  print(">>SOP>>",dcmfnm,'->',newfnm)<jupyter_output>>>SOP>> /content/drive/My Drive/result2/Abdomen03 -> /content/drive/My Drive/result3/1.2.392.200036.9116.2.6.1.16.1613469034.1289544259.847222
>>SOP>> /content/drive/My Drive/result2/Abdomen02 -> /content/drive/My Drive/result3/1.2.392.200036.9116.2.6.1.16.1613469034.1289544253.849998
>>SOP>> /content/drive/My Drive/result2/Abdomen01 -> /content/drive/My Drive/result3/1.2.392.200036.9116.2.6.1.16.1613469034.1289544253.352221<jupyter_text>4.9 DICOM圧縮画像を外部ツールを使って解凍する<jupyter_code>!sudo apt install dcmtk
!dcmdjpeg<jupyter_output>$dcmtk: dcmdjpeg v3.6.2 2017-07-14 $

dcmdjpeg: Decode JPEG-compressed DICOM file
usage: dcmdjpeg [options] dcmfile-in dcmfile-out

parameters:
  dcmfile-in                     DICOM input filename to be converted
  dcmfile-out                    DICOM output filename

general options:
  -h      --help                 print this help text and exit
          --version              print version information and exit
          --arguments            print expanded command line arguments
  -q      --quiet                quiet mode, print no warnings and errors
  -v      --verbose              verbose mode, print processing details
  -d      --debug                debug mode, print debug information
  -ll     --log-level            [l]evel: string constant
                                 (fatal, error, warn, info, debug, trace)
                                 use level l for the logger
  -lc     --log-config           [f]ilename: string
                                 use config file f f[...]<jupyter_text>4.9.1<jupyter_code>import subprocess
import pydicom
from matplotlib import pyplot as plt

def decompjpeg(in_fnm,out_fnm):
  cmdline="dcmdjpeg "+in_fnm+" "+out_fnm
  proc=subprocess.run(cmdline,shell=True)
  print(proc)

  return proc<jupyter_output><empty_output><jupyter_text>Memo  ・コマンドラインの引数の中に空白が含まれるとき、  　ダブルクォーテーションで括る 4.9.2<jupyter_code>cfnm='/content/drive/"My Drive"/DATASET/dataset/mr_dcmdir/Knee01'
dfnm='/content/drive/"My Drive"/Knee01'

decompjpeg(cfnm,dfnm)

dfnm1=dfnm.replace('"','')
ds=pydicom.dcmread(dfnm1)
wc=ds.WindowCenter
ww=ds.WindowWidth
img=ds.pixel_array

max=wc+ww/2
min=wc-ww/2
print("max=",max,"min=",min)
plt.imshow(img,cmap="gray",vmax=max,vmin=min)
plt.show()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup