def crop_by_mask(img_ori, img_mask, padding_size=20, seg_padding_size=0, rotate=True): # add pad to seg image if seg_padding_size > 0: _, contours, hierachy = cv2.findContours(img_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) img_mask = cv2.drawContours(img_mask, contours, -1, 255, seg_padding_size) # rotate image if rotate: angle = calculate_angle(img_mask) img_mask = rotate_bound(img_mask, angle) img_ori = rotate_bound(img_ori, angle) # Add black padding to input image and seg image img_mask = cv2.copyMakeBorder(img_mask, padding_size, padding_size, padding_size, padding_size, 0) img_ori = cv2.copyMakeBorder(img_ori, padding_size, padding_size, padding_size, padding_size, 0) # get white pixel bounding box x, y, w, h = find_bounding_square(img_mask, padding=padding_size) img_crop = img_ori[int(y):int(y + h), int(x):int(x + w)] return img_crop
def main(seg_path, us_path, mask_path, kidney_list_csv, save_path, padding_size=20, train=True): seg_path = norm_path(seg_path) us_path = norm_path(us_path) mask_path = norm_path(mask_path) save_path = norm_path(save_path) #csv 파일 경로 추가 kidney_list_csv = norm_path(kidney_list_csv) if not os.path.exists(save_path): os.makedirs(os.path.join(save_path, 'kidney')) os.makedirs(os.path.join(save_path, 'non-kidney')) seg_name = file_dict(seg_path) us_name = file_dict(us_path) mask_name = file_dict(mask_path) kidney_set = kidney_file_set(kidney_list_csv) for name_order in tqdm(mask_name.keys()): name, order = name_order.split('#') mask_img = cv2.imread(mask_name[name_order], cv2.IMREAD_GRAYSCALE) us_img = cv2.imread(us_name[name], cv2.IMREAD_GRAYSCALE) # Add black padding to input image and seg image mask_img = cv2.copyMakeBorder(mask_img, padding_size, padding_size, padding_size, padding_size, 0) us_img = cv2.copyMakeBorder(us_img, padding_size, padding_size, padding_size, padding_size, 0) # rotate image angle = calculate_angle(mask_img) mask_img = rotate_bound(mask_img, angle) us_img = rotate_bound(us_img, angle) # get white pixel bounding box x, y, w, h = find_bounding_square(mask_img, padding=padding_size) # crop bounding mask_img = mask_img[int(y):int(y + h), int(x):int(x + w)] us_img = us_img[int(y):int(y + h), int(x):int(x + w)] # mask image shape_img = np.where(mask_img == 255, us_img, 0) # has kidney? if order == '0': if train: has_kidney = name in seg_name.keys() else: has_kidney = name in kidney_set else: has_kidney = False dst_path = os.path.join(save_path, 'kidney' if has_kidney else 'non-kidney') dst_file = os.path.join(dst_path, name_order + '.png') if not os.path.exists(dst_path): os.makedirs(dst_path) # print(dst_file) cv2.imwrite(dst_file, shape_img)
def image_crop_kidney_loader(input_path, seg_path): # input_path : non-kidney image # seg_path : any seg image # output : crop non-kidney image padding_size = args.kidney_crop_padding # read image in grayscale input_image = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE) seg_image = cv2.imread(seg_path, cv2.IMREAD_GRAYSCALE) seg_image = cv2.resize(seg_image, (input_image.shape[1], input_image.shape[0])) # rotate image angle = calculate_angle(seg_image) seg_image = rotate_bound(seg_image, angle) input_image = rotate_bound(input_image, angle) # Add black padding to input image and seg image seg_image = cv2.copyMakeBorder(seg_image, padding_size, padding_size, padding_size, padding_size, 0) input_image = cv2.copyMakeBorder(input_image, padding_size, padding_size, padding_size, padding_size, 0) # get white pixel bounding box x, y, w, h = find_bounding_square(seg_image, padding=padding_size) # crop kidney with padding result_image = input_image[int(y):int(y + h), int(x):int(x + w)] # cv2 img into pil img img_for_pil = Image.fromarray(result_image) resized_img = pil_resize(img_for_pil) # #debug # debug_path = os.path.join(args.result, 'debug') # if not os.path.exists(debug_path): # os.makedirs(debug_path) # debug_file = os.path.join(debug_path, os.path.split(input_path)[1]) # cv2.imwrite(debug_file, result_image) return resized_img
def main(us_path, mask_path, result_path, scale=None, view_scale=None, use_top_n_greatest_width=True, size=None, horizontally=True, crop=False, denoise=True): ''' center boolean: 신장의 중앙 정렬 여부 scale float: 영상 축적 고정 only_greatest_width boolean: 신장 영상중 가장 큰것만 사용할지 여부 resize (W, H): 최종 이미지 크기 ''' us_dict = image_dict(norm_path(us_path)) mask_dict = image_dict(norm_path(mask_path)) result_path = norm_path(result_path, True) for patient, dicoms in Per_patient_fast(): patient_datas = list() for dicom in dicoms: Name = dicom['Name'][:-4] # remove file ext Diagnosis = dicom['Diagnosis'] AccNo = dicom['AccNo'] PhysicalUnitsXDirection = dicom['PhysicalUnitsXDirection'] PhysicalUnitsYDirection = dicom['PhysicalUnitsYDirection'] PhysicalDeltaY = dicom['PhysicalDeltaY'] # cm per pixels PhysicalDeltaX = dicom['PhysicalDeltaX'] # 1 픽셀이 몇 cm 인지 나타냄 # checking the kidney if Name not in mask_dict: # pass the non-kidney images continue # for debug # if Name != '1.2.840.113663.1500.1.295077244.3.8.20101014.92756.625': # continue # checking physical unit(mm) if PhysicalUnitsXDirection != '3' or PhysicalUnitsYDirection != '3' \ and not PhysicalDeltaY and not PhysicalDeltaX: continue PhysicalDeltaY = float(PhysicalDeltaY) PhysicalDeltaX = float(PhysicalDeltaX) # read image us_img = cv2.imread(us_dict[Name], cv2.IMREAD_GRAYSCALE) print(us_dict[Name]) mask_img = cv2.imread(mask_dict[Name], cv2.IMREAD_GRAYSCALE) # assert scale != view_scale, "use only scale or view_scale" if horizontally: angle = calculate_angle(mask_img) mask_img = rotate_bound(mask_img, angle) us_img = rotate_bound(us_img, angle) if scale: us_img = resize_physical_unit(us_img, (PhysicalDeltaX, PhysicalDeltaY), scale) mask_img = resize_physical_unit( mask_img, (PhysicalDeltaX, PhysicalDeltaY), scale) if view_scale: bbX, bbY, bbW, bbH = find_bounding_square(mask_img) fx = view_scale[0] / bbW fy = view_scale[1] / bbH us_img = cv2.resize(us_img, None, fx=fx, fy=fy) mask_img = cv2.resize(mask_img, None, fx=fx, fy=fy) if size: #numpy 좌표값을 얻어낸다 -> argwhere mask_pts = np.argwhere(mask_img == 255) #평균을 구한다 mask_cx, mask_cy = int(np.mean(mask_pts[:, 1])), int( np.mean(mask_pts[:, 0])) #캔버스를 만들고 붙혀넣는다 us_canvas = np.zeros(size, dtype=np.uint8) mask_canvas = np.zeros(size, dtype=np.uint8) # # for debug # us_canvas[:] = 100 # mask_canvas[:] = 100 canvas_h, canvas_w = size canvas_cx, canvas_cy = canvas_w // 2, canvas_h // 2 dst_x, dst_y = canvas_cx - mask_cx, canvas_cy - mask_cy us_img = paste(dst=us_canvas, src=us_img, dst_x=dst_x, dst_y=dst_y) mask_img = paste(dst=mask_canvas, src=mask_img, dst_x=dst_x, dst_y=dst_y) if crop: mask = mask_img.astype(np.bool) us_img = us_img * mask if denoise: us_img = cv2.fastNlMeansDenoising(us_img, None, 10, 7, 21) data = dict() data['us'] = us_img data['mask'] = mask_img data['info'] = dicom patient_datas.append(data) # sort by kidney value patient_datas = sorted( patient_datas, key=lambda x: np.count_nonzero(x['mask'] == 255), reverse=True) # use one or all if use_top_n_greatest_width: cut_n = use_top_n_greatest_width patient_datas = patient_datas[:cut_n] accNo = patient['AccNo'] diagnosis = patient['Diagnosis'] train_val = 'val' if accNo in isangmi_accno_list else 'train' save_path = os.path.join(result_path, train_val, diagnosis, accNo) ''' if args.preprocess_denoise: np_out = np.asarray(out) np_out = cv2.fastNlMeansDenoising(np_out, None, 10, 7, 21) out = Image.fromarray(np.uint8(np_out)) return out''' # save image for order, data in enumerate(patient_datas): us_img = data['us'] name = data['info']['Name'][:-4] save_file = os.path.join(save_path, name + '.png') if not os.path.exists(save_path): os.makedirs(save_path) print(save_file) cv2.imwrite(save_file, us_img) # save order of images if patient_datas: save_file = os.path.join(save_path, 'order.txt') with open(save_file, 'wt') as f: for order, data in enumerate(patient_datas): name = data['info']['Name'][:-4] f.write(name + '\n')
def main(us_path, mask_path, save_path, padding_size=20, train=True): us_path = norm_path(us_path) mask_path = norm_path(mask_path) save_path = norm_path(save_path) if not os.path.exists(save_path): os.makedirs(os.path.join(save_path, 'normal')) os.makedirs(os.path.join(save_path, 'AKI')) os.makedirs(os.path.join(save_path, 'CKD')) us_name = file_dict(us_path) mask_name = file_dict(mask_path) for name_order in tqdm(mask_name.keys()): print('name_order:', name_order) if '#' in name_order: name, order = name_order.split('#') print('name:', name) print('order:', order) else: name = name_order continue print('no has: #') mask_img = cv2.imread(mask_name[name_order], cv2.IMREAD_GRAYSCALE) us_img = cv2.imread(us_name[name], cv2.IMREAD_GRAYSCALE) # Add black padding to input image and seg image mask_img = cv2.copyMakeBorder(mask_img, padding_size, padding_size, padding_size, padding_size, 0) us_img = cv2.copyMakeBorder(us_img, padding_size, padding_size, padding_size, padding_size, 0) # rotate image angle = calculate_angle(mask_img) mask_img = rotate_bound(mask_img, angle) us_img = rotate_bound(us_img, angle) # get white pixel bounding box x, y, w, h = find_bounding_square(mask_img, padding=padding_size) # crop bounding mask_img = mask_img[int(y):int(y + h), int(x):int(x + w)] us_img = us_img[int(y):int(y + h), int(x):int(x + w)] # mask image shape_img = np.where(mask_img == 255, us_img, 0) result_img = preproess_image(shape_img, mask_img) # has kidney? if order == '0': if train: has_kidney = name in seg_name.keys() else: has_kidney = name in kidney_set else: has_kidney = False dst_path = os.path.join(save_path, 'kidney' if has_kidney else 'non-kidney') dst_file = os.path.join(dst_path, name_order + '.png') if not os.path.exists(dst_path): os.makedirs(dst_path) # print(dst_file) cv2.imwrite(dst_file, result_img)
def main(us_path, mask_path, save_path, padding_size=20): us_path = norm_path(us_path) mask_path = norm_path(mask_path) save_path = norm_path(save_path) if not os.path.exists(save_path): os.makedirs(os.path.join(save_path, 'normal')) os.makedirs(os.path.join(save_path, 'AKI')) os.makedirs(os.path.join(save_path, 'CKD')) us_name = file_dict(us_path) mask_name = file_dict(mask_path) for name_order in tqdm(mask_name.keys()): if '#' in name_order: name, order = name_order.split('#') print('saved:', name) if name not in mask_name.keys(): print('no:', name) continue else: print('no has: #') continue mask_img = cv2.imread(mask_name[name_order], cv2.IMREAD_GRAYSCALE) us_img = cv2.imread(us_name[name], cv2.IMREAD_GRAYSCALE) # Add black padding to input image and seg image mask_img = cv2.copyMakeBorder(mask_img, padding_size, padding_size, padding_size, padding_size, 0) us_img = cv2.copyMakeBorder(us_img, padding_size, padding_size, padding_size, padding_size, 0) # rotate image angle = calculate_angle(mask_img) mask_img = rotate_bound(mask_img, angle) us_img = rotate_bound(us_img, angle) # get white pixel bounding box x, y, w, h = find_bounding_square(mask_img, padding=padding_size) # crop bounding mask_img = mask_img[int(y):int(y + h), int(x):int(x + w)] us_img = us_img[int(y):int(y + h), int(x):int(x + w)] # mask image shape_img = np.where(mask_img == 255, us_img, 0) result_img = preproess_image(shape_img, mask_img) KidneyList = ['normal', 'AKI', "CKD"] if KidneyList[0] in us_name[name]: dst_path = os.path.join(save_path, KidneyList[0]) print('save normal') elif KidneyList[1] in us_name[name]: dst_path = os.path.join(save_path, KidneyList[1]) print('save AKI') elif KidneyList[2] in us_name[name]: dst_path = os.path.join(save_path, KidneyList[2]) print('save CKD') else: continue dst_file = os.path.join(dst_path, name_order + '.png') if not os.path.exists(dst_path): os.makedirs(dst_path) # print(dst_file) cv2.imwrite(dst_file, result_img)