#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov  8 12:29:07 2017

@author: kanchana
"""
import numpy as np
from PIL import Image ,ImageOps , ImageChops,ImageDraw
import glob
import csv

def trim(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)
    
i=1
with open("../ML_projt/Dataset/myimages4.csv", "a") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for filename in glob.glob("/home/kanchana/Downloads/Ankle_boot/*.jpg"): #assuming jpg
            img=ImageOps.invert(trim(Image.open(filename) ))
            img.thumbnail((28,28), Image.ANTIALIAS)
            img_w, img_h = img.size
            new_img = Image.new(img.mode, (28, 28), (0, 0, 0, 0))
            bg_w, bg_h = new_img.size
            offset = (int((bg_w - img_w) / 2), int((bg_h - img_h) / 2))
            new_img.paste(img, offset)
            new_img=new_img.convert('L')
#            new_img = img.resize((28,28),resample=Image.BICUBIC)
            im1=(np.reshape(list(new_img.getdata()), (28, 28))).astype(np.uint8)
            img2 = Image.fromarray(im1, 'L')
            line=list(new_img.getdata())
            line.insert(0,9)
            writer.writerow(line)
            #img2.save("../ML_projt/Images/Shirt_Top/Shirt_Top"+ str(i) +".jpg")
            i +=1