text_html_output_1.png text_plain_output_1.png
from PIL import Image, ImageDraw

import matplotlib.pyplot as plt

import pandas as pd

# Defines the class to load metadata and images and to process those.
class WhaleAndDolphin():
    def __init__(self, path_to_metadata, path_to_dir_images):
        self._path_to_metadata = path_to_metadata
        self._path_to_dir_images = path_to_dir_images
        self._metadata = pd.read_csv(path_to_metadata)
        
    def getAllSpecies(self):
        return self._metadata["species"].unique()
    
    def sliceMetadata(self, query):
        return self._metadata.query(query).reset_index(drop=True)
    
    def getAllIndividualIDs(self, metadata):
        return metadata["individual_id"].unique()

    def showImagesTile(self, metadata, num_cols=3):
        num_rows = len(metadata) // num_cols + 1
        fig = plt.figure(figsize=(6.4 * num_cols, 4.8 * num_rows))
        
        for row in metadata.itertuples():
            title, image = self.getImage(row)
            ax = fig.add_subplot(num_rows, num_cols, row.Index + 1)
            ax.set_title(title)
            plt.imshow(image)
            
        plt.show()
        plt.clf()
        plt.close()
        
    def getImage(self, metadata_row):
        title = "%s (%s)" % (metadata_row.individual_id, \
                             metadata_row.species)
        path_to_image = self._pathToImage(
            self._path_to_dir_images,
            file_name=metadata_row.image
        )
        image = Image.open(path_to_image)
        return title, image
    
    def _pathToImage(self, path_to_dir_images, file_name):
        return "%s/%s" % (path_to_dir_images, file_name)
    
    def showIndividualImagesTile(self, metadata, num_cols=3, num_individuals=10):
        metadata_sorted = \
            metadata.sort_values(by=["individual_id"]).reset_index(drop=True)
        
        num_rows = num_cols * num_individuals
        fig = plt.figure(figsize=(6.4 * num_cols, 4.8 * num_rows))
        
        num_images = 0

        individual_id_prev = ""
        i_row, i_col = 0, 0
        for row in metadata_sorted.itertuples():
            if row.individual_id != individual_id_prev:
                # Moves to next row, if different individuals is found.
                i_row += 1
                i_col = 1
                i = (i_row - 1) * num_cols + i_col
                
                individual_id_prev = row.individual_id
                
                if i_row > num_individuals:
                    break
                
                # Shows image.
                title, image = self.getImage(row)
                ax = fig.add_subplot(num_rows, num_cols, i)
                ax.set_title(title)
                plt.imshow(image)
                #print("New individuals is found!!")
                #print(">  i_row, i_col, title, id = %d, %d, %s, %s" % (i_row, i_col, title, row.individual_id)) # for DEBUG
            elif i_col < num_cols:
                # Moves to next column, if the number of images for same individuals is less than num_cols.
                i_col += 1
                i = (i_row - 1) * num_cols + i_col
                
                # Shows image.
                title, image = self.getImage(row)
                ax = fig.add_subplot(num_rows, num_cols, i)
                ax.set_title(title)
                plt.imshow(image)
                #print(">> i_row, i_col, title, id = %d, %d, %s, %s" % (i_row, i_col, title, row.individual_id)) # for DEBUG
            else:
                #print("<  i_row, i_col, title, id = %d, %d, %s, %s" % (i_row, i_col, title, row.individual_id)) # for DEBUG
                continue
                
        plt.show()
        plt.clf()
        plt.close()

path_to_metadata = '%s/train.csv' % path_to_inputs
path_to_dir_images = '%s/train_images' % path_to_inputs
whale_and_dolphin = WhaleAndDolphin(path_to_metadata=path_to_metadata, path_to_dir_images=path_to_dir_images)

all_species = whale_and_dolphin.getAllSpecies()

metadata = {}
stats = pd.DataFrame(columns=['num_of_images', 'num_of_individuals'], index=all_species)
for species in all_species:
    metadata[species] = whale_and_dolphin.sliceMetadata(query='species == @species')
    num_images = len(metadata[species])
    individual_ids = whale_and_dolphin.getAllIndividualIDs(metadata[species])
    num_individuals = len(individual_ids)
    stats.loc[species] = [num_images, num_individuals]
stats.loc['total'] = [stats['num_of_images'].sum(), stats['num_of_individuals'].sum()]

print('Number of images/individuals for each species:')
stats