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 return (64, 64) : the width and height
47 dicimg = pydicom.read_file(inputfile) # read dicom image
48 except pydicom.errors.InvalidDicomError as e:
49 # @TODO: log, i can't read this file
51 img = dicimg.pixel_array# get image array (12bits)
54 # return img.shape # $$ COMMENT OR REMOVE THIS LINE
56 # print('img', type(img))
57 # print('min', img.min(), 'max', img.max())
58 # dicimg.convert_pixel_data() # same as using dicimg.pixel_array
59 # pixa = dicimg._pixel_array
60 # print('dicimg._pixel_array', pixa)
61 # print('dicimg.pixel_array==pixa', dicimg.pixel_array==pixa)
64 # affine transfo to png 16 bits, func affects img variable
66 # print('maxdepth, PNG8_MAX', maxdepth, PNG8_MAX) # testing..
68 (img.min(), maxdepth),
69 (0, PNG16_MAX if maxdepth > PNG8_MAX else PNG8_MAX)
72 savepath = (outfile or inputfile) + '.png'
73 savedir = getdir(savepath)
74 if overwrite and not isdir( savedir ):
75 pathlib.Path(savedir).mkdir(parents=True, exist_ok=True)
79 # tmp = np.array(img) # to get eye on the numpy format of img
80 # tmp = np.array(img) # to get eye on the numpy format of img
81 # print("img[0,0]", img[0,0])
83 # tmp.dtype = 'uint32'
84 # np.savetxt(savepath + '.npy', img)
87 cv2.imwrite(savepath, img, [cv2.IMWRITE_PNG_COMPRESSION, 0]) # write png image
92 def topngs(inputdir, outdir):
94 inputdir : directory which contains directly dicom files
96 files = [f for f in os.listdir(inputdir)]
99 topng( inputdir + f, join(outdir, f) )
101 if __name__ == '__main__':
102 # topngs( INPUT_DIR, join(OUT_DIR, INPUT_DIR.split('/')[-2]) )
103 topng(INPUT_DIR+'Image00001', OUT_DIR + INPUT_DIR.split('/')[-2] +'-Image00001')