text_plain_output_1.png
from PIL import Image

import glob

import matplotlib.pyplot as plt

import numpy as np

import os

import xml.etree.ElementTree as ET

root_images = '../input/all-dogs/all-dogs/'
root_annots = '../input/annotation/Annotation/'
all_images = os.listdir('../input/all-dogs/all-dogs/')
breeds = glob.glob('../input/annotation/Annotation/*')
annotation = []
for b in breeds:
    annotation += glob.glob(b + '/*')
breed_map = {}
for annot in annotation:
    breed = annot.split('/')[-2]
    index = breed.split('-')[0]
    breed_map.setdefault(index, breed)

def bounding_box(image):
    bpath = root_annots + str(breed_map[image.split('_')[0]]) + '/' + str(image.split('.')[0])
    tree = ET.parse(bpath)
    root = tree.getroot()
    objects = root.findall('object')
    for o in objects:
        bndbox = o.find('bndbox')
        xmin = int(bndbox.find('xmin').text)
        ymin = int(bndbox.find('ymin').text)
        xmax = int(bndbox.find('xmax').text)
        ymax = int(bndbox.find('ymax').text)
    return (xmin, ymin, xmax, ymax)
num_rows = 5
num_cols = 9
num_images_to_show = num_rows * num_cols
selected_images = np.random.choice(all_images, size=num_images_to_show, replace=False)
for k, image_filename in enumerate(selected_images):
    bbox = bounding_box(image_filename)
    orig_image = Image.open(os.path.join(root_images, image_filename))
    cropped_image = orig_image.crop(bbox)
    plt.axis('off')

num_images_in_dataset = 16384
image_dimention = 64
resize_shape = (image_dimention, image_dimention)
selected_images = np.random.choice(all_images, size=num_images_in_dataset, replace=False)
image_dataset_4D_matrix = np.zeros((image_dimention, image_dimention, 3, num_images_in_dataset), dtype=np.uint8)
for k, image_filename in enumerate(selected_images):
    bbox = bounding_box(image_filename)
    orig_image = Image.open(os.path.join(root_images, image_filename))
    cropped_image = orig_image.crop(bbox)
    resized_image = tform.resize(np.array(cropped_image), resize_shape, preserve_range=True).astype(np.uint8)
    image_dataset_4D_matrix[:, :, :, k] = resized_image

image_dataset_4D_matrix
normlized_X = image_dataset_4D_matrix.astype(np.float32)
print(normlized_X.shape)
normlized_X = normlized_X - normlized_X.mean(axis=3, keepdims=True)
print(normlized_X.shape)
normlized_X = normlized_X / normlized_X.std(axis=3, keepdims=True)
print(normlized_X.shape)
normlized_X = np.transpose(normlized_X, [3, 0, 1, 2])
print(normlized_X.shape)