Python glob.glob1() Examples

The following are 30 code examples for showing how to use glob.glob1(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module glob , or try the search function .

Example 1
Project: DOTA_models   Author: ringringyi   File: script_preprocess_annoations_S3DIS.py    License: Apache License 2.0 6 votes vote down vote up
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 2
Project: avocado-vt   Author: avocado-framework   File: ppm_utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def have_similar_img(base_img, comp_img_path, threshold=10):
    """
    Check whether comp_img_path have a image looks like base_img.
    """
    support_img_format = ['jpg', 'jpeg', 'gif', 'png', 'pmp']
    comp_images = []
    if os.path.isdir(comp_img_path):
        for ext in support_img_format:
            comp_images.extend([os.path.join(comp_img_path, x) for x in
                                glob.glob1(comp_img_path, '*.%s' % ext)])
    else:
        comp_images.append(comp_img_path)

    for img in comp_images:
        if img_similar(base_img, img, threshold):
            return True
    return False 
Example 3
Project: yolo_v2   Author: rky0930   File: script_preprocess_annoations_S3DIS.py    License: Apache License 2.0 6 votes vote down vote up
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 4
Project: cornerwise   Author: codeforboston   File: cambridgema.py    License: MIT License 6 votes vote down vote up
def import_shapers(logger):
    (_, zip_path) = tempfile.mkstemp()
    (_, http_message) = request.urlretrieve(url, zip_path)
    zip_file = ZipFile(zip_path)
    ex_dir = tempfile.mkdtemp()
    zip_file.extractall(ex_dir)
    shapefiles = glob.glob1(ex_dir, "*.shp")
    lm = LayerMapping(Parcel, "/data/shapefiles/M274TaxPar.shp", {
        "shape_leng": "SHAPE_Leng",
        "shape_area": "SHAPE_Area",
        "map_par_id": "MAP_PAR_ID",
        "loc_id": "LOC_ID",
        "poly_type": "POLY_TYPE",
        "map_no": "MAP_NO",
        "source": "SOURCE",
        "plan_id": "PLAN_ID",
        "last_edit": "LAST_EDIT",
        "town_id": "TOWN_ID",
        "shape": "POLYGON"
    }) 
Example 5
Project: Gun-Detector   Author: itsamitgoel   File: script_preprocess_annoations_S3DIS.py    License: Apache License 2.0 6 votes vote down vote up
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 6
Project: CrisisMappingToolkit   Author: nasa   File: plot_water_levelui.py    License: Apache License 2.0 6 votes vote down vote up
def table_water_level(lake, startdate, enddate, result_dir, output_file=None):
    # Grabs lake names from .txt files in the results folder.
    lakes = [i.split('.')[0] for i in glob.glob1(result_dir,'*txt')]

    # Compares lake names found from .txt files with the chosen lake. If a match is found, the parser is run.
    if lake in lakes:
        lake_dir = result_dir + os.sep + lake + '.txt'
        (features, dates, water, clouds) = parse_lake_results(lake_dir, startdate, enddate)

        # Error-catcher for situation where a date range is selected and no good points are available for plotting.
        if water == False:
            print "No good data points found in selected date range. Please try a larger date range and retry."
        # Table creating and saving block:
        else:
            # Error catching for invalid directories.
            if output_file == None:
                output_file = result_dir + '/' + lake + '.csv'
            with open(output_file, 'wb') as f:
                writer = csv.writer(f)
                writer.writerow(["Date", "Area (km^2)"])
                writer.writerows(izip(dates, water)) 
Example 7
Project: CrisisMappingToolkit   Author: nasa   File: plot_water_levelui.py    License: Apache License 2.0 6 votes vote down vote up
def plot_water_level(lake, startdate, enddate, result_dir):
    # Grabs lake names from .txt files in the results folder.
    lakes = [i.split('.')[0] for i in glob.glob1(result_dir,'*txt')]

    # Compares lake names found from .txt files with the chosen lake. If a match is found, the parser is run.
    if lake in lakes:
        lake = result_dir + os.sep + lake + '.txt'
        (features, dates, water, clouds) = parse_lake_results(lake, startdate, enddate)

        # Error-catcher for situation where a date range is selected and no good points are available for plotting.
        if water == False:
            print "No good data points found in selected date range. Please try a larger date range."
        # plot_results(features, dates, water, clouds, None, 'results/mono_lake_elevation.txt')
        else:
            plot_results(features, dates, water, clouds)
            plt.show()

    # Notifies user if the data file for the selected lake has not been generated yet.
    else:
        print "Specified lake data file not found. Please retrieve data and try again." 
Example 8
Project: porder   Author: tyson-swetnam   File: diffcheck.py    License: Apache License 2.0 6 votes vote down vote up
def checker(folder, typ, infile, item, asset, start, end, cmin, cmax,outfile):
    print('Now Searching....')
    allasset = idl(infile = infile, item = item, asset = asset, start = start, end = end, cmin = cmin, cmax = cmax)
    sprefix = {'PSScene4Band': '_3B', 'REOrthoTile': '_R', 'PSScene3Band': '_3B', 'PSOrthoTile': '_BGRN'}
    sval = sprefix.get(item)
    if typ == 'image':
        filenames = glob.glob1(folder,"*.tif")
        l = []
        for items in filenames:
            l.append(items.split(sval)[0])
        print('Number of items not found locally: '+str(len(set(allasset)-set(l))))
        print('IDlist written to '+str(outfile)+' with '+str(len(set(allasset)-set(l))))
        with open(outfile, "w") as f:
            for s in list(set(allasset)-set(l)):
                f.write(str(s) +"\n")
    if typ=='metadata':
        filenames=glob.glob1(folder,"*.xml")
        l=[]
        for items in filenames:
            l.append(items.split(sval)[0])
        print('Number of items not found locally: '+str(len(set(allasset).difference(set(l)))))
        print('IDlist written to '+str(outfile)+' with '+str(len(set(allasset)-set(l)))+' ids')
        with open(outfile, "w") as f:
            for s in list(set(allasset)-set(l)):
                f.write(str(s) +"\n") 
Example 9
Project: hands-detection   Author: loicmarie   File: script_preprocess_annoations_S3DIS.py    License: MIT License 6 votes vote down vote up
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 10
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 11
Project: object_detection_with_tensorflow   Author: scotthuang1989   File: script_preprocess_annoations_S3DIS.py    License: MIT License 6 votes vote down vote up
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 12
Project: g-tensorflow-models   Author: generalized-iou   File: script_preprocess_annoations_S3DIS.py    License: Apache License 2.0 6 votes vote down vote up
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 13
Project: models   Author: tensorflow   File: script_preprocess_annoations_S3DIS.py    License: Apache License 2.0 6 votes vote down vote up
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 14
def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out 
Example 15
Project: DOTA_models   Author: ringringyi   File: factory.py    License: Apache License 2.0 5 votes vote down vote up
def load_building_meshes(self, building):
    dir_name = os.path.join(building['data_dir'], 'mesh', building['name'])
    mesh_file_name = glob.glob1(dir_name, '*.obj')[0]
    mesh_file_name_full = os.path.join(dir_name, mesh_file_name)
    logging.error('Loading building from obj file: %s', mesh_file_name_full)
    shape = renderer.Shape(mesh_file_name_full, load_materials=True, 
                           name_prefix=building['name']+'_')
    return [shape] 
Example 16
Project: GTDWeb   Author: lanbing510   File: filebased.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _list_cache_files(self):
        """
        Get a list of paths to all the cache files. These are all the files
        in the root cache dir that end on the cache_suffix.
        """
        if not os.path.exists(self._dir):
            return []
        filelist = [os.path.join(self._dir, fname) for fname
                    in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
        return filelist 
Example 17
Project: ironpython2   Author: IronLanguages   File: bitmap.py    License: Apache License 2.0 5 votes vote down vote up
def demo():
	import glob
	winDir=win32api.GetWindowsDirectory()
	for fileName in glob.glob1(winDir, '*.bmp')[:2]:
		bitmapTemplate.OpenDocumentFile(os.path.join(winDir, fileName)) 
Example 18
Project: ironpython2   Author: IronLanguages   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def glob(self, pattern, exclude = None):
        """Add a list of files to the current component as specified in the
        glob pattern. Individual files can be excluded in the exclude list."""
        files = glob.glob1(self.absolute, pattern)
        for f in files:
            if exclude and f in exclude: continue
            self.add_file(f)
        return files 
Example 19
Project: yolo_v2   Author: rky0930   File: factory.py    License: Apache License 2.0 5 votes vote down vote up
def load_building_meshes(self, building):
    dir_name = os.path.join(building['data_dir'], 'mesh', building['name'])
    mesh_file_name = glob.glob1(dir_name, '*.obj')[0]
    mesh_file_name_full = os.path.join(dir_name, mesh_file_name)
    logging.error('Loading building from obj file: %s', mesh_file_name_full)
    shape = renderer.Shape(mesh_file_name_full, load_materials=True, 
                           name_prefix=building['name']+'_')
    return [shape] 
Example 20
Project: cornerwise   Author: codeforboston   File: somervillema.py    License: MIT License 5 votes vote down vote up
def run(logger=None):
    shapefiles_dir = download_shapefiles(shapefile_url, logger)

    try:
        shapefile = os.path.join(
            shapefiles_dir, glob.glob1(shapefiles_dir, "M274TaxPar.shp")[0])
        assessor_data = os.path.join(
            shapefiles_dir, glob.glob1(shapefiles_dir, "M274Assess.dbf")[0])
        import_shapes(shapefile, logger)
        add_assessor_data(assessor_data, logger)
    finally:
        shutil.rmtree(shapefiles_dir) 
Example 21
Project: Gun-Detector   Author: itsamitgoel   File: factory.py    License: Apache License 2.0 5 votes vote down vote up
def load_building_meshes(self, building):
    dir_name = os.path.join(building['data_dir'], 'mesh', building['name'])
    mesh_file_name = glob.glob1(dir_name, '*.obj')[0]
    mesh_file_name_full = os.path.join(dir_name, mesh_file_name)
    logging.error('Loading building from obj file: %s', mesh_file_name_full)
    shape = renderer.Shape(mesh_file_name_full, load_materials=True, 
                           name_prefix=building['name']+'_')
    return [shape] 
Example 22
Project: visual-followme   Author: dronekit   File: file_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_new_file_name(path):
    video_counter = len(glob.glob1(path, "*.avi"))
    filename = "demo_%03d" % video_counter
    return path + time_stamped(filename) + ".avi" 
Example 23
Project: insights-core   Author: RedHatInsights   File: test_specs.py    License: Apache License 2.0 5 votes vote down vote up
def max_globs():
    for f in range(MAX_GLOBS):
        tmpfile = tempfile.NamedTemporaryFile(prefix='tmp_', suffix='_glob', delete=False)
        tmpfile.close()
        with open(tmpfile.name, 'w') as fd:
            fd.write(DATA)
    yield tempfile.gettempdir()
    for fle in glob.glob1(tempfile.gettempdir(), "tmp_*_glob"):
        os.remove(tempfile.gettempdir() + "/" + fle)


# hack to find this source file and not the .pyc version of it 
Example 24
Project: semantic_segmentation   Author: JunshengFu   File: helper.py    License: GNU General Public License v3.0 5 votes vote down vote up
def pred_samples(runs_dir, data_dir, sess, image_shape, logits, keep_prob, input_image, print_speed=False):
    # Make folder for current run
    output_dir = os.path.join(runs_dir, str(time.time()))
    if os.path.exists(output_dir):
        shutil.rmtree(output_dir)
    os.makedirs(output_dir)

    # Run NN on test images and save them to HD
    print('Predicting images...')
    # start epoch training timer

    image_outputs = gen_output(
        sess, logits, keep_prob, input_image, data_dir, image_shape)

    counter = 0
    for name, image, speed_ in image_outputs:
        scipy.misc.imsave(os.path.join(output_dir, name), image)
        if print_speed is True:
            counter+=1
            print("Processing file: {0:05d},\tSpeed: {1:.2f} fps".format(counter, speed_))

        # sum_time += laptime

    # pngCounter = len(glob1(data_dir,'*.png'))

    print('All augmented images are saved to: {}.'.format(output_dir)) 
Example 25
Project: picasso   Author: jungmannlab   File: simulate.py    License: MIT License 5 votes vote down vote up
def loadTif(self):

        self.path = QtWidgets.QFileDialog.getExistingDirectory(
            self, "Select Directory"
        )
        if self.path:

            self.tifCounter = len(_glob.glob1(self.path, "*.tif"))
            self.tifFiles = _glob.glob(os.path.join(self.path, "*.tif"))

            self.table.setRowCount(int(self.tifCounter))
            self.table.setColumnCount(6)
            self.table.setHorizontalHeaderLabels(
                [
                    "FileName",
                    "Imager concentration[nM]",
                    "Integration time [ms]",
                    "Laserpower",
                    "Mean [Photons]",
                    "Std [Photons]",
                ]
            )

            for i in range(0, self.tifCounter):
                self.table.setItem(
                    i, 0, QtWidgets.QTableWidgetItem(self.tifFiles[i])
                ) 
Example 26
Project: hands-detection   Author: loicmarie   File: factory.py    License: MIT License 5 votes vote down vote up
def load_building_meshes(self, building):
    dir_name = os.path.join(building['data_dir'], 'mesh', building['name'])
    mesh_file_name = glob.glob1(dir_name, '*.obj')[0]
    mesh_file_name_full = os.path.join(dir_name, mesh_file_name)
    logging.error('Loading building from obj file: %s', mesh_file_name_full)
    shape = renderer.Shape(mesh_file_name_full, load_materials=True, 
                           name_prefix=building['name']+'_')
    return [shape] 
Example 27
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def glob(self, pattern, exclude = None):
        """Add a list of files to the current component as specified in the
        glob pattern. Individual files can be excluded in the exclude list."""
        files = glob.glob1(self.absolute, pattern)
        for f in files:
            if exclude and f in exclude: continue
            self.add_file(f)
        return files 
Example 28
Project: object_detection_kitti   Author: sshleifer   File: factory.py    License: Apache License 2.0 5 votes vote down vote up
def load_building_meshes(self, building):
    dir_name = os.path.join(building['data_dir'], 'mesh', building['name'])
    mesh_file_name = glob.glob1(dir_name, '*.obj')[0]
    mesh_file_name_full = os.path.join(dir_name, mesh_file_name)
    logging.error('Loading building from obj file: %s', mesh_file_name_full)
    shape = renderer.Shape(mesh_file_name_full, load_materials=True, 
                           name_prefix=building['name']+'_')
    return [shape] 
Example 29
Project: ObjectDatasetTools   Author: F2Wang   File: register_scene.py    License: MIT License 5 votes vote down vote up
def load_pcds(path, downsample = True, interval = 1):

    """
    load pointcloud by path and down samle (if True) based on voxel_size 

    """
    

    global voxel_size, camera_intrinsics 
    pcds= []
    
    for Filename in trange(int(len(glob.glob1(path+"JPEGImages","*.jpg"))/interval)):
        img_file = path + 'JPEGImages/%s.jpg' % (Filename*interval)
        # mask = cv2.imread(img_file, 0)
        
        cad = cv2.imread(img_file)
        cad = cv2.cvtColor(cad, cv2.COLOR_BGR2RGB)
        depth_file = path + 'depth/%s.png' % (Filename*interval)
        reader = png.Reader(depth_file)
        pngdata = reader.read()
        depth = np.array(tuple(map(np.uint16, pngdata[2])))
        mask = depth.copy()
        depth = convert_depth_frame_to_pointcloud(depth, camera_intrinsics)


        source = geometry.PointCloud()
        source.points = utility.Vector3dVector(depth[mask>0])
        source.colors = utility.Vector3dVector(cad[mask>0])

        if downsample == True:
            pcd_down = source.voxel_down_sample(voxel_size = voxel_size)
            pcd_down.estimate_normals(geometry.KDTreeSearchParamHybrid(radius = 0.002 * 2, max_nn = 30))
            pcds.append(pcd_down)
        else:
            pcds.append(source)
    return pcds 
Example 30
Project: ObjectDatasetTools   Author: F2Wang   File: compute_gt_poses.py    License: MIT License 5 votes vote down vote up
def load_pcds(path, downsample = True, interval = 1):

    """
    load pointcloud by path and down samle (if True) based on voxel_size 

    """
    

    global voxel_size, camera_intrinsics 
    pcds= []
    
    for Filename in xrange(len(glob.glob1(path+"JPEGImages","*.jpg"))/interval):
        img_file = path + 'JPEGImages/%s.jpg' % (Filename*interval)
        
        cad = cv2.imread(img_file)
        cad = cv2.cvtColor(cad, cv2.COLOR_BGR2RGB)
        depth_file = path + 'depth/%s.png' % (Filename*interval)
        reader = png.Reader(depth_file)
        pngdata = reader.read()
        # depth = np.vstack(map(np.uint16, pngdata[2]))
        depth = np.array(tuple(map(np.uint16, pngdata[2])))
        mask = depth.copy()
        depth = convert_depth_frame_to_pointcloud(depth, camera_intrinsics)


        source = geometry.PointCloud()
        source.points = utility.Vector3dVector(depth[mask>0])
        source.colors = utility.Vector3dVector(cad[mask>0])

        if downsample == True:
            pcd_down = source.voxel_down_sample(voxel_size = voxel_size)
            pcd_down.estimate_normals(geometry.KDTreeSearchParamHybrid(radius = 0.002 * 2, max_nn = 30))
            pcds.append(pcd_down)
        else:
            pcds.append(source)
    return pcds