96 lines
3.0 KiB
Python
96 lines
3.0 KiB
Python
# coding:utf-8
|
|
import os
|
|
import traceback
|
|
import pydicom
|
|
import numpy as np
|
|
import re
|
|
from PIL import Image
|
|
import time
|
|
import sys
|
|
import codecs
|
|
try:
|
|
__import__('gdcm')
|
|
except:
|
|
pass
|
|
|
|
UTF8Reader = codecs.getreader('utf8')
|
|
|
|
def str_numbers(s):
|
|
pieces =int(re.compile(r'(\d+)').split(s)[1])
|
|
return pieces
|
|
|
|
def sort_strings_with_numbers(alist):
|
|
return sorted(alist, key=str_numbers)
|
|
|
|
def convertTo16BitData(ds,path):
|
|
data = ds.pixel_array
|
|
|
|
HUArray = np.array(data, dtype=data.dtype)
|
|
|
|
if data.dtype == 'uint8' and len(data.shape) ==3:
|
|
img= Image.fromarray(HUArray)
|
|
newWidth = img.size[0]
|
|
newHeight = img.size[1]
|
|
img.save(path,"PNG")
|
|
result = str(data.dtype)+","+str(newWidth)+","+str(newHeight)
|
|
|
|
else:
|
|
# tempSlope=1
|
|
# tempIntercept=0
|
|
# if 'RescaleSlope' in ds:
|
|
# tempSlope = ds.RescaleSlope
|
|
# if 'RescaleIntercept' in ds:
|
|
# tempIntercept = ds.RescaleIntercept
|
|
# HUArray = np.array(data*tempSlope + tempIntercept, dtype=data.dtype)
|
|
|
|
rArray = ((HUArray&0xFF00)>>8).astype('uint8')
|
|
gArray = (HUArray& 0x00FF).astype('uint8')
|
|
bArray = (HUArray*0).astype('uint8')
|
|
r_pixels = Image.fromarray(rArray).convert('L')
|
|
g_pixels = Image.fromarray(gArray).convert('L')
|
|
b_pixels = Image.fromarray(bArray).convert('L')
|
|
img = Image.merge("RGB", (r_pixels, g_pixels, b_pixels))
|
|
newWidth = img.size[0]
|
|
newHeight = img.size[1]
|
|
|
|
# if 'Modality' in ds and (ds.Modality=='CR' or ds.Modality == 'DX'): # 1, 2
|
|
if 0:
|
|
if newWidth>1000 or newHeight>1000:
|
|
newWidth=img.size[0]
|
|
newHeight=img.size[1]
|
|
if newWidth>1000 and newWidth<2000:
|
|
newWidth=newWidth/2
|
|
if newWidth>2000:
|
|
newWidth=newWidth/4
|
|
if newHeight>1000 and newHeight<2000:
|
|
newHeight=newHeight/2
|
|
if newHeight>2000:
|
|
newHeight=newHeight/4
|
|
img=img.resize((newWidth,newHeight),Image.ANTIALIAS)
|
|
|
|
img.save(path,"PNG")
|
|
result = str(data.dtype)+","+str(newWidth)+","+str(newHeight)
|
|
return result
|
|
|
|
while True:
|
|
argsInput = UTF8Reader(sys.stdin.readline()).strip('\n')
|
|
try:
|
|
image_id = argsInput.split(" ")[0]
|
|
dcmFile = argsInput.split(" ")[1]
|
|
pngPath = argsInput.split(" ")[2]
|
|
instance = argsInput.split(" ")[3]
|
|
if not os.path.isdir(pngPath):
|
|
os.mkdir(pngPath)
|
|
pngFile = pngPath+ instance + ".png"
|
|
dataset = pydicom.read_file(dcmFile)
|
|
result =convertTo16BitData(dataset,pngFile)
|
|
print "success"
|
|
print image_id
|
|
print pngFile
|
|
print result
|
|
sys.stdout.flush()
|
|
except Exception:
|
|
sys.stderr.write("error")
|
|
sys.stderr.flush()
|
|
pass
|