import os import time from binascii import b2a_hex import cv2 import numpy as np #import nibabel as nib import base64 from Crypto.Cipher import AES def encrypt(text): key = '1234561234561234' cryptor = AES.new(key, AES.MODE_CBC, key) count = len(text) add = len(key) - (count % len(key)) text = text + ('\0' * add) ciphertext = cryptor.encrypt(text) return b2a_hex(ciphertext) def decrypt_oralce(text): key = '123456' aes = AES.new(add_to_16(key), AES.MODE_ECB) base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8')) decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '') return decrypted_text def add_to_16(value): while len(value) % 16 != 0: value += '\0' return str.encode(value) # 返回bytesl def index_to_list(indexs): if indexs: strList = indexs[:-1].split('],') list = [] for idx, str in enumerate(strList): stri = str[1:].split(',') map = {'x': stri[0], 'y': stri[1]} list.append(map) return list def index_to_meta(indexs): list = index_to_list(indexs) x = min_by_key(list, 'x') y = min_by_key(list, 'y') w = max_by_key(list, 'x') - min_by_key(list, 'x') + 1 h = max_by_key(list, 'y') - min_by_key(list, 'y') + 1 spot = ''.zfill(w * h) spot_len = len(spot) for m in list: flag = (int(m['y']) - y) * w + (int(m['x']) - x) spot = spot[0:flag] + '1' + spot[flag+1:spot_len] strs = get_str_list(spot, 32) array = '[' for s in strs: array = array + '%d,' % (parse_unsigned_int(s, 2)) array = array[:-1] + ']' meta = '{"x":%s,"y":%s,"w":%s,"h":%s,"delineation":%s}' % (x, y, w, h, array) return meta def parse_unsigned_int(s, radix): length = len(s) if length > 0: firstChar = int(s[0]) if firstChar > 0: newstr='' for str in s[1:]: if str == '0': newstr = newstr + '1' else: newstr = newstr + '0' return -(int(newstr, radix) + 1) else: return int(s, radix) def get_str_list(instr, length): size = len(instr) / length if len(instr) % length != 0: s = '00000000000000000000000000000000000' instr = instr + s[len(instr) % length:] size += 1 return get_str_list_size(instr, length, size) def get_str_list_size(instr, length, size): list = [] for i in range(int(size)): childStr = substring(instr, i * length, (i + 1) * length) list.append(childStr) return list def substring(str, f, t): if f > len(str): return None if t > len(str): return str[f:len(str)] else: return str[f:t] def sub(str, p, c): newstr = [] for s in str: newstr.append(s) newstr[p] = c return ''.join(newstr) def min_by_key(coll, key): if coll: candidate = coll[0][key] for map in coll: if int(map[key]) < int(candidate): candidate = map[key] return int(candidate) def max_by_key(coll, key): if coll: candidate = coll[0][key] for map in coll: if int(map[key]) > int(candidate): candidate = map[key] return int(candidate) def sigmoid(X): return 1 / (1 + np.exp(-X)) ''' def load_image(input_file): return nib.load(input_file) def get_image(data, affine, nib_class=nib.Nifti1Image): return nib_class(dataobj=data, affine=affine) ''' def hu_value_clip(image, hu_min=-1200.0, hu_max=600.0, hu_nan=-2000.0): image_new = np.asarray(image) image_new[np.isnan(image_new)] = hu_nan image_new = np.clip(image_new, hu_min, hu_max) return image_new #对ct原像素进行处理,将其像素值进行规范化 def hu_value_to_uint8(original_data, hu_min=-1200.0, hu_max=600.0, hu_nan=-2000.0): image_new = np.asarray(original_data) image_new[np.isnan(image_new)] = hu_nan # normalize to [0, 1] image_new = (image_new - hu_min) image_new = image_new / (hu_max - hu_min) image_new = np.clip(image_new, 0, 1) image_new = (image_new * 255).astype(np.float32) return image_new #将数据转化到(-1,1) def normalize(image): image_new = np.asarray(image) image_new = (image_new - 128.0) / 128.0 return image_new def hu_normalize(original_data, hu_nan=-1000): image_new = np.asarray(original_data) image_new[np.isnan(image_new)] = hu_nan image_new = image_new / 1000 image_new = np.clip(image_new, -1, 1) image_new = image_new.astype(np.float32) return image_new def check_and_makedirs(output_file, is_file=True): if is_file: output_dir = os.path.dirname(output_file) else: output_dir = output_file #如果文件夹下面存在文件,则将其全部删除 if os.path.exists(output_file): os.remove(output_file) if output_dir is not None and output_dir != '' and not os.path.exists(output_dir): os.makedirs(output_dir) def get_z_start_end_from_bound(data, z_center, bound_size): z_start, z_end = max(z_center - bound_size, 0), min(z_center + bound_size, data.shape[0]) return z_start, z_end def get_crop_start_end(start, end, crop_size): center = (start + end) // 2 crop_start = center - np.asarray(crop_size) // 2 crop_start = np.maximum(crop_start, 0) return crop_start, crop_start + crop_size def print_data_mask(data, mask, filename=None, group=False): coords = np.asarray(np.where(mask > 0)) if len(coords[0]) > 0: new_start = coords.min(axis=1) new_end = coords.max(axis=1) + 1 print_mask = mask[new_start[0]:new_end[0], new_start[1]:new_end[1]] print_data = data[new_start[0]:new_end[0], new_start[1]:new_end[1]] if filename is not None: with open(filename, 'w') as f: for temp_data in print_data: f.write(np.array2string(temp_data).replace('\n', '') + '\n') for temp_mask in print_mask: f.write(np.array2string(temp_mask).replace('\n', '') + '\n') if group: for temp_data, temp_mask in zip(print_data, print_mask): temp_group = np.array([str(i) + '(' + str(j) + ')' for i, j in zip(temp_data, temp_mask)]) f.write(np.array2string(temp_group).replace('\n', '').replace('\'', '') + '\n') else: for temp_data in print_data: print(np.array2string(temp_data).replace('\n', '') + '\n') for temp_mask in print_mask: print(np.array2string(temp_mask).replace('\n', '') + '\n') if group: for temp_data, temp_mask in zip(print_data, print_mask): temp_group = np.array([str(i) + '(' + str(j) + ')' for i, j in zip(temp_data, temp_mask)]) print(np.array2string(temp_group).replace('\n', '').replace('\'', '') + '\n') def base64_to_list(base64_str): indexs = '' list = [] img_np = None if base64_str: time_now = time.time() img_data = base64.b64decode(base64_str[22:]) nparr = np.fromstring(img_data, np.uint8) img_np = cv2.imdecode(nparr, 0) img_np[img_np != 0] = 1 point_list = np.where(img_np != 0) if len(point_list[0]) > 0: y_list = point_list[0] x_list = point_list[1] indexs = '{' for point_idx, x in enumerate(x_list): raw_x = x raw_y = y_list[point_idx] map = {'x': raw_x, 'y': raw_y} list.append(map) indexs = indexs + '[%s,%s],' % (raw_x, raw_y) indexs = indexs[:-1] + '}' #print('run time {:.5f}(s)'.format(time.time() - time_now)) return list, indexs, img_np