def browse_picture(self):
self.image = QtGui.QFileDialog.getOpenFileName(None,'OpenFile','c:\\',"Image file(*.png *.jpg)")
#self.progressBar.setValue(0)
self.image = str(self.image)
self.labeLAnomaly.setStyleSheet("QLabel {background-color:red;color:white;}")
self.file_name = ntpath.basename(self.image)
self.file_name, ext=os.path.splitext(self.file_name)
self.file_path = ntpath.dirname(self.image)
self.write_path = ntpath.expanduser('~\\Documents\\Document Analysis')
# creating write path if not exists
if not os.path.exists(self.write_path):
os.makedirs(self.write_path)
if self.image:
self.imgPreview.setPixmap(QtGui.QPixmap(self.image).
scaled(self.imgPreview.width(),
self.imgPreview.height()))
python类basename()的实例源码
def save_images(self, webpage, visuals, image_path):
image_dir = webpage.get_image_dir()
short_path = ntpath.basename(image_path[0])
name = os.path.splitext(short_path)[0]
webpage.add_header(name)
ims = []
txts = []
links = []
for label, image_numpy in visuals.items():
image_name = '%s_%s.png' % (name, label)
save_path = os.path.join(image_dir, image_name)
util.save_image(image_numpy, save_path)
ims.append(image_name)
txts.append(label)
links.append(image_name)
webpage.add_images(ims, txts, links, width=self.win_size)
def save_images(self, webpage, visuals, image_path):
image_dir = webpage.get_image_dir()
short_path = ntpath.basename(image_path[0])
name = os.path.splitext(short_path)[0]
webpage.add_header(name)
ims = []
txts = []
links = []
for label, image_numpy in visuals.items():
image_name = '%s_%s.png' % (name, label)
save_path = os.path.join(image_dir, image_name)
util.save_image(image_numpy, save_path)
ims.append(image_name)
txts.append(label)
links.append(image_name)
webpage.add_images(ims, txts, links, width=self.win_size)
step2_preprocess_test.py 文件源码
项目:TC-Lung_nodules_detection
作者: Shicoder
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def get_patient_spacing():
cn_patient_id = []
dst_dir = settings.TEST_EXTRACTED_IMAGE_DIR
for subject_no in range(settings.TEST_SUBSET_START_INDEX, settings.TEST_SUBSET_TRAIN_NUM):
src_dir = settings.RAW_SRC_DIR + "test_subset0" + str(subject_no) + "/"
src_paths = glob.glob(src_dir + "*.mhd")
for path in src_paths:
patient_id = ntpath.basename(path).replace(".mhd", "")
print("Patient: ", patient_id)
if patient_id=='LKDS-00384':
continue
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
itk_img = SimpleITK.ReadImage(path)
img_array = SimpleITK.GetArrayFromImage(itk_img)
print("Img array: ", img_array.shape)
spacing = numpy.array(itk_img.GetSpacing()) # spacing of voxels in world coor. (mm)
print("Spacing (x,y,z): ", spacing)
cn_patient_id.append([patient_id,spacing[0],spacing[1],spacing[2]])
cn_patient = pandas.DataFrame(cn_patient_id, columns=["patient_id", "spacing_x", "spacing_y", "spacing_z"])
print(cn_patient.head())
cn_patient.to_csv(dst_dir +"patient_spacing.csv", index=False)
step6_predict_nodules.py 文件源码
项目:TC-Lung_nodules_detection
作者: Shicoder
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def get_patient_xyz(path_f):
candidate_index = 0
only_patient = "197063290812663596858124411210"
only_patient = None
patient_list=[]
for subject_no in range(settings.TEST_SUBSET_START_INDEX, settings.TEST_SUBSET_TRAIN_NUM):
src_dir = settings.RAW_SRC_DIR + "test_subset0" + str(subject_no) + "/"
for src_path in glob.glob(src_dir + "*.mhd"):
if only_patient is not None and only_patient not in src_path:
continue
patient_id = ntpath.basename(src_path).replace(".mhd", "")
print(candidate_index, " patient: ", patient_id)
if patient_id=='LKDS-00395' or patient_id == 'LKDS-00434'or patient_id == 'LKDS-00384' or patient_id == 'LKDS-00186':
continue
pos_annos = get_patient_xyz_do(src_path, patient_id,path_f)
patient_list.extend(pos_annos)
candidate_index += 1
df_patient_list = pandas.DataFrame(patient_list, columns=["seriesuid", "coordX", "coordY", "coordZ","probability"])
print("len of can:",len(df_patient_list))
df_patient_list.to_csv("./output_val/prediction_submisssion_luna_manal.csv", index=False)
step6_predict_nodules_validation.py 文件源码
项目:TC-Lung_nodules_detection
作者: Shicoder
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def merge_csv_orign():
df_empty = pandas.DataFrame(columns=['seriesuid','coord_x','coord_y','coord_z','probability',])
src_dir =settings.VAL_NODULE_DETECTION_DIR+'predictions10_luna16_fs/'
# src_dir =settings.VAL_NODULE_DETECTION_DIR
# for r in glob.glob(src_dir + "*_candidates_1.csv"):
for r in glob.glob(src_dir + "*.csv"):
csv=pandas.read_csv(r)
del csv['diameter']
del csv['diameter_mm']
del csv['anno_index']
file_name = ntpath.basename(r)
# patient_id = file_name.replace("_candidates_1.csv", "")
patient_id = file_name.replace(".csv", "")
csv['seriesuid']=patient_id
csv = csv[csv["probability"] >= 0.95]
df_empty = df_empty.append(csv)
id = df_empty['seriesuid']
df_empty.drop(labels=['seriesuid'], axis=1,inplace = True)
df_empty.insert(0, 'seriesuid', id)
df_empty.rename(columns={'coord_x':'coordX','coord_y':'coordY','coord_z':'coordZ'}, inplace = True)
df_empty.to_csv("./output_val/prediction_can_val3.csv",index=False)
step6_predict_nodules_validation.py 文件源码
项目:TC-Lung_nodules_detection
作者: Shicoder
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def get_patient_xyz(path_f):
candidate_index = 0
only_patient = "197063290812663596858124411210"
only_patient = None
patient_list=[]
for subject_no in range(settings.VAL_SUBSET_START_INDEX, settings.VAL_SUBSET_TRAIN_NUM):
src_dir = settings.RAW_SRC_DIR + "val_subset0" + str(subject_no) + "/"
for src_path in glob.glob(src_dir + "*.mhd"):
if only_patient is not None and only_patient not in src_path:
continue
patient_id = ntpath.basename(src_path).replace(".mhd", "")
print(candidate_index, " patient: ", patient_id)
if patient_id == 'LKDS-00557'or patient_id =='LKDS-00978' or patient_id =='LKDS-00881' or patient_id == 'LKDS-00186' or patient_id=='LKDS-00228' or patient_id=='LKDS-00877':
continue
pos_annos = get_patient_xyz_do(src_path, patient_id,path_f)
patient_list.extend(pos_annos)
candidate_index += 1
df_patient_list = pandas.DataFrame(patient_list, columns=["seriesuid", "coordX", "coordY", "coordZ","probability"])
df_patient_list.to_csv("./output_val/prediction_submission_val3.csv", index=False)
def do_put(self, s):
try:
params = s.split(' ')
if len(params) > 1:
src_path = params[0]
dst_path = params[1]
elif len(params) == 1:
src_path = params[0]
dst_path = ''
src_file = os.path.basename(src_path)
fh = open(src_path, 'rb')
dst_path = string.replace(dst_path, '/','\\')
import ntpath
pathname = ntpath.join(ntpath.join(self.__pwd,dst_path), src_file)
drive, tail = ntpath.splitdrive(pathname)
logging.info("Uploading %s to %s" % (src_file, pathname))
self.__transferClient.putFile(drive[:-1]+'$', tail, fh.read)
fh.close()
except Exception, e:
logging.critical(str(e))
pass
def do_put(self, s):
try:
if self.transferClient is None:
self.connect_transferClient()
params = s.split(' ')
if len(params) > 1:
src_path = params[0]
dst_path = params[1]
elif len(params) == 1:
src_path = params[0]
dst_path = '/'
src_file = os.path.basename(src_path)
fh = open(src_path, 'rb')
f = dst_path + '/' + src_file
pathname = string.replace(f,'/','\\')
logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path))
self.transferClient.putFile(self.share, pathname, fh.read)
fh.close()
except Exception, e:
logging.error(str(e))
pass
self.send_data('\r\n')
def do_put(self, s):
try:
params = s.split(' ')
if len(params) > 1:
src_path = params[0]
dst_path = params[1]
elif len(params) == 1:
src_path = params[0]
dst_path = ''
src_file = os.path.basename(src_path)
fh = open(src_path, 'rb')
dst_path = string.replace(dst_path, '/','\\')
import ntpath
pathname = ntpath.join(ntpath.join(self.__pwd,dst_path), src_file)
drive, tail = ntpath.splitdrive(pathname)
logging.info("Uploading %s to %s" % (src_file, pathname))
self.__transferClient.putFile(drive[:-1]+'$', tail, fh.read)
fh.close()
except Exception, e:
logging.critical(str(e))
pass
def do_get(self, src_path):
try:
if self.transferClient is None:
self.connect_transferClient()
import ntpath
filename = ntpath.basename(src_path)
fh = open(filename,'wb')
logging.info("Downloading %s\%s" % (self.share, src_path))
self.transferClient.getFile(self.share, src_path, fh.write)
fh.close()
except Exception, e:
logging.error(str(e))
pass
self.send_data('\r\n')
def do_put(self, s):
try:
if self.transferClient is None:
self.connect_transferClient()
params = s.split(' ')
if len(params) > 1:
src_path = params[0]
dst_path = params[1]
elif len(params) == 1:
src_path = params[0]
dst_path = '/'
src_file = os.path.basename(src_path)
fh = open(src_path, 'rb')
f = dst_path + '/' + src_file
pathname = string.replace(f,'/','\\')
logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path))
self.transferClient.putFile(self.share, pathname, fh.read)
fh.close()
except Exception, e:
logging.error(str(e))
pass
self.send_data('\r\n')
def do_get(self, src_path):
try:
if self.transferClient is None:
self.connect_transferClient()
import ntpath
filename = ntpath.basename(src_path)
fh = open(filename,'wb')
logging.info("Downloading %s\%s" % (self.share, src_path))
self.transferClient.getFile(self.share, src_path, fh.write)
fh.close()
except Exception, e:
logging.critical(str(e))
pass
self.send_data('\r\n')
def do_put(self, s):
try:
if self.transferClient is None:
self.connect_transferClient()
params = s.split(' ')
if len(params) > 1:
src_path = params[0]
dst_path = params[1]
elif len(params) == 1:
src_path = params[0]
dst_path = '/'
src_file = os.path.basename(src_path)
fh = open(src_path, 'rb')
f = dst_path + '/' + src_file
pathname = string.replace(f,'/','\\')
logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path))
self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read)
fh.close()
except Exception, e:
logging.error(str(e))
pass
self.send_data('\r\n')
def getValue(self, keyValue):
# returns a tuple with (ValueType, ValueData) for the requested keyValue
regKey = ntpath.dirname(keyValue)
regValue = ntpath.basename(keyValue)
key = self.findKey(regKey)
if key is None:
return None
if key['NumValues'] > 0:
valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1)
for value in valueList:
if value['Name'] == regValue:
return value['ValueType'], self.__getValueData(value)
elif regValue == 'default' and value['Flag'] <=0:
return value['ValueType'], self.__getValueData(value)
return None
def check_and_repair_framework(self, base):
name = os.path.basename(base)
if ".framework" in name:
basename = name[:-len(".framework")]
finalHeaders = os.path.join(base, "Headers")
finalCurrent = os.path.join(base, "Versions/Current")
finalLib = os.path.join(base, basename)
srcHeaders = "Versions/A/Headers"
srcCurrent = "A"
srcLib = "Versions/A/" + basename
if not os.path.exists(finalHeaders):
os.symlink(srcHeaders, finalHeaders)
if not os.path.exists(finalCurrent):
os.symlink(srcCurrent, finalCurrent)
if not os.path.exists(finalLib):
os.symlink(srcLib, finalLib)
prepare_data.py 文件源码
项目:cervix-roi-segmentation-by-unet
作者: scottykwok
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def resize_addset(source_folder, target_folder, dsize, pattern=FILE_PATTERN):
print('Resizing additional set...')
if not os.path.exists(target_folder): os.makedirs(target_folder)
for clazz in ClassNames:
if clazz not in os.listdir(target_folder):
os.makedirs(os.path.join(target_folder, clazz))
total_images = glob.glob(os.path.join(source_folder, clazz, pattern))
total = len(total_images)
for i, source in enumerate(total_images):
filename = ntpath.basename(source)
target = os.path.join(target_folder, clazz, filename.replace('.jpg', '.png'))
try:
img = cv2.imread(source)
img_resized = cv2.resize(img, dsize, interpolation=cv2.INTER_CUBIC)
cv2.imwrite(target, img_resized)
except:
print('-------------------> error in: {}'.format(source))
if i % 20 == 0:
print("Resized {}/{} images".format(i, total))
def processFile(self, file_fullpath, hostID, instanceID, rowsData):
rowNumber = 0
file_object = loadFile(file_fullpath)
rows = _processAmCacheFile_StringIO(file_object)
file_object.close()
for r in rows:
namedrow = settings.EntriesFields(HostID = hostID, EntryType = settings.__AMCACHE__, RowNumber = rowNumber,
FilePath = (None if r.path == None else ntpath.dirname(r.path)), FileName = (None if r.path == None else ntpath.basename(r.path)),
Size = r.size, ExecFlag = 'True', SHA1 = (None if r.sha1 == None else r.sha1[4:]),
FileDescription = r.file_description, FirstRun = r.first_run, Created = r.created_timestamp, Modified1 = r.modified_timestamp,
Modified2 = r.modified_timestamp2, LinkerTS = r.linker_timestamp, Product = r.product, Company = r.company,
PE_sizeofimage = r.pe_sizeofimage, Version_number = r.version_number, Version = r.version, Language = r.language,
Header_hash = r.header_hash, PE_checksum = r.pe_checksum, SwitchBackContext = r.switchbackcontext, InstanceID = instanceID)
rowsData.append(namedrow)
rowNumber += 1
def processFile(self, file_fullpath, hostID, instanceID, rowsData):
rowNumber = 0
file_object = loadFile(file_fullpath)
rows = _processAmCacheFile_StringIO(file_object)
file_object.close()
for r in rows:
namedrow = settings.EntriesFields(HostID = hostID, EntryType = settings.__AMCACHE__, RowNumber = rowNumber,
FilePath = (None if r.path == None else ntpath.dirname(r.path)), FileName = (None if r.path == None else ntpath.basename(r.path)),
Size = r.size, ExecFlag = 'True', SHA1 = (None if r.sha1 == None else r.sha1[4:]),
FileDescription = r.file_description, FirstRun = r.first_run, Created = r.created_timestamp, Modified1 = r.modified_timestamp,
Modified2 = r.modified_timestamp2, LinkerTS = r.linker_timestamp, Product = r.product, Company = r.company,
PE_sizeofimage = r.pe_sizeofimage, Version_number = r.version_number, Version = r.version, Language = r.language,
Header_hash = r.header_hash, PE_checksum = r.pe_checksum, SwitchBackContext = r.switchbackcontext, InstanceID = instanceID)
rowsData.append(namedrow)
rowNumber += 1
download-subs.py 文件源码
项目:Download-Subtitles-Automatically
作者: ramazmar
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def download_files_subtitles(user,password,files_array):
array_errors = []
open_subs_manager = OpenSubsManager(False)
if open_subs_manager.loginServer(user,password) == False:
array_errors.append("Cant login into open subtitles server")
else:
for i, film_path in enumerate(files_array):
if os.path.isfile(film_path):
return_codes = open_subs_manager.automatically_download_subtitles(film_path,array_languages,"srt")
for key, val in enumerate(return_codes):
if val == 2:
array_errors.append(basename(film_path)+" ( " + array_languages[key] + " ) : Download limit reached")
if val == 4:
array_errors.append(basename(film_path)+" ( " + array_languages[key] + " ) : Couldnt write subtitle to disk")
elif val != 1:
array_errors.append(basename(film_path)+" ( " + array_languages[key] + " ) : Not found valid subtitle")
# Logout
open_subs_manager.logoutServer()
return array_errors
#########################################################################################################################
# MAIN #
#########################################################################################################################
# Get movies array
def parse_ini_file(self, ini_file):
self.active_ini = cp.ConfigParser()
self.active_ini.read(ini_file)
self.active_ini_filename = ini_file
self.section_select.delete(0, tk.END)
for index, section in enumerate(self.active_ini.sections()):
self.section_select.insert(index, section)
self.ini_elements[section] = {}
if "DEFAULT" in self.active_ini:
self.section_select.insert(len(self.active_ini.sections()) + 1, "DEFAULT")
self.ini_elements["DEFAULT"] = {}
file_name = ": ".join([ntpath.basename(ini_file), ini_file])
self.file_name_var.set(file_name)
self.clear_right_frame()
def parse_ini_file(self, ini_file):
self.active_ini = cp.ConfigParser()
self.active_ini.read(ini_file)
self.active_ini_filename = ini_file
self.section_select.delete(0, tk.END)
for index, section in enumerate(self.active_ini.sections()):
self.section_select.insert(index, section)
if "DEFAULT" in self.active_ini:
self.section_select.insert(len(self.active_ini.sections()) + 1, "DEFAULT")
file_name = ": ".join([ntpath.basename(ini_file), ini_file])
self.file_name_var.set(file_name)
self.clear_right_frame()
def browse_picture(self):
image = QtGui.QFileDialog.getOpenFileName(None,'OpenFile','c:\\',"Image file(*.png *.jpg)")
self.progressBar.setValue(0)
image = str(image)
print(image)
self.file_name = ntpath.basename(image)
self.file_name, ext=os.path.splitext(self.file_name)
self.file_path = ntpath.dirname(image)
self.write_path = ntpath.expanduser('~\\Documents\\Document Analysis')
# creating write path if not exists
if not os.path.exists(self.write_path):
os.makedirs(self.write_path)
if image:
self.labelInputImage.setPixmap(QtGui.QPixmap(image).
scaled(self.labelInputImage.width(),
self.labelInputImage.height()))
def execute(self, context):
scene = context.scene
if not scene.sequence_editor:
return {"FINISHED"}
audiofile = bpy.path.abspath(scene.bz_audiofile)
name = ntpath.basename(audiofile)
all_strips = list(sorted(
bpy.context.scene.sequence_editor.sequences_all,
key=lambda x: x.frame_start))
bpy.ops.sequencer.select_all(action="DESELECT")
count = 0
for strip in all_strips:
if strip.name.startswith("bz_" + name):
strip.select = True
bpy.ops.sequencer.delete()
return {"FINISHED"}
def do_get(self, arg, lpath="", r=True):
"Receive file: get <file>"
if not arg:
arg = raw_input("Remote file: ")
if not lpath:
lpath = self.basename(arg)
path = self.rpath(arg) if r else arg
str_recv = self.get(path)
if str_recv != c.NONEXISTENT:
rsize, data = str_recv
lsize = len(data)
# fix carriage return chars added by some devices
if lsize != rsize and len(conv().nstrip(data)) == rsize:
lsize, data = rsize, conv().nstrip(data)
# write to local file
file().write(lpath, data)
if lsize == rsize:
print(str(lsize) + " bytes received.")
else:
self.size_mismatch(rsize, lsize)
def do_put(self, arg, rpath=""):
"Send file: put <local file>"
if not arg:
arg = raw_input("Local file: ")
if not rpath:
rpath = os.path.basename(arg)
rpath = self.rpath(rpath)
lpath = os.path.abspath(arg)
# read from local file
data = file().read(lpath)
if data != None:
self.put(rpath, data)
lsize = len(data)
rsize = self.file_exists(rpath)
if rsize == lsize:
print(str(rsize) + " bytes transferred.")
elif rsize == c.NONEXISTENT:
print("Permission denied.")
else:
self.size_mismatch(lsize, rsize)
# ------------------------[ append <file> <string> ]------------------
def load_TED():
'''Loads a TED file and returns a TrackObject'''
root=tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
file_opt = options = {}
options['defaultextension'] = '.ted'
options['filetypes'] = [('GT6TED', '.ted')]
options['initialdir'] = 'TED'
options['parent'] = root
options['title'] = 'Open file'
path = filedialog.askopenfilename(**file_opt)
filename = basename(path)
root.destroy()
try:
with open(path, mode='rb') as file:
tedfile = file.read()
Track = initFromTedFile(tedfile, filename)
return Track
except FileNotFoundError:
return None
visualizer.py 文件源码
项目:CycleGANwithPerceptionLoss
作者: EliasVansteenkiste
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def save_images(self, webpage, visuals, image_path):
image_dir = webpage.get_image_dir()
short_path = ntpath.basename(image_path[0])
name = os.path.splitext(short_path)[0]
webpage.add_header(name)
ims = []
txts = []
links = []
for label, image_numpy in visuals.items():
image_name = '%s_%s.png' % (name, label)
save_path = os.path.join(image_dir, image_name)
util.save_image(image_numpy, save_path)
ims.append(image_name)
txts.append(label)
links.append(image_name)
webpage.add_images(ims, txts, links, width=self.win_size)
def save_images(self, webpage, visuals, image_path):
image_dir = webpage.get_image_dir()
short_path = ntpath.basename(image_path[0])
name = os.path.splitext(short_path)[0]
webpage.add_header(name)
ims = []
txts = []
links = []
for label, image_numpy in visuals.items():
image_name = '%s_%s.png' % (name, label)
save_path = os.path.join(image_dir, image_name)
util.save_image(image_numpy, save_path)
ims.append(image_name)
txts.append(label)
links.append(image_name)
webpage.add_images(ims, txts, links, width=self.win_size)
def action_inject_delay(self):
stereo = None
if (self.var_3d.get()):
stereo = "top-bottom"
metadata = metadata_utils.Metadata()
metadata.video = metadata_utils.generate_spherical_xml(stereo=stereo)
if self.var_spatial_audio.get():
metadata.audio = metadata_utils.SPATIAL_AUDIO_DEFAULT_METADATA
console = Console()
metadata_utils.inject_metadata(
self.in_file, self.save_file, metadata, console.append)
self.set_message("Successfully saved file to %s\n"
% ntpath.basename(self.save_file))
self.button_open.configure(state="normal")
self.update_state()