3 from os.path import isdir, join
6 from pprint import pprint
10 from decimal import Decimal as d, ROUND_HALF_UP as rhu
12 PNG16_MAX = pow(2, 16) - 1 # here if thinks the heaviest weight bit is for transparency or something not in use with dicom imgs
13 PNG8_MAX = pow(2, 8+1) - 1 # heaviest weight bit is 8 => 2**8, but dont forget the others: the reason of +1
15 INPUT_DIR = '../../Data/Images_anonymous/Case_0449/'
16 OUT_DIR = './generated/'
19 def map16(array):# can be useful in future
23 # return d(str(n)).quantize(d('1'), rounding=rhu)# safe round without
25 def affine(Mat, ab, cd):
28 ab: the 'from' interval (2, 384) or {begin:2, end:384} begin is 0, and end is 1
29 cd: the 'to' interval (0, 1024) {begin:0, end:1024}
34 with np.nditer(Mat, op_flags=['readwrite']) as M:
36 x[...] = max( 0, round( (x-a) * (d-c) / (b-a) + c ) ) # could not be negative
40 return '/'.join(filepath.split('/')[:-1]) + '/'
42 def topng(inputfile, outfile=None, overwrite=True):
44 dicimg = pydicom.read_file(inputfile) # read dicom image
45 except pydicom.errors.InvalidDicomError as e:
46 # @TODO: log, i can't read this file
48 img = dicimg.pixel_array# get image array (12bits)
52 # print('img', type(img))
53 # print('min', img.min(), 'max', img.max())
54 # dicimg.convert_pixel_data() # same as using dicimg.pixel_array
55 # pixa = dicimg._pixel_array
56 # print('dicimg._pixel_array', pixa)
57 # print('dicimg.pixel_array==pixa', dicimg.pixel_array==pixa)
60 # affine transfo to png 16 bits, func affects img variable
62 # print('maxdepth, PNG8_MAX', maxdepth, PNG8_MAX) # testing..
64 (img.min(), maxdepth),
65 (0, PNG16_MAX if maxdepth > PNG8_MAX else PNG8_MAX)
68 savepath = (outfile or inputfile) + '.png'
69 savedir = getdir(savepath)
70 if overwrite and not isdir( savedir ):
71 pathlib.Path(savedir).mkdir(parents=True, exist_ok=True)
75 # tmp = np.array(img) # to get eye on the numpy format of img
76 # tmp = np.array(img) # to get eye on the numpy format of img
77 # print("img[0,0]", img[0,0])
79 # tmp.dtype = 'uint32'
80 # np.savetxt(savepath + '.npy', img)
83 cv2.imwrite(savepath, img, [cv2.IMWRITE_PNG_COMPRESSION, 0]) # write png image
86 def topngs(inputdir, outdir):
88 inputdir : directory which contains directly dicom files
90 files = [f for f in os.listdir(inputdir)]
93 topng( inputdir + f, join(outdir, f) )
95 if __name__ == '__main__':
96 # topngs( INPUT_DIR, join(OUT_DIR, INPUT_DIR.split('/')[-2]) )
97 topng(INPUT_DIR+'Image00001', OUT_DIR + INPUT_DIR.split('/')[-2] +'-Image00001')