file_utils.py 5.93 KB
Newer Older
1 2 3 4
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
"""
5 6 7 8
    Provides file handle utilities.
    
    Name: file_utils.py
    Author: Alessandro dos Santos Ferreira ( santosferreira.alessandro@gmail.com )
9 10 11 12 13
"""

import cv2
#import numpy as np
import os
14
import shutil
15 16
from skimage.util import img_as_float
from scipy import ndimage
17 18
from PIL import Image
import numpy as np
19 20

class File(object):
21
    """Set of utilities to handle files."""
22 23 24

    @staticmethod
    def get_filename(filepath):
25 26 27 28 29 30 31 32 33 34 35 36
        """Return only the filename part from a filepath.
        
        Parameters
        ----------
        filepath : string
            Filepath of a file.
        
        Returns
        -------
        name : string
            Filename part from filepath.
        """
37 38 39 40 41
        path, name = os.path.split(filepath)
        
        return name
    
    @staticmethod
42 43 44 45 46 47 48 49 50 51 52 53 54
    def get_path(filepath):
        """Return only the path part from a filepath, excluding the name of file.
        
        Parameters
        ----------
        filepath : string
            Filepath of a file.
        
        Returns
        -------
        name : string
            Path from filepath, excluding the name of file.
        """
55 56 57 58 59
        path, name = os.path.split(filepath)
        
        return path    
        
    @staticmethod
60
    def open_image(filepath, rgb = True):
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
        """Open a image.
        
        Parameters
        ----------
        filepath : string
            Filepath of a file.
        rgb : boolean, optional, default = True
            If true return the image in RGB, else BGR.
        
        Returns
        -------
        image : opencv 3-channel color image.
            Return the image opened.
            
        Raises
        ------
        IOError
            Error opening the image.
        """
80
        image = cv2.imread(filepath)
81 82
        if image is None:
            raise IOError('Image not opened')
83
            
84
        #image = np.flipud(image)
85 86 87
        if rgb == True:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

88 89
        #return img_as_float(image)
        return image
90
        
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

    @staticmethod
    def open_image_lut(filepath):
        """Open a image.
        
        Parameters
        ----------
        filepath : string
            Filepath of a file.
        
        Returns
        -------
        image : 3-channel color image.
            Return the image opened.
            
        Raises
        ------
        IOError
            Error opening the image.
        """
        image = Image.open(filepath)
        if image is None:
            raise IOError('Image not opened')
            
        return np.array(image)
    

118 119
    @staticmethod
    def save_image(image, directory, filename, ext = '.tif'):
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        """Save a image.
        
        Parameters
        ----------
        image : opencv image
            Image to be saved.
        directory : string
            Path where image must be saved.
        filename : string
            Name of image.
        ext : string, optional, default = '.tif'
            Extension which image must be saved in format .ext.
        
        Returns
        -------
        filepath : string
            Return the complete filepath where image was saved.
        """
138 139 140 141 142 143
        filepath = File.make_path(directory, filename + ext)
        if not os.path.exists(directory):
            os.makedirs(directory)
        cv2.imwrite(filepath, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))

        return filepath
144 145

    @staticmethod
146
    def save_class_image(image, dataset, directory, filename, idx, ext = '.tif'):
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        """Save a class image.
        
        Parameters
        ----------
        image : opencv image
            Image to be saved.
        dataset : string
            Path do image dataset.
        directory : string
            Directory where image must be saved.
        image : string
            Name of image.
        image : string
            Name of image.
        idx : integer
            Index of image inside the class.
        ext : string, optional, default = '.tif'
            Extension which image must be saved in format .ext.
165
        
166 167 168 169 170
        Returns
        -------
        filepath : string
            Return the complete filepath where image was saved.
        """
171 172
        for root, dirs, files in os.walk(dataset):
            for d in dirs:
173
                filepath = File.make_path(dataset, d, filename + '_%05d' % idx + ext)
174 175 176
                if(os.path.isfile(filepath)):
                    os.remove(filepath)

177
        return File.save_image(image, File.make_path(dataset, directory), filename + '_%05d' % idx, ext)
178

179
    @staticmethod
180
    def list_dirs(dataset):
181 182 183 184 185 186 187 188 189 190 191 192
        """List all directories inside the dataset.
        
        Parameters
        ----------
        dataset : string
            Filepath to dataset.
        
        Returns
        -------
        dirs : list of string
            Return a list containing the name of all directories inside the dataset.
        """
193
        return [name for name in os.listdir(dataset) 
194
                    if os.path.isdir(os.path.join(dataset, name)) and not name.startswith('.')]
195 196 197

    @staticmethod
    def create_dir(directory):
198 199 200 201 202 203 204
        """Make a directory.
        
        Parameters
        ----------
        dataset : string
            Filepath to directory to be created.
        """
205
        if not os.path.exists(directory):
206
            os.makedirs(directory)
207
            
208 209
    @staticmethod
    def remove_dir(directory):
210 211 212 213 214 215 216
        """Delete a directory recursively if needed.
        
        Parameters
        ----------
        dataset : string
            Filepath to directory to be removed.
        """
217 218 219
        if os.path.exists(directory):
            shutil.rmtree(directory)
            
220 221
    @staticmethod
    def make_path(*dirs):
222 223 224 225 226 227 228
        """Make a path from a list.
        
        Parameters
        ----------
        dirs : list of arguments 
            Ordered list used to make a path.
        """
229
        return '/'.join([ d for d in dirs])