From 22853f6086bf51e7721b8f9190af0a0c9c28c34f Mon Sep 17 00:00:00 2001 From: Zhennong Chen Date: Wed, 4 May 2022 22:58:43 -0700 Subject: [PATCH] delete unused functions --- .DS_Store | Bin 10244 -> 10244 bytes function_list.py | 354 +++++++++++------------------------------------ 2 files changed, 83 insertions(+), 271 deletions(-) diff --git a/.DS_Store b/.DS_Store index 2a3a1d75c087b514705fce4e3eb83e2caf06953d..13900f0ab8f0b59f484f76a49fe355683670cee4 100644 GIT binary patch delta 301 zcmZn(XbIS`R6?Aap_rkRp#TVT7*ZK>fjEz$grRuyE{Pi{IOI}_lXH^t^K%%00Ed#C zbi?4}{M-VN5(b7(GC%@{%FQ1n8<}vqVso2J8cxZ{jPk;cI84pWPjN{pElFlzxDnT( Z6#XB!{gVUbg>hLwxl+DnGrPiHb^!PONT>h+ delta 160 zcmZn(XbIS`RDzLfvZB1m;SX{EGz&3 diff --git a/function_list.py b/function_list.py index de8def2..55e63f6 100644 --- a/function_list.py +++ b/function_list.py @@ -16,33 +16,78 @@ import cv2 import pandas as pd -# function: minimize the line of codes when you have several list to append -def massive_list_append(list_list,append_list): - assert len(list_list) == len(append_list) - [list_list[i].append(append_list[i]) for i in range(0,len(append_list))] # function: make folders def make_folder(folder_list): for i in folder_list: os.makedirs(i,exist_ok = True) -# function: get patient_list -def get_patient_list_from_csv(csv_file): - d = pd.read_csv(csv_file) - l = [] - for i in range(0,d.shape[0]): - case = d.iloc[i] - patient_class = case['Patient_Class'] - patient_id = case['Patient_ID'] - l.append([patient_class,patient_id]) - return l - -# function: multiple slice view -def show_slices(slices,colormap = "gray",origin_point = "lower"): - """ Function to display row of image slices """ - fig, axes = plt.subplots(1, len(slices)) - for i, slice in enumerate(slices): - axes[i].imshow(slice.T, cmap=colormap, origin=origin_point) +# function: find all files under the name * in the main folder, put them into a file list +def find_all_target_files(target_file_name,main_folder): + F = np.array([]) + for i in target_file_name: + f = np.array(sorted(gb.glob(os.path.join(main_folder, os.path.normpath(i))))) + F = np.concatenate((F,f)) + return F + +# function: make movies of several .png files +def make_movies(save_path,pngs,fps = 10): + mpr_array=[] + i = cv2.imread(pngs[0]) + h,w,l = i.shape + + for j in pngs: + img = cv2.imread(j) + mpr_array.append(img) + + # set fps + if len(pngs) == 16: + fps = 15 # set 16 will cause bug + elif len(pngs) > 20: + fps = len(pngs)//2 + else: + fps = len(pngs) + + # save movies + out = cv2.VideoWriter(save_path,cv2.VideoWriter_fourcc(*'mp4v'),fps,(w,h)) + for j in range(len(mpr_array)): + out.write(mpr_array[j]) + out.release() + + +# function: find time frame of a file +def find_timeframe(file,num_of_dots,signal = '/'): + k = list(file) + if num_of_dots == 1: #.png + num1 = [i for i, e in enumerate(k) if e == '.'][-1] + else: + num1 = [i for i, e in enumerate(k) if e == '.'][-2] + num2 = [i for i,e in enumerate(k) if e==signal][-1] + kk=k[num2+1:num1] + if len(kk)==2: + return int(kk[0])*10+int(kk[1]) + if len(kk) == 3: + return int(kk[0])*100 + int(kk[1])*10 + int(kk[2]) + if len(kk)==1: + return int(kk[0]) + +# function: sort files based on their time frames +def sort_timeframe(files,num_of_dots,signal = '/'): + time=[] + time_s=[] + for i in files: + a = find_timeframe(i,num_of_dots,signal) + time.append(a) + time_s.append(a) + time_s.sort() + new_files=[] + for i in range(0,len(time_s)): + j = time.index(time_s[i]) + new_files.append(files[j]) + new_files = np.asarray(new_files) + return new_files + + # function: normalize one vector def normalize(x): @@ -61,33 +106,6 @@ def angle(v1, v2): result = rad / math.pi * 180 return result -# function: get a vector which is with a certain angle from one known vector -def vector_with_angle(v,angle): - return np.dot(np.array([[math.cos(angle),-math.sin(angle)],[math.sin(angle),math.cos(angle)]]),np.array([[v[0]],[v[1]]])).reshape(2,) - -# function: calculate orientation error: -def orientation_error(x_truth,y_truth,x_pred,y_pred): - n_truth = normalize(np.cross(x_truth,y_truth)) - n_pred = normalize(np.cross(x_pred,y_pred)) - - error = angle(n_truth,n_pred) - if error > 180: - error = error - 180 - return error - -# function: project one vector onto a plane with known normal vectors -def project_onto_plane(u,n): - '''n is the normal vector of the plane''' - n = normalize(n) - return (u - dotproduct(u,n) * n) - -# function: only pick one time frame from each patient -def one_time_frame_per_patient(x): - '''only pick one time frame for each patient''' - for i in range(len(x)): - if i%2 == 1: - x[i]='0' - return x[x!='0'] # function: turn normalized vector into pixel unit def turn_to_pixel(vec,size=[160,160,96]): @@ -185,15 +203,6 @@ def find_center_list_whole_stack(start_center,n,num_a,num_b,slice_thickness,pixe center_list = np.concatenate((center_list,c.reshape(1,3))) return center_list -# function: find the indexes base, mid or apex -def base_mid_apex(range_of_index,num_of_divisions,base_no,mid_no,apex_no): - # range of index is a list in the form of range(start,end+1) - # to find base,mid and apex - gap = (range_of_index[-1] - range_of_index[0] ) / num_of_divisions - base = math.floor(((gap * base_no) ) + range_of_index[0]) - mid = math.floor(((gap * mid_no) ) + range_of_index[0]) - apex = math.floor(((gap * apex_no) ) + range_of_index[0]) - return base,mid,apex # funciton: resample a SAX stack with n planes into a particular num of planes # will return the indexes as well as the centerpoint_list @@ -233,24 +242,6 @@ def reslice_mpr(mpr_data,plane_center,x,y,x_s,y_s,interpolation): return new_mpr -# function: find which batch a patient is belonged to: -def locate_batch_num_for_patient(patient_class,patient_id,partition_file_path): - partition_list = np.load(partition_file_path,allow_pickle=True) - simplified_partition_list = [] - for group in range(0,len(partition_list)): - l = [] - for p in partition_list[group]: - p_id = os.path.basename(p) - p_class = os.path.basename(os.path.dirname(p)) - l.append(((p_class,p_id))) - simplified_partition_list.append(l) - answer = [] - for group in range(0,len(simplified_partition_list)): - for i in simplified_partition_list[group]: - if i == (patient_class,patient_id): - answer.append(group) - assert len(answer) == 1 - return answer[0] # function: check affine from all time frames (affine may have errors in some tf, that's why we need to find the mode ) def check_affine(one_time_frame_file_name): @@ -302,13 +293,6 @@ def get_affine_from_vectors(mpr_data,volume_affine,vector,zoom = 1.0): mpr_A = np.dot(volume_affine,Transform) return mpr_A -# function: find all files under the name * in the main folder, put them into a file list -def find_all_target_files(target_file_name,main_folder): - F = np.array([]) - for i in target_file_name: - f = np.array(sorted(gb.glob(os.path.join(main_folder, os.path.normpath(i))))) - F = np.concatenate((F,f)) - return F # function: color box addition def color_box(image,y_range = 10, x_range = 20): @@ -397,39 +381,6 @@ def DICE(seg1,seg2,target_val): return DSC -# function: find time frame of a file -# function: find time frame of a file -def find_timeframe(file,num_of_dots,signal = '/'): - k = list(file) - if num_of_dots == 1: #.png - num1 = [i for i, e in enumerate(k) if e == '.'][-1] - else: - num1 = [i for i, e in enumerate(k) if e == '.'][-2] - num2 = [i for i,e in enumerate(k) if e==signal][-1] - kk=k[num2+1:num1] - if len(kk)==2: - return int(kk[0])*10+int(kk[1]) - if len(kk) == 3: - return int(kk[0])*100 + int(kk[1])*10 + int(kk[2]) - if len(kk)==1: - return int(kk[0]) - -# function: sort files based on their time frames -def sort_timeframe(files,num_of_dots,signal = '/'): - time=[] - time_s=[] - for i in files: - a = find_timeframe(i,num_of_dots,signal) - time.append(a) - time_s.append(a) - time_s.sort() - new_files=[] - for i in range(0,len(time_s)): - j = time.index(time_s[i]) - new_files.append(files[j]) - new_files = np.asarray(new_files) - return new_files - # function: set window level and width def set_window(image,level,width): if len(image.shape) == 3: @@ -449,88 +400,31 @@ def set_window(image,level,width): new[i,j] = norm return new -# function: find aha segments vectors from two RV insertion points and the LV center -def find_aha_segments(c,i12,i34): - '''c,i12 and i34 are coordinates of LV center and two RV insertion points saved in numpy file. - this function can then use saved information to get the vectors (v12 to v61) representing 6 AHA segments in MID plane''' - v12 = normalize(i12 - c) - v34 = normalize(i34 - c) - - septum_angle = math.acos(dotproduct(v12, v34) / (length(v12) * length(v34)))/2 - lateral_angle = (2*math.pi - septum_angle*2) / 4 - - v61 = np.dot(np.array([[math.cos(lateral_angle),-math.sin(lateral_angle)],[math.sin(lateral_angle),math.cos(lateral_angle)]]),np.array([[v12[0]],[v12[-1]]])).reshape(2,) - v56 = np.dot(np.array([[math.cos(lateral_angle),-math.sin(lateral_angle)],[math.sin(lateral_angle),math.cos(lateral_angle)]]),np.array([[v61[0]],[v61[-1]]])).reshape(2,) - v45 = np.dot(np.array([[math.cos(lateral_angle),-math.sin(lateral_angle)],[math.sin(lateral_angle),math.cos(lateral_angle)]]),np.array([[v56[0]],[v56[-1]]])).reshape(2,) - v34 = np.dot(np.array([[math.cos(lateral_angle),-math.sin(lateral_angle)],[math.sin(lateral_angle),math.cos(lateral_angle)]]),np.array([[v45[0]],[v45[-1]]])).reshape(2,) - v23 = np.dot(np.array([[math.cos(septum_angle),-math.sin(septum_angle)],[math.sin(septum_angle),math.cos(septum_angle)]]),np.array([[v34[0]],[v34[-1]]])).reshape(2,) - - v61 = np.array([v61[0],v61[1],0]);v12 = np.array([v12[0],v12[1],0]);v23 = np.array([v23[0],v23[1],0]);v34 = np.array([v34[0],v34[1],0]);v45 = np.array([v45[0],v45[1],0]);v56 = np.array([v56[0],v56[1],0]) - result = np.array([v12,v23,v34,v45,v56,v61]) - return result - -# function: draw aha segments on the MID -def draw_aha_segments(image,AHA_axis,LV_center): - result = np.copy(image) - # load 6 vectors for segments from axis - vectors = [] - for a in AHA_axis: - vectors.append(normalize(a)) - c = np.array([LV_center[0],LV_center[1],0]) - - # draw lines - for v in vectors: - for i in range(0,50): - [x,y] = [c[0] + v[0]*i , c[1] + v[1]*i] - if x>0 and y>0 and x 1 slices, so we need to copy the current slice - I = np.zeros((image.shape[0],image.shape[1],2)) - I[:,:,0] = image[:,:,0];I[:,:,1] = image[:,:,0] - # define interpolation - interpolation = define_interpolation(I,Fill_value=I.min(),Method='linear') - - new_image = [] - new_size = [image.shape[0]*up_size,image.shape[1]*up_size] - - for i in range(0,new_size[0]): - for j in range(0,new_size[1]): - point = np.array([1/up_size*i,1/up_size*j,0]) - new_image.append(point) - - new_image = interpolation(new_image).reshape(new_size[0],new_size[1],1) - return new_image # function: adapt the re-slicing vector from low resolution for native resolution: -def adapt_reslice_vector_for_native_resolution(vector,volume_file_low,volume_file_native): - A_low = check_affine(volume_file_low) - A_native = check_affine(volume_file_native) - dim_low = get_voxel_size(volume_file_low) +# def adapt_reslice_vector_for_native_resolution(vector,volume_file_low,volume_file_native): +# A_low = check_affine(volume_file_low) +# A_native = check_affine(volume_file_native) +# dim_low = get_voxel_size(volume_file_low) - dim_native = get_voxel_size(volume_file_native) +# dim_native = get_voxel_size(volume_file_native) - # adapt direction vectors: - vector['x'] = convert_coordinates(A_native,A_low,vector['x']) - convert_coordinates(A_native,A_low,[0,0,0]) - vector['y'] = convert_coordinates(A_native,A_low,vector['y']) - convert_coordinates(A_native,A_low,[0,0,0]) +# # adapt direction vectors: +# vector['x'] = convert_coordinates(A_native,A_low,vector['x']) - convert_coordinates(A_native,A_low,[0,0,0]) +# vector['y'] = convert_coordinates(A_native,A_low,vector['y']) - convert_coordinates(A_native,A_low,[0,0,0]) - vector['s'] = np.array([length(vector['x']),length(vector['y'])]) - # also find the scale of vectors that can be used to reslice on orignial CT volume - vector['final_s'] = np.array([vector['s'][0]/dim_low[0]*dim_native[0], vector['s'][1]/dim_low[1]*dim_native[1]]) +# vector['s'] = np.array([length(vector['x']),length(vector['y'])]) +# # also find the scale of vectors that can be used to reslice on orignial CT volume +# vector['final_s'] = np.array([vector['s'][0]/dim_low[0]*dim_native[0], vector['s'][1]/dim_low[1]*dim_native[1]]) - vector['x'] = normalize(vector['x']) - vector['y'] = normalize(vector['y']) - # adapt translation vector - t_low = vector['t'] - vector['t'] = np.asarray([t_low[i] * dim_low[i] / dim_native[i] for i in range(0,t_low.shape[0])]) - return vector +# vector['x'] = normalize(vector['x']) +# vector['y'] = normalize(vector['y']) +# # adapt translation vector +# t_low = vector['t'] +# vector['t'] = np.asarray([t_low[i] * dim_low[i] / dim_native[i] for i in range(0,t_low.shape[0])]) +# return vector # function: set scale for plane re-slicing in the case in which x and y scale are not the same (=1 for both) @@ -543,91 +437,9 @@ def set_scale_for_unequal_x_and_y(vector,zoom_factor = 1): return np.array([1.0/vector['s'][1]*vector['s'][0]/zoom_factor,1.0/zoom_factor]) - -# function: make movies of several .png files -def make_movies(save_path,pngs,fps = 10): - mpr_array=[] - i = cv2.imread(pngs[0]) - h,w,l = i.shape - - for j in pngs: - img = cv2.imread(j) - mpr_array.append(img) - # set fps - if len(pngs) == 16: - fps = 15 # set 16 will cause bug - elif len(pngs) > 20: - fps = len(pngs)//2 - else: - fps = len(pngs) - # save movies - out = cv2.VideoWriter(save_path,cv2.VideoWriter_fourcc(*'mp4v'),fps,(w,h)) - for j in range(len(mpr_array)): - out.write(mpr_array[j]) - out.release() -# function: calculate SNR and CNR -def check_SNR(image,xrange,yrange,calculate_type = 'SNR'): - assert len(image.shape) == 2 - assert len(xrange) == 2 - assert len(yrange) == 2 - - x_range = np.arange(xrange[0],xrange[1],1) - y_range = np.arange(yrange[0],yrange[1],1) - xgrid,ygrid = np.meshgrid(x_range,y_range) - intensity_list = [] - for i in range(0,xgrid.shape[0]): - for j in range(0,xgrid.shape[1]): - intensity_list.append(image[xgrid[i,j],ygrid[i,j]]) - intensity_list = np.asarray(intensity_list) - [peak,bottom,mean,std] = [np.max(intensity_list),np.min(intensity_list),np.mean(intensity_list),np.std(intensity_list)] - info = [peak,bottom,mean,std] - if calculate_type == 'SNR': - ans = peak / std - elif calculate_type == 'CNR': - ans = (peak - bottom) / std - else: - raise ValueError("Wrong calculate type") - return ans,info - -# function: obtain the linear profile in 2D image -def linear_profile(image,start,end): - start = np.asarray(start) - end = np.asarray(end) - vector = normalize(end - start) - profile = [] - count = 1 - while 1 == 1: - point = (start + vector * (count - 1)) - profile.append(image[int(point[0]),int(point[1])]) - if (point[0]>end[0] and vector[0] >=0) or (point[0]end[1] and vector[1] >=0) or (point[1]