Python list image

60 Python code examples are found related to " list image". 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.
Example 1
Source File: cmd.py    From pcocc with GNU General Public License v3.0 7 votes vote down vote up
def print_image_list(images):
    tbl = TextTable("%name %type %revision %repo %owner %date")
    for img in sorted(images.itervalues(), key=lambda i:i[i.keys()[0]]["name"]):
        rev = max(img.keys())
        ts = time.localtime(img[rev]["timestamp"])
        str_time = time.strftime('%Y-%m-%d %H:%M:%S', ts)
        repo = img[rev]["repo"]

        tbl.append({'name'     : img[rev]["name"],
                    'type'     : img[rev]["kind"],
                    'revision' : str(rev),
                    'repo'     : repo,
                    'owner'    : img[rev]["owner"],
                    "date"     : str_time})

    print tbl 
Example 2
Source File: run_augmentation_pool_map.py    From dlcv_for_beginners with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_image_list(args):
    filenames = os.listdir(args.input_dir)
    num_imgs = len(filenames)

    num_ave_aug = int(math.floor(args.num/num_imgs))
    rem = args.num - num_ave_aug*num_imgs
    lucky_seq = [True]*rem + [False]*(num_imgs-rem)
    random.shuffle(lucky_seq)

    img_list = [
        (os.sep.join([args.input_dir, filename]), num_ave_aug+1 if lucky else num_ave_aug)
        for filename, lucky in zip(filenames, lucky_seq)
    ]

    random.shuffle(img_list)  # in case the file size are not uniformly distributed
    return img_list 
Example 3
Source File: datagenerator.py    From MC-CNN-python with MIT License 6 votes vote down vote up
def read_image_list(self, image_list):
        """
            form lists of left, right & ground truth paths
        """
        with open(image_list) as f:

            lines = f.readlines()
            self.left_paths = []
            self.right_paths = []
            self.gt_paths = []

            for l in lines:
                sl = l.strip()
                self.left_paths.append(sl)
                self.right_paths.append(sl.replace(self.in_left_suffix, self.in_right_suffix))
                self.gt_paths.append(sl.replace(self.in_left_suffix, self.gt_suffix))
            
            # store total number of data
            self.data_size = len(self.left_paths)
            print "total image num in file {} is {}".format(image_list, self.data_size) 
Example 4
Source File: preprocess.py    From ck-mlperf with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_image_list(images_dir, images_count, skip_images):
  assert os.path.isdir(images_dir), 'Input dir does not exit'
  files = [f for f in os.listdir(images_dir) if os.path.isfile(os.path.join(images_dir, f))]
  files = [f for f in files if re.search(r'\.jpg$', f, re.IGNORECASE)
                            or re.search(r'\.jpeg$', f, re.IGNORECASE)]
  assert len(files) > 0, 'Input dir does not contain image files'
  files = sorted(files)[skip_images:]
  assert len(files) > 0, 'Input dir does not contain more files'
  images = files[:images_count]
  # Repeat last image to make full last batch
  if len(images) < images_count:
    for _ in range(images_count-len(images)):
      images.append(images[-1])
  return images


# Zoom to target size 
Example 5
Source File: generic_searcher.py    From ColumbiaImageSearch with Apache License 2.0 6 votes vote down vote up
def search_image_path_list(self, image_list, options_dict=dict()):
    """Search from a list of images paths.

    :param image_list: list of images paths
    :type image_list: list
    :param options_dict: options dictionary
    :type options_dict: dict
    :return: formatted output of search results
    :rtype: OrderedDict
    """
    # To deal with a featurizer without detection, just pass the imgio 'get_buffer_from_file' function
    # NB: path would be path from within the docker...
    if self.detector is None:
      from ..imgio.imgio import get_buffer_from_filepath
      detect_load_fn = lambda x: get_buffer_from_filepath(x)
    else:
      detect_load_fn = self.detector.detect_from_filepath
    return self._search_from_any_list(image_list, detect_load_fn, options_dict, push_img=True) 
Example 6
Source File: utils.py    From progressive_growing_of_gans_tensorflow with MIT License 6 votes vote down vote up
def read_image_list(category):
    filenames = []
    print("list file")
    list = os.listdir(category)
    list.sort()
    for file in list:
        if 'jpg' in file:
            filenames.append(category + "/" + file)
    print("list file ending!")
    length = len(filenames)
    perm = np.arange(length)
    np.random.shuffle(perm)
    filenames = np.array(filenames)
    filenames = filenames[perm]

    return filenames 
Example 7
Source File: image_reader_classfc.py    From dcsp_segmentation with MIT License 6 votes vote down vote up
def read_labeled_image_forward_list(data_dir, data_list):
    """Reads txt file containing paths to images and ground truths.
    
    Args:
      data_dir: path to the directory with images and masks.
      data_list: path to the file with lines of the form
      '/path/to/image /path/to/image-labels'.
       
    Returns:
      Two lists with all file names for images and image-labels, respectively.
    """

    f = open(data_list, 'r')
    images = []
    catgs = []
    for line in f:
        image, catg = line.strip("\n").split(' ')
        images.append(data_dir + image)
        catgs.append(data_dir + catg)
    return images, catgs 
Example 8
Source File: image_reader.py    From dcsp_segmentation with MIT License 6 votes vote down vote up
def read_labeled_image_list(data_dir, data_list):
    """Reads txt file containing paths to images and ground truth masks.
    
    Args:
      data_dir: path to the directory with images and masks.
      data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
       
    Returns:
      Two lists with all file names for images and masks, respectively.
    """
    f = open(data_list, 'r')
    images = []
    masks = []
    for line in f:
        try:
            image, mask = line.strip("\n").split(' ')
        except ValueError: # Adhoc for test.
            image = mask = line.strip("\n")
        images.append(data_dir + image)
        masks.append(data_dir + mask)
    return images, masks 
Example 9
Source File: Imagenet.py    From ADL with MIT License 6 votes vote down vote up
def get_image_list(self, split):
        fname = ospj(self.meta_dir, '{}.txt'.format(split))
        with open(fname) as f:
            ret = []
            for line in f.readlines():
                if split == 'train':
                    name, cls = line.strip().split()
                    xa = ya = xb = yb = 1
                elif split == 'val':
                    name, cls, xa, ya, xb, yb = line.strip().split()
                else:
                    raise KeyError("Unavailable split: {}".format(split))

                bbox = np.array(
                    [(float(xa), float(ya)), (float(xb), float(yb))],
                    dtype=np.float)
                ret.append((name.strip(), int(cls), bbox))
        return ret 
Example 10
Source File: view_convert_dataset.py    From costar_plan with Apache License 2.0 6 votes vote down vote up
def ConvertImageListToNumpy(data, format='numpy', data_format='NHWC', dtype=np.uint8):
    """ Convert a list of binary jpeg or png files to numpy format.

    # Arguments

    data: a list of binary jpeg images to convert
    format: default 'numpy' returns a 4d numpy array,
        'list' returns a list of 3d numpy arrays
    """
    images = []
    for raw in data:
        img = JpegToNumpy(raw)
        if data_format == 'NCHW':
            img = np.transpose(img, [2, 0, 1])
        images.append(img)
    if format == 'numpy':
        images = np.array(images, dtype=dtype)
    return images 
Example 11
Source File: image_generator.py    From MedicalDataAugmentationTool with GNU General Public License v3.0 6 votes vote down vote up
def get_np_image_list(self, output_image_sitk):
        """
        Converts an sitk image to a list of np arrays, depending on the number of
        pixel components (RGB or grayscale).
        :param output_image_sitk: The sitk image to convert.
        :return: A list of np array.
        """
        output_image_list_np = []
        output_image_np = utils.sitk_np.sitk_to_np(output_image_sitk, self.np_pixel_type)
        pixel_components = output_image_sitk.GetNumberOfComponentsPerPixel()
        if pixel_components > 1:
            for i in range(pixel_components):
                output_image_list_np.append(output_image_np[..., i])
        else:
            output_image_list_np.append(output_image_np)
        return output_image_list_np 
Example 12
Source File: v3workspace_idimagecatalogs_api.py    From whoville with Apache License 2.0 6 votes vote down vote up
def list_image_catalogs_by_workspace(self, workspace_id, **kwargs):
        """
        list image catalogs for the given workspace
        Provides an interface to determine available Virtual Machine images for the given version of Cloudbreak.
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.list_image_catalogs_by_workspace(workspace_id, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param int workspace_id: (required)
        :return: list[ImageCatalogResponse]
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.list_image_catalogs_by_workspace_with_http_info(workspace_id, **kwargs)
        else:
            (data) = self.list_image_catalogs_by_workspace_with_http_info(workspace_id, **kwargs)
            return data 
Example 13
Source File: evaluation.py    From xView1_baseline with Apache License 2.0 6 votes vote down vote up
def compute_precision_recall_given_image_statistics_list(
    iou_threshold, image_statistics_list):
  """Computes the precision recall numbers given iou_threshold and statistics.

  Args:
      iou_threshold: the iou_threshold under which the statistics are computed.
      image_statistics_list: a list of the statistics computed and returned
      by the compute_statistics_given_rectangle_matches method for a list of
      images.
  Returns:
      A dictionary holding the precision, recall as well as the inputs.
  """
  total_positives = 0
  true_positives = 0
  false_positives = 0
  for statistics in image_statistics_list:
    total_positives += statistics['total_positives']
    true_positives += statistics['true_positives']
    false_positives += statistics['false_positives']
  precision = safe_divide(true_positives, true_positives + false_positives)
  recall = safe_divide(true_positives, total_positives)
  return {'iou_threshold': iou_threshold,
          'precision': precision,
          'recall': recall,
          'image_statistics_list': image_statistics_list} 
Example 14
Source File: attack.py    From The-Stolen-Crown-RPG with MIT License 6 votes vote down vote up
def make_image_list(self):
        """
        Make a list of images to cycle through for the
        animation.
        """
        image_list = []

        for row in range(8):
            for column in range(8):
                posx = column * 128
                posy = row * 128
                new_image = self.get_image(posx, posy, 128, 128,
                                           self.spritesheet)
                image_list.append(new_image)

        return image_list 
Example 15
Source File: K8sSecret.py    From kubernetes-py with Apache License 2.0 6 votes vote down vote up
def list_image_pull_secrets(config=None):
        _list = K8sSecret(config=config, name="yo").list()
        secrets = []
        for x in _list:
            if x.type == Secret.K8s_TYPE_DOCKER_CONFIG:
                secrets.append(x)
        return secrets 
Example 16
Source File: create_mscoco_subset.py    From nnabla-examples with Apache License 2.0 6 votes vote down vote up
def create_image_list(args, N, which):
    annotation_path = os.path.join(
        args.data_path, 'annotations/instances_' + which + '2014.json')
    data_json = json.load(open(annotation_path, 'r'))
    annotation_data = data_json['annotations']
    images_by_class = defaultdict(set)
    for data in annotation_data:
        class_id = data['category_id']
        if class_id in args.selected_classes:
            images_by_class[class_id].add(data['image_id'])
    # Obtain N files per categories
    image_subset = set()
    for ids in args.selected_classes:
        image_subset.update(list(images_by_class[ids])[:N])
    # Save a list of files
    image_subset = list(map(lambda x: args.data_path+'/images/'+which +
                            '2014/COCO_'+which+'2014_' + '%012d.jpg' % int(x), image_subset))
    path = os.path.join(args.subset_path, which+'2014.txt')
    with open(path, 'a+') as fo:
        for im in image_subset:
            fo.writelines('%s\n' % im)
    return data_json
    print("################ completed ################") 
Example 17
Source File: image_reader.py    From tensorflow-deeplab-resnet-crf with MIT License 6 votes vote down vote up
def read_labeled_image_list(data_dir, data_list):
    """Reads txt file containing paths to images and ground truth masks.
    
    Args:
      data_dir: path to the directory with images and masks.
      data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
       
    Returns:
      Two lists with all file names for images and masks, respectively.
    """
    f = open(data_list, 'r')
    images = []
    masks = []
    for line in f:
        try:
            image, mask = line.strip("\n").split(' ')
        except ValueError:  # Adhoc for test.
            image = mask = line.strip("\n")
        images.append(data_dir + image)
        masks.append(data_dir + mask)
    return images, masks 
Example 18
Source File: image_reader.py    From SIGGRAPH18SSS with MIT License 6 votes vote down vote up
def read_labeled_image_list(data_dir, data_list):
    """Reads txt file containing paths to images and ground truth masks.
    
    Args:
      data_dir: path to the directory with images and masks.
      data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
       
    Returns:
      Two lists with all file names for images and masks, respectively.
    """
    f = open(data_list, 'r')
    images = []
    masks = []
    for line in f:
        try:
            image, mask = line.strip("\n").split(' ')
        except ValueError: # Adhoc for test.
            image = mask = line.strip("\n")
        images.append(os.path.join(data_dir, image))
        masks.append(os.path.join(data_dir, mask))
    return images, masks 
Example 19
Source File: image_reader.py    From SegSort with MIT License 6 votes vote down vote up
def read_labeled_image_list(data_dir, data_list):
  """Reads txt file containing paths to images and ground truth masks.
    
  Args:
    data_dir: A string that specifies the root of images and masks.
    data_list: A string that specifies the relative locations of images and masks.
       
  Returns:
    images: A list of strings for image paths.
    masks: A list of strings for mask paths.
  """
  f = open(data_list, 'r')
  images = []
  masks = []
  for line in f:
    try:
      image, mask = line.strip("\n").split(' ')
    except ValueError: # Adhoc for test.
      image = mask = line.strip("\n")
    images.append(data_dir + image)
    masks.append(data_dir + mask)
  return images, masks 
Example 20
Source File: Read_Image_List.py    From PEPSI-Fast_image_inpainting_with_parallel_decoding_network with MIT License 6 votes vote down vote up
def read_labeled_image_list(image_list_file):
    #"""Reads a .txt file containing pathes and labeles
    #Args:
    #   image_list_file: a .txt file with one /path/to/image per line
    #   label: optionally, if set label will be pasted after each line
    #Returns:
    #   List with all filenames in file image_list_file

    f = open(image_list_file, 'r')
    filenames1 = []

    Total_Image_Num = 0

    for line in f:
        filename1 = line[:-1]
        filenames1.append(filename1)

        Total_Image_Num = Total_Image_Num + 1

    return filenames1, Total_Image_Num 
Example 21
Source File: database.py    From ETS2Autopilot with MIT License 6 votes vote down vote up
def get_image_list_filter(self, country=None, maneuver=None):
        sql_where = ""
        sql_conditions = []
        sql_condition_values = []
        if country is not None:
            sql_where = " WHERE "
            sql_conditions.append("cty.code=?")
            sql_condition_values.append(country)

        if maneuver is not None:
            sql_where = " WHERE "
            sql_conditions.append("img.maneuver=?")
            sql_condition_values.append(maneuver)

        result = self.db.execute("SELECT img.id, img.filename, img.steering, img.speed, img.throttle, img.maneuver, "
                                 "cty.code FROM image img "
                                 "LEFT JOIN sequence seq ON img.sequence = seq.id "
                                 "LEFT JOIN country cty ON cty.id = seq.country "
                                 "%s%s" % (sql_where, " AND ".join(sql_conditions)), tuple(sql_condition_values))
        if type(result) == str and result.startswith("ERROR"):
            return []
        else:
            return result 
Example 22
Source File: sequence.py    From ETS2Autopilot with MIT License 6 votes vote down vote up
def fill_image_list(self):
        """
        Fill list_image with data.
        """
        data = Data()
        list_images = self.ui.list_images

        model = QStandardItemModel(list_images)
        images = data.get_image_list(self.sequence_id)
        if len(images) > 0:
            for image in images:
                item = QStandardItem("%s - %s" % (image[1], functions.get_indicator(image[5])))
                item.setEditable(False)
                item.setData(str(image[0]), QtCore.Qt.UserRole)
                model.appendRow(item)
        list_images.setModel(model) 
Example 23
Source File: im2rec.py    From SNIPER-mxnet with Apache License 2.0 6 votes vote down vote up
def list_image(root, recursive, exts):
    i = 0
    if recursive:
        cat = {}
        for path, dirs, files in os.walk(root, followlinks=True):
            dirs.sort()
            files.sort()
            for fname in files:
                fpath = os.path.join(path, fname)
                suffix = os.path.splitext(fname)[1].lower()
                if os.path.isfile(fpath) and (suffix in exts):
                    if path not in cat:
                        cat[path] = len(cat)
                    yield (i, os.path.relpath(fpath, root), cat[path])
                    i += 1
        for k, v in sorted(cat.items(), key=lambda x: x[1]):
            print(os.path.relpath(k, root), v)
    else:
        for fname in sorted(os.listdir(root)):
            fpath = os.path.join(root, fname)
            suffix = os.path.splitext(fname)[1].lower()
            if os.path.isfile(fpath) and (suffix in exts):
                yield (i, os.path.relpath(fpath, root), 0)
                i += 1 
Example 24
Source File: vscoscrape.py    From vsco-scraper with MIT License 6 votes vote down vote up
def makeImageList(self, num):
        num +=1
        z = self.session.get(self.mediaurl,params={"size":100,"page":num},headers=constants.media).json()["media"]
        count = len(z)
        while count>0:
            for url in z:
                if '%s.jpg' % str(url["upload_date"])[:-3] in os.listdir() or '%s.mp4' % str(url["upload_date"])[:-3] in os.listdir():
                    continue
                if url['is_video'] is True:
                    self.imagelist.append(["http://%s"% url["video_url"],str(url["upload_date"])[:-3],True])
                    self.pbar.update()
                else:
                    self.imagelist.append(["http://%s"% url["responsive_url"],str(url["upload_date"])[:-3],False])
                    self.pbar.update()
            num +=5
            z = self.session.get(self.mediaurl,params={"size":100,"page":num},headers=constants.media).json()["media"]
            count = len(z)
        return "done" 
Example 25
Source File: utils.py    From Residual_Image_Learning_GAN with MIT License 6 votes vote down vote up
def read_image_list(category):

    filenames = []
    print("list file")
    list = os.listdir(category)
    list.sort()
    for file in list:
        if 'jpg' or 'png' in file:
            filenames.append(category + "/" + file)
    print("list file ending!")

    length = len(filenames)
    perm = np.arange(length)
    np.random.shuffle(perm)
    filenames = np.array(filenames)
    filenames = filenames[perm]

    return filenames 
Example 26
Source File: image_reader.py    From tensorflow-deeplab-lfov with MIT License 6 votes vote down vote up
def read_labeled_image_list(data_dir, data_list):
    """Reads txt file containing paths to images and ground truth masks.
    
    Args:
      data_dir: path to the directory with images and masks.
      data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
       
    Returns:
      Two lists with all file names for images and masks, respectively.
    """
    f = open(data_list, 'r')
    images = []
    masks = []
    for line in f:
        image, mask = line.strip("\n").split(' ')
        images.append(data_dir + image)
        masks.append(data_dir + mask)
    return images, masks 
Example 27
Source File: _secure.py    From python-sdc-client with MIT License 6 votes vote down vote up
def list_image_profiles(self):
        '''**Description**
            List the current set of image profiles.

        **Arguments**
            - None

        **Success Return Value**
            A JSON object containing the details of each profile.

        '''
        url = "{url}/api/v1/profiling/profileGroups/0/profiles".format(
            url = self.url
        )

        res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)
        return self._request_result(res) 
Example 28
Source File: lip_reader.py    From LIP_JPPNet with MIT License 6 votes vote down vote up
def read_labeled_image_list(data_dir, data_list):
    """Reads txt file containing paths to images and ground truth masks.
    
    Args:
      data_dir: path to the directory with images and masks.
      data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
       
    Returns:
      Two lists with all file names for images and masks, respectively.
    """
    f = open(data_list, 'r')
    images = []
    masks = []
    masks_rev = []
    for line in f:
        try:
            image, mask, mask_rev = line.strip("\n").split(' ')
        except ValueError: # Adhoc for test.
            image = mask = mask_rev = line.strip("\n")
        images.append(data_dir + image)
        masks.append(data_dir + mask)
        masks_rev.append(data_dir + mask_rev)
    return images, masks, masks_rev 
Example 29
Source File: global_handler.py    From voltha with Apache License 2.0 6 votes vote down vote up
def ListImageDownloads(self, request, context):
        try:
            log.debug('grpc-request', request=request)
            response = yield self.dispatcher.dispatch('ListImageDownloads',
                                                      request,
                                                      context,
                                                      id=request.id)
            log.debug('grpc-response', response=response)
        except Exception as e:
            log.exception('grpc-exception', e=e)

        if isinstance(response, DispatchError):
            log.warn('grpc-error-response', error=response.error_code)
            context.set_details('Device \'{}\' error'.format(request.id))
            context.set_code(response.error_code)
            returnValue(ImageDownloads())
        else:
            log.debug('grpc-success-response', response=response)
            returnValue(response) 
Example 30
Source File: synchronous_operations.py    From anchore-engine with Apache License 2.0 6 votes vote down vote up
def list_image_users(page=None):
    """
    Returns the list of users the system knows about, based on images from users.
    Queries the set of users in the images list.

    :return: List of user_id strings
    """
    db = get_session()
    if not db:
        db = get_session()
    try:
        users = db.query(Image.user_id).group_by(Image.user_id).all()
        img_user_set = set([rec[0] for rec in users])
    finally:
        db.close()

    return list(img_user_set) 
Example 31
Source File: DAVIS.py    From PReMVOS with MIT License 5 votes vote down vote up
def read_image_and_annotation_list_2017(fn, data_dir):
  imgs = []
  ans = []
  with open(fn) as f:
    for seq in f:
      seq = seq.strip()
      base_seq = seq.split("__")[0]
      imgs_seq = sorted(glob.glob(data_dir + "JPEGImages/480p/" + base_seq + "/*.jpg"))
      ans_seq = [im.replace("JPEGImages", "Annotations").replace(".jpg", ".png") for im in imgs_seq]
      if "__" in seq:
        ans_seq = [x.replace(base_seq, seq) for x in ans_seq]
        imgs_seq = [x.replace(base_seq, seq) for x in imgs_seq]
      imgs += imgs_seq
      ans += ans_seq
  return imgs, ans 
Example 32
Source File: database.py    From ETS2Autopilot with MIT License 5 votes vote down vote up
def get_image_list(self, sequence):
        """
        :param sequence: id of sequence
        :return: List with all images of a sequence
        """
        result = self.db.execute("SELECT id, filename, steering, speed, throttle, maneuver FROM image WHERE sequence=?", (sequence,))
        if type(result) == str and result.startswith("ERROR"):
            return []
        else:
            return result 
Example 33
Source File: ilsvrc.py    From tensorpack with Apache License 2.0 5 votes vote down vote up
def get_image_list(self, name, dir_structure='original'):
        """
        Args:
            name (str): 'train' or 'val' or 'test'
            dir_structure (str): same as in :meth:`ILSVRC12.__init__()`.
        Returns:
            list: list of (image filename, label)
        """
        assert name in ['train', 'val', 'test']
        assert dir_structure in ['original', 'train']
        add_label_to_fname = (name != 'train' and dir_structure != 'original')
        if add_label_to_fname:
            synset = self.get_synset_1000()

        fname = os.path.join(self.dir, name + '.txt')
        assert os.path.isfile(fname), fname
        with open(fname) as f:
            ret = []
            for line in f.readlines():
                name, cls = line.strip().split()
                cls = int(cls)

                if add_label_to_fname:
                    name = os.path.join(synset[cls], name)

                ret.append((name.strip(), cls))
        assert len(ret), fname
        return ret 
Example 34
Source File: ilsvrcsemi.py    From adanet with MIT License 5 votes vote down vote up
def get_image_list(self, name, dir_structure='original', labeled=True):
        """
        Args:
            name (str): 'train' or 'val' or 'test'
            dir_structure (str): same as in :meth:`ILSVRC12.__init__()`.
        Returns:
            list: list of (image filename, label)
        """
        assert name in ['train', 'val', 'test']
        assert dir_structure in ['original', 'train']
        add_label_to_fname = (name != 'train' and dir_structure != 'original')
        if add_label_to_fname:
            synset = self.get_synset_1000()
        
        if labeled:
            print("Read labeled training")
            fname = name + '_labeled.txt'
        else:
            print("Read unlabeled training")
            fname = name + '_unlabeled.txt'
        assert os.path.isfile(fname), fname
        with open(fname) as f:
            lines = f.readlines()
            if labeled:
                lines = lines * 9
                np.random.shuffle(lines)
            ret = []
            for line in lines:
                name, cls = line.strip().split()
                cls = int(cls)

                if add_label_to_fname:
                    name = os.path.join(synset[cls], name)

                ret.append((name.strip(), cls))
        assert len(ret), fname
        print(len(ret))
        return ret 
Example 35
Source File: im2rec.py    From MXNet-Deep-Learning-in-Action with Apache License 2.0 5 votes vote down vote up
def list_image(root, recursive, exts):
    """Traverses the root of directory that contains images and
    generates image list iterator.
    Parameters
    ----------
    root: string
    recursive: bool
    exts: string
    Returns
    -------
    image iterator that contains all the image under the specified path
    """

    i = 0
    if recursive:
        cat = {}
        for path, dirs, files in os.walk(root, followlinks=True):
            dirs.sort()
            files.sort()
            for fname in files:
                fpath = os.path.join(path, fname)
                suffix = os.path.splitext(fname)[1].lower()
                if os.path.isfile(fpath) and (suffix in exts):
                    if path not in cat:
                        cat[path] = len(cat)
                    yield (i, os.path.relpath(fpath, root), cat[path])
                    i += 1
        for k, v in sorted(cat.items(), key=lambda x: x[1]):
            print(os.path.relpath(k, root), v)
    else:
        for fname in sorted(os.listdir(root)):
            fpath = os.path.join(root, fname)
            suffix = os.path.splitext(fname)[1].lower()
            if os.path.isfile(fpath) and (suffix in exts):
                yield (i, os.path.relpath(fpath, root), 0)
                i += 1 
Example 36
Source File: remoteDialog.py    From LabelImgTool with MIT License 5 votes vote down vote up
def get_server_image_list(self):
        if self.server_image_list is not None:
            return self.server_image_list.text()
        else:
            QtGui.QMessageBox.about(
                self,
                "server image list!",
                "the server image list is None!") 
Example 37
Source File: ilsvrc.py    From ternarynet with Apache License 2.0 5 votes vote down vote up
def get_image_list(self, name):
        """
        :param name: 'train' or 'val' or 'test'
        :returns: list of (image filename, cls)
        """
        assert name in ['train', 'val', 'test']
        fname = os.path.join(self.dir, name + '.txt')
        assert os.path.isfile(fname)
        with open(fname) as f:
            ret = []
            for line in f.readlines():
                name, cls = line.strip().split()
                ret.append((name, int(cls)))
        return ret 
Example 38
Source File: utils.py    From bard with GNU General Public License v3.0 5 votes vote down vote up
def extractAnyImageFromList(values):
    expandedList = [(key, val) for key, val in values.items()
                    if not isinstance(val, list)]
    for key, value in values.items():
        if key in ['WM/MCDI', 'WM/UserWebURL', 'CT_Custom', 'CT_MY_RATING']:
            continue

        if isinstance(value, list):
            for val in value:
                expandedList.append((key, val))
        else:
            expandedList.append((key, value))

    for key, value in expandedList:
        if isinstance(value, mutagen.apev2.APEBinaryValue):
            return loadImageFromAPEBinaryValue(value)

        if isinstance(value, mutagen.asf._attrs.ASFByteArrayAttribute):
            return loadImageFromASFByteArrayAttribute(value)

        if isinstance(value, mutagen.mp4.MP4Cover):
            return loadImageFromData(value)

        if isinstance(value, mutagen.id3.APIC) and value.data:
            return loadImageFromData(value.data)

    return None 
Example 39
Source File: definitions.py    From pyclustering with GNU General Public License v3.0 5 votes vote down vote up
def GET_LIST_IMAGE_SAMPLES(symbol):
        default_path = samples.__path__[0] + os.sep + "images" + os.sep + "symbols" + os.sep
        number_sample_symbols = 1
        
        name_file_pattern = "Symbol_%s_Sample%.2d.png"
        list_image_samples = []
        
        for index_image in range(1, number_sample_symbols + 1, 1):
            file_path = default_path + (name_file_pattern % (symbol, index_image))
            list_image_samples.append(file_path)
            
        return list_image_samples 
Example 40
Source File: CustomTree.py    From OpenPLC_Editor with GNU General Public License v3.0 5 votes vote down vote up
def SetImageListCheck(self, sizex, sizey, imglist=None):
        CT.CustomTreeCtrl.SetImageListCheck(self, sizex, sizey, imglist=None)

        self.ExtraImages = {}
        for image in ["function", "functionBlock", "program"]:
            self.ExtraImages[image] = self._imageListCheck.Add(GetBitmap(image.upper())) 
Example 41
Source File: imm_20170906.py    From alibabacloud-python-sdk-v2 with Apache License 2.0 5 votes vote down vote up
def list_image_jobs(self, max_keys=None, marker=None, project=None, job_type=None):
        api_request = APIRequest('ListImageJobs', 'GET', 'http', 'RPC', 'query')
        api_request._params = {
            "MaxKeys": max_keys,
            "Marker": marker,
            "Project": project,
            "JobType": job_type}
        return self._handle_request(api_request).result 
Example 42
Source File: utils.py    From Conditional-GAN with MIT License 5 votes vote down vote up
def read_image_list(category):
    filenames = []
    print("list file")
    list = os.listdir(category)

    for file in list:
        filenames.append(category + "/" + file)

    print("list file ending!")

    return filenames

##from caffe 
Example 43
Source File: hcl_api.py    From intersight-python with Apache License 2.0 5 votes vote down vote up
def get_hcl_driver_image_list(self, **kwargs):  # noqa: E501
        """Read a 'hcl.DriverImage' resource.  # noqa: E501

        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.get_hcl_driver_image_list(async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param str filter: Filter criteria for the resources to return. A URI with a $filter query option identifies a subset of the entries from the Collection of Entries. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the $filter option. The expression language that is used in $filter queries supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false). 
        :param str orderby: Determines what properties are used to sort the collection of resources.
        :param int top: Specifies the maximum number of resources to return in the response.
        :param int skip: Specifies the number of resources to skip in the response.
        :param str select: Specifies a subset of properties to return.
        :param str expand: Specify additional attributes or related resources to return in addition to the primary resources.
        :param str apply: Specify one or more transformation operations to perform aggregation on the resources. The transformations are processed in order with the output from a transformation being used as input for the subsequent transformation. The \"$apply\" query takes a sequence of set transformations, separated by forward slashes to express that they are consecutively applied, i.e. the result of each transformation is the input to the next transformation. Supported aggregation methods are \"aggregate\" and \"groupby\". The **aggregate** transformation takes a comma-separated list of one or more aggregate expressions as parameters and returns a result set with a single instance, representing the aggregated value for all instances in the input set. The **groupby** transformation takes one or two parameters and 1. Splits the initial set into subsets where all instances in a subset have the same values for the grouping properties specified in the first parameter, 2. Applies set transformations to each subset according to the second parameter, resulting in a new set of potentially different structure and cardinality, 3. Ensures that the instances in the result set contain all grouping properties with the correct values for the group, 4. Concatenates the intermediate result sets into one result set. A groupby transformation affects the structure of the result set. 
        :param bool count: The $count query specifies the service should return the count of the matching resources, instead of returning the resources.
        :param str inlinecount: The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response.
        :param str at: Similar to \"$filter\", but \"at\" is specifically used to filter versioning information properties for resources to return. A URI with an \"at\" Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in at operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. 
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: HclDriverImageList
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        return self.get_hcl_driver_image_list_with_http_info(
            **kwargs)  # noqa: E501 
Example 44
Source File: zeiler_plotter.py    From anna with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_image_from_list(patches, num_rows, num_cols):
    count = 0
    row_list = []
    image_list = []
    size = [19, 19, 3]
    for row in range(num_rows):
        for col in range(num_cols):
            row_list.append(zero_pad(patches[count], size))
            count += 1
        row_image = numpy.hstack(row_list)
        row_list = []
        image_list.append(row_image)
    image_image = numpy.vstack(image_list)
    return image_image 
Example 45
Source File: TID2008.py    From IQA_BIECON_release with MIT License 5 votes vote down vote up
def make_image_list(scenes, dist_types=None, show_info=True):
    """
    Make image list from TID2008 database
    TID2008: 25 reference images x 17 distortions x 4 levels
    """
    # Get reference / distorted image file lists:
    # d_img_list and score_list
    d_img_list, r_img_list, score_list = [], [], []
    list_file_name = LIST_FILE_NAME
    with open(list_file_name, 'r') as listFile:
        for line in listFile:
            # ref_idx ref_name dist_name dist_types, DMOS
            (scn_idx, dis_idx, ref, dis, score) = line.split()
            scn_idx = int(scn_idx)
            dis_idx = int(dis_idx)
            if scn_idx in scenes and dis_idx in dist_types:
                d_img_list.append(dis)
                r_img_list.append(ref)
                score_list.append(float(score))

    score_list = np.array(score_list, dtype='float32')
    n_images = len(d_img_list)

    if show_info:
        print(' - Scenes: %s' % ', '.join([str(i) for i in scenes]))
        print(' - Distortion types: %s' % ', '.join(
            [str(i) for i in dist_types]))
        print(' - Number of images: {:,}'.format(n_images))
        print(' - MOS range: [{:.2f}, {:.2f}]'.format(
            np.min(score_list), np.max(score_list)))

    return {
        'scenes': scenes,
        'dist_types': dist_types,
        'base_path': BASE_PATH,
        'n_images': n_images,
        'd_img_list': d_img_list,
        'r_img_list': r_img_list,
        'score_list': score_list} 
Example 46
Source File: input_fetcher.py    From deep-visualization-toolbox with MIT License 5 votes vote down vote up
def get_files_from_siamese_image_list(self):
        # returns list of pair files in requested siamese image list file

        available_files = []

        with open(self.settings.static_files_input_file, 'r') as image_list_file:
            lines = image_list_file.readlines()
            # take first and second tokens from each line
            available_files = [(tsplit(line, True, ' ', ',','\t')[0], tsplit(line, True, ' ', ',','\t')[1])
                               for line in lines if line.strip() != ""]

        return available_files 
Example 47
Source File: input_fetcher.py    From deep-visualization-toolbox with MIT License 5 votes vote down vote up
def get_files_from_image_list(self):
        # returns list of files in requested image list file

        available_files = []

        with open(self.settings.static_files_input_file, 'r') as image_list_file:
            lines = image_list_file.readlines()
            # take first token from each line
            available_files = [tsplit(line, True,' ',',','\t')[0] for line in lines if line.strip() != ""]

        return available_files 
Example 48
Source File: image_reader.py    From SegSort with MIT License 5 votes vote down vote up
def read_unsup_labeled_image_list(data_dir, data_list):
  """Reads txt file containing paths to images and masks for unsupervised SegSort.

  Args:
    data_dir: A string that specifies the root of images and masks.
    data_list: A string that specifies the relative locations of images and masks.

  Returns:
    images: A list of strings for image paths.
    masks: A list of strings for mask paths.
    segs: A list of strings for boundary segmentation paths.
  """
  f = open(data_list, 'r')
  images = []
  masks = []
  segs = []
  for line in f:
    try:
      image, mask = line.strip("\n").split(' ')
    except ValueError: # Adhoc for test.
      image = mask = line.strip("\n")
    seg = mask.replace('segcls', 'hed')
    images.append(data_dir + image)
    masks.append(data_dir + mask)
    segs.append(data_dir + seg)
  return images, masks, segs 
Example 49
Source File: DAVIS.py    From PReMVOS with MIT License 5 votes vote down vote up
def read_image_and_annotation_list(fn, data_dir):
  imgs = []
  ans = []
  with open(fn) as f:
    for l in f:
      sp = l.split()
      an = data_dir + sp[1]
      im = data_dir + sp[0]
      imgs.append(im)
      ans.append(an)
  return imgs, ans 
Example 50
Source File: base.py    From ATX with Apache License 2.0 5 votes vote down vote up
def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
    """List all images under path

    @return unicode list
    """
    for filename in os.listdir(path):
        bname, ext = os.path.splitext(filename)
        if ext.lower() not in VALID_IMAGE_EXTS:
            continue
        filepath = os.path.join(path, filename)
        yield strutils.decode(filepath) 
Example 51
Source File: rpn_generator.py    From DetectAndTrack with Apache License 2.0 5 votes vote down vote up
def get_image_list(ind_range):
    dataset = JsonDataset(cfg.TEST.DATASET)
    roidb = dataset.get_roidb()

    if ind_range is not None:
        total_num_images = len(roidb)
        start, end = ind_range
        roidb = roidb[start:end]
    else:
        start = 0
        end = len(roidb)
        total_num_images = end

    return roidb, start, end, total_num_images 
Example 52
Source File: images.py    From anchore-engine with Apache License 2.0 5 votes vote down vote up
def list_image_metadata(imageDigest):
    try:
        localconfig = anchore_engine.configuration.localconfig.get_config()
        return_object = localconfig.get('image_metadata_types', [])
        httpcode = 200
    except Exception as err:
        httpcode = 500
        return_object = str(err)

    return return_object, httpcode 
Example 53
Source File: caa.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_image_list(releaseid):
    """Get the list of cover art associated with a release.

    The return value is the deserialized response of the `JSON listing
    <http://musicbrainz.org/doc/Cover_Art_Archive/API#.2Frelease.2F.7Bmbid.7D.2F>`_
    returned by the Cover Art Archive API.

    If an error occurs then a :class:`~musicbrainzngs.ResponseError` will
    be raised with one of the following HTTP codes:

    * 400: `Releaseid` is not a valid UUID
    * 404: No release exists with an MBID of `releaseid`
    * 503: Ratelimit exceeded
    """
    return _caa_request(releaseid) 
Example 54
Source File: caa.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_release_group_image_list(releasegroupid):
    """Get the list of cover art associated with a release group.

    The return value is the deserialized response of the `JSON listing
    <http://musicbrainz.org/doc/Cover_Art_Archive/API#.2Frelease-group.2F.7Bmbid.7D.2F>`_
    returned by the Cover Art Archive API.

    If an error occurs then a :class:`~musicbrainzngs.ResponseError` will
    be raised with one of the following HTTP codes:

    * 400: `Releaseid` is not a valid UUID
    * 404: No release exists with an MBID of `releaseid`
    * 503: Ratelimit exceeded
    """
    return _caa_request(releasegroupid, entitytype="release-group") 
Example 55
Source File: Icons.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def ClearImageList():
    """
    Clear the global wxImageList.
    """
    gImageList.RemoveAll()
    # clear out all instance variables for all icons, except the key variable
    for clsType in (IconBase, ActionSubIcon, PluginSubIcon):
        for icon in clsType.cache.itervalues():
            icon.__dict__ = {"key": icon.key} 
Example 56
Source File: tags.py    From astrobin with GNU Affero General Public License v3.0 5 votes vote down vote up
def search_image_list(context, paginate=True, **kwargs):
    context.update({
        'paginate': paginate,
        'search_domain': context['request'].GET.get('d'),
        'sort': context['request'].GET.get('sort'),
    })

    return context