Beispiel #1
0
 def plt_image(self, coco_img_list, **kwargs):
     """
     Plot coco image in .json file. Default image source from images['coco_url']
     Keyword Options:
         show_mask {bool} -- Option to display annotation mask. Default: True
         display_cat {bool} -- Option to display category information. Default: False
     Arguments:
         coco_img_list {[type]} -- [description]
     """
     show_mask = get_varargin(kwargs, 'show_mask', True)
     display_cat = get_varargin(kwargs, 'display_cat', False)
     for img_info in coco_img_list:
         try:
             img = skio.imread(img_info['coco_url'])
         except:
             img = skio.imread(img_info['file_name'])
         plt.imshow(img)
         plt.axis('off')
         if show_mask is True:
             annIds = self.coco.getAnnIds(imgIds=img_info['id'])
             anns = self.coco.loadAnns(annIds)
             self.coco.showAnns(anns)
         plt.show()
         if display_cat is True:
             annIds = self.coco.getAnnIds(imgIds=img_info['id'])
             anns = self.coco.loadAnns(annIds)
Beispiel #2
0
 def get_coco_img_id(self, **kwargs):
     """
     Get a list of image ID given category names
     Keyword Options:
         cat_names {list} -- list of category names. Default: None
         nb_image {int} -- number of input images. Default: 1
     Returns:
         [list] -- List of image IDs
     """
     cat_names = get_varargin(kwargs, 'cat_names', None)
     nb_img = get_varargin(kwargs, 'nb_image', 1)
     coco_img_list = self.get_coco_img(cat_names=cat_names, nb_image=nb_img)
     img_id = [coco_img['id'] for coco_img in coco_img_list]
     return img_id
Beispiel #3
0
 def __init__(self, *args, **kwargs):
     '''
         File class for experimental data.
         
         args:
         #####
         :fullfilename: full filename. Format subjID-timestamp-Trial-filetype
         kwargs:
         #######
         :subjID: Subject ID
         :trial: trial number
         :filetype: experimental data type 'eeg', 'kin','imu',etc
     '''
     if args:
         self.filename = args[0]
         return
     # Parsers
     varargin = {'subjID': 'Anonymous', 'trial': 0, 'filetype': ''}
     varargin = utils.get_varargin(varargin, kwargs)
     self.filename = '-'.join([
         varargin['subjID'],
         utils.get_timenow(key=EXPFILE_TIMEKEY),
         'T{:02d}'.format(varargin['trial']),
         varargin['filetype'],
     ])
Beispiel #4
0
 def __init__(self, **kwargs):
     # Parsers
     varargin = utils.get_varargin({'brand': 'Maxon',
                              'tag': 'EC305013'},
                             kwargs)
     for key, val in varargin.items():
         setattr(self,key,val)
     self.get_specs()
Beispiel #5
0
def img_resize(imgpath, **kwargs):
    width = get_varargin(kwargs, 'width', None)
    height = get_varargin(kwargs, 'height', None)
#    Load image
    img = PIL.Image.open(imgpath)
    logging.info('Image path: {}'.format(imgpath))
    logging.info('Image size: {}'.format(img.size))
#   Compute new width and height
    if width is not None:
        scale_factor = width/img.size[0]
        height = int((float(img.size[1]) * float(scale_factor)))
    else:
        scale_factor = height/img.size[1]
        width = int((float(img.size[0]) * float(scale_factor)))
    logging.info('New size: ({}, {})'.format(width,height))
    img = img.resize((width, height), PIL.Image.ANTIALIAS)
    img.save(imgpath)
Beispiel #6
0
 def get_key_values(self, **kwargs):
     """
     Get key value from json object
     Options:
         keys: List of key to get value. Default: All key
     """
     key_list = self.get_keys()
     input_keys = get_varargin(kwargs, 'keys', key_list)
     display_opt = get_varargin(kwargs, 'display', True)
     for key in input_keys:
         if key in key_list:
             strcmd = "self.{} = self.json_obj.get('{}')".format(key, key)
             exec(strcmd)
             if display_opt is True:
                 strcmd = "print(self.{})".format(key)
                 exec(strcmd)
         else:
             logging.info('Key not exist in coco json file: {}'.format(key))
Beispiel #7
0
    def export_segmentation_png(self, coco_img_list, **kwargs):
        export_dir = get_varargin(kwargs, 'export_dir', os.getcwd())
        display_opt = get_varargin(kwargs, 'display', True)
        if not os.path.exists(export_dir):
            os.makedirs(export_dir)
#         imgId_list = [coco_img['id'] for coco_img in coco_img_list]
        filename_list = [
            os.path.splitext(coco_img['file_name'])[0]
            for coco_img in coco_img_list
        ]
        for coco_img, filename in tqdm(zip(coco_img_list, filename_list)):
            imgId = coco_img['id']
            pngPath = Path(export_dir) / '{}.png'.format(filename)
            self.cocoSegmentationToPng(self.coco, imgId, pngPath)
            if display_opt is True:
                plt.figure()
                plt.imshow(skio.imread(pngPath))
                plt.axis('off')
Beispiel #8
0
 def get_coco_img(self, **kwargs):
     """
     Get coco images information in .json file
     Keyword Options:
         cat_names {list} -- list of category names. Default: None
         nb_image {int} -- Number of input images. Default: 1
     Returns:
         [coco_img] -- list of coco image dictionary in .json file
     """
     cat_names = get_varargin(kwargs, 'cat_names', None)
     nb_img = get_varargin(kwargs, 'nb_image', 1)
     coco_cats = self.coco.getCatIds(catNms=cat_names)
     img_id = self.coco.getImgIds(catIds=coco_cats)
     if nb_img > len(img_id):
         nb_img = len(img_id)
     pick = np.random.choice(len(img_id), size=nb_img, replace=False)
     sel_img_id = [img_id[i] for i in pick]
     coco_img = self.coco.loadImgs(sel_img_id)
     return coco_img
Beispiel #9
0
def get_expfiles(**kwargs):
    '''
        Get experiment data file names
        
        kwargs:
        #######
        :subjID: Subject ID
        :trial: trial number
        :timestamp: Default. Today
        :filetype: a keyword in exp filename
        :fullpath: Default. True
    '''
    # Parsers
    varargin = {
        'subjID': None,
        'trial': None,
        'timestamp': utils.get_timenow(key=EXPFILE_TIMEKEY),
        'filetype': None,
        'fullpath': True
    }
    varargin = utils.get_varargin(varargin, kwargs)
    ####
    allfiles = []
    myboard = mainBoard()
    for subj in myboard.subjList:
        subjfiles = get_subjfiles(subj)
        for f in subjfiles:
            allfiles.append(f)
    # Convert all files full path to filename
    filenames = [expFile(f) for f in utils.get_filename(allfiles)]
    output = filenames
    for key, val in varargin.items():
        if val is None:
            pass
        else:
            if key == 'subjID':
                output = [f for f in output if val == f.subjID]
            elif key == 'trial':
                trial = val
                if val == -1:
                    trialList = [f.trial for f in output]
                    trial = max(trialList)
                output = [f for f in output if trial == f.trial]
            elif key == 'timestamp':
                output = [f for f in output if val == f.timestamp]
            elif key == 'filetype':
                output = [f for f in output if val == f.filetype]

    if varargin['fullpath'] is True:
        output = [
            os.path.join(myboard.dataDir, f.subjID, f.filename) for f in output
        ]
    else:
        output = [f.filename for f in output]
    return output
Beispiel #10
0
 def display_coco_info(self, **kwargs):
     """
     Display key values information in .json file
     Keyword Options:
         key {str}: Input key to display information. Default: 'info'
         id {int}: Item id to display information. Default: None
     """
     key = get_varargin(kwargs, 'key', 'info')
     item_id = get_varargin(kwargs, 'id', None)
     if key == 'info':
         self.coco.info()
     elif key == 'category':
         cat_id = item_id
         cat_list = self.coco.loadCats(self.coco.getCatIds())
         if cat_id is None:
             print('Number of categories: {}'.format(len(cat_list)))
             nms = [cat['name'] for cat in cat_list]
             print('COCO categories: \n{}\n'.format(' '.join(nms)))
             print('Category list in Json file')
             print(cat_list)
         else:
             cat_id_list = [cat['id'] for cat in cat_list]
             if cat_id in cat_id_list:
                 idx = cat_id_list.index(cat_id)
                 print(cat_list[idx])
             else:
                 print('Category ID: {} is not found'.format(cat_id))
     elif key == 'image':
         img_id = item_id
         img_list = self.coco.loadImgs(self.coco.getImgIds())
         if img_id is None:
             print('Number of Images: {}'.format(len(img_list)))
             print(img_list)
         else:
             img_id_list = [img['id'] for img in img_list]
             if img_id in img_id_list:
                 idx = img_id_list.index(img_id)
                 print(img_list[idx])
             else:
                 print('Image ID: {} is not found'.format(img_id))
     else:
         pass
Beispiel #11
0
 def __init__(self, **kwargs):
     varargin = utils.get_varargin(
         {
             'name': 'Analog Sensor',
             'sensType': 'Analog',
             'pin': 'Px_xx'
         }, kwargs)
     for key, val in varargin.items():
         # Attributes in sensor abstract class are static
         setattr(self, '{}'.format(key), val)
     self.setup()
Beispiel #12
0
def create_coco_info(**kwargs):
    """
    Create info dict that follow coco dataset format
    Ref: http://cocodataset.org/#format-data
    Input Options:
        description: -str. description of the dataset. Default: 'Custom COCO dataset'
        url : -str. url to dataset. Default: ''
        version: -str. dataset version. Default: '1.0'
        year: -int. Default: this year
        contributor: -str. Default: 'author'
        date_created: -str. Default: today()
    Returns:
        coco_info: -edict. Dictonary of coco information
    """
    description = get_varargin(kwargs, 'description', 'Custom COCO dataset')
    url = get_varargin(kwargs, 'url', '')
    version = get_varargin(kwargs, 'version', '1.0')
    year = get_varargin(kwargs, 'year', datetime.today().year)
    contributor = get_varargin(kwargs, 'contributor', 'author')
    date_created = get_varargin(kwargs, 'date_created',
                                datetime.today().strftime('%Y/%m/%d'))

    coco_info = edict()
    coco_info.description = description
    coco_info.url = url
    coco_info.version = version
    coco_info.year = year
    coco_info.contributor = contributor
    coco_info.date_created = date_created
    return coco_info