text_plain_output_1.png
from PIL import Image

from PIL import Image

from tqdm import tqdm, tqdm_notebook

import matplotlib.patches as patches

import matplotlib.patches as patches

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import numpy as np # linear algebra

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import numpy as np
import pandas as pd
import os, os.path

from xml.etree import ElementTree as ET
def parse_annotation(fname):
    objects = []
    for child in ET.parse(fname).findall('object'):
        dog = {}
        dog['name'] = child.find('name').text
        dog['pose'] = child.find('pose').text
        dog['difficult'] = int(child.find('difficult').text)
        dog['truncated'] = int(child.find('truncated').text)
        bbox = child.find('bndbox')
        dog['bbox'] = [int(bbox.find('xmin').text), int(bbox.find('ymin').text), int(bbox.find('xmax').text), int(bbox.find('ymax').text)]
        objects.append(dog)
    return objects

IMAGE_DIR = '../input/all-dogs/all-dogs'
dog_imgs = pd.DataFrame(os.listdir(IMAGE_DIR), columns=['filename'])
dog_imgs['basename'] = dog_imgs['filename'].str.split('.').apply(lambda x: x[0])
dog_imgs[['class', 'id']] = dog_imgs['basename'].str.split('_', expand=True)
dog_imgs = dog_imgs.set_index('basename').sort_index()
ANNOTATION_DIR = '../input/annotation/Annotation'
dog_breeds = pd.DataFrame(os.listdir(ANNOTATION_DIR), columns=['dirname'])
dog_breeds[['class', 'breedname']] = dog_breeds['dirname'].str.split('-', 1, expand=True)
dog_breeds = dog_breeds.set_index('class').sort_index()
dog_imgs['annotation_filename'] = dog_imgs.apply(lambda x: os.path.join(ANNOTATION_DIR, dog_breeds.loc[x['class']]['dirname'], x.name), axis=1)
dog_imgs['objects'] = dog_imgs['annotation_filename'].apply(parse_annotation)

doggo = dog_imgs.sample(1).iloc[0]

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import matplotlib.patches as patches

from PIL import Image

import imgaug.augmenters as iaa

pil_im = Image.open(os.path.join(IMAGE_DIR, doggo['filename']))
im = np.asarray(pil_im)

fig,ax = plt.subplots(1)

ax.imshow(im)

h,w,c = im.shape
for dog in doggo['objects']:
    xmin, ymin, xmax, ymax = dog['bbox']
    print(h,w,":",xmin,ymin,xmax,ymax)
    bbox = patches.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, linewidth=1, edgecolor='r', facecolor='none')
    ax.add_patch(bbox)

plt.show()

fig,ax = plt.subplots(1)

dog = doggo.objects[0]

h,w,c = im.shape
xmin, ymin, xmax, ymax = dog['bbox']

#im = im[ymin:ymax,xmin:xmax]
pil_crop = pil_im.crop((xmin, ymin, xmax, ymax)).resize((64, 64))
im2 = np.asarray(pil_crop)

ax.imshow(im2)

plt.show()

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import imgaug.augmenters as iaa
from tqdm import tqdm, tqdm_notebook
def get_truth_images():
    all_imgs = []
    for _, doggo in tqdm_notebook(dog_imgs.iterrows(), total=len(dog_imgs)):
        pil_im = Image.open(os.path.join(IMAGE_DIR, doggo['filename']))
        h, w, c = im.shape
        for dog in doggo['objects']:
            border = 10
            xmin, ymin, xmax, ymax = dog['bbox']
            xmin = max(0, xmin - border)
            ymin = max(0, ymin - border)
            xmax = min(w, xmax + border)
            ymax = min(h, ymax + border)
            pil_crop = pil_im.crop((xmin, ymin, xmax, ymax)).resize((64, 64))
            all_imgs.append(np.asarray(pil_crop))
    return np.stack(all_imgs)
truth_imgs = get_truth_images()