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)
plt.figure(figsize=(30, 16))
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.subplot(num_rows, num_cols, k + 1)
    plt.imshow(cropped_image)
    plt.axis('off')