import scipy.misc, os, array
import numpy as np
import math
import cv2
from PIL import Image

def get_feature_img(data_set = 'data', data_type = 'bytes'):
    data_list = os.listdir(data_set)
    data_list.sort()
    start = 0
    end = len(data_list)
    for i in range(start, end):
        file_id = data_list[i]
        read_binary = read_image(os.path.join(data_set, data_list[i]))
        hw = int(round(math.sqrt(len(read_binary))))
        feature_img = np.zeros((hw, hw), np.uint8)

        for y in range(0, hw) :
            for x in range(0, hw) :
                idx = x + (y * hw)
                if idx >= len(read_binary) :
                    feature_img[y, x] = 0
                else :
                    feature_img[y, x] = read_binary[idx]

        if hw < 300 :
            feature_img = cv2.resize(feature_img, (300,300), interpolation=cv2.INTER_CUBIC)

        file_name = os.path.join("data/total",file_id + ".jpg")
        print "%d/%d \t %s" % (i, len(data_list)/4, file_name)
        cv2.imwrite(file_name, feature_img)




def read_image(filename):
    f = open(filename,'rb')
    ln = os.path.getsize(filename) # length of file in bytes
    width = 256
    a = array.array("B") # uint8 array
    a.fromfile(f,ln)#-rem)
    f.close()
    a = np.uint8(a)
    return list(a)

if __name__ == '__main__':
    get_feature_img(data_set = 'data', data_type = 'bytes')

