#!/usr/bin/python

import sys
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.misc import imread, imsave


def sky_view(image_list, label_list, src_warp, dst_warp):
    warped_image = []
    height, width = image_list[0].shape[:2]
    warp_matrix = cv2.getPerspectiveTransform(src_warp, dst_warp)
    for i in range(len(image_list)):
        warped_image.append(cv2.warpPerspective(image_list[i], warp_matrix, (width, height)))
        save_image(warped_image[i], label_list[i])

def roi_area(image_list, label_list, src_roi):
    x0, y0 = src_roi[0]
    x1, y1 = src_roi[1]
    x2, y2 = src_roi[2]
    x3, y3 = src_roi[3]
    for i in range(len(image_list)):
        cv2.line(image_list[i], (x0, y0), (x1, y1), (0, 0, 255), 10)
        cv2.line(image_list[i], (x1, y1), (x2, y2), (0, 0, 255), 10)
        cv2.line(image_list[i], (x2, y2), (x3, y3), (0, 0, 255), 10)
        cv2.line(image_list[i], (x3, y3), (x0, y0), (0, 0, 255), 10)
        save_image(image_list[i], label_list[i])

def save_image(img, name):
    path = '../output_images/' + name + '.png'
    imsave(path, img)

def show_images(img_list, labels):
    rows = 2
    cols = 3
    fig_size = (200, 100)
    figure, axes = plt.subplots(nrows=rows, ncols=cols, figsize=fig_size)
    counter = 0
    for i in range(0, rows):
        for j in range(0, cols):
            axes[i, j].imshow(img_list[counter], cmap='gray')
            axes[i, j].set_title(labels[counter], fontsize=30, pad=15)
            axes[i, j].axis('off')
            counter +=1

    plt.tight_layout()
    plt.show()

nimgs = 6
image_list = [imread('../test_images/image0' + str(i) + '.png') for i in range(1, nimgs + 1)]
label_list_imgs = ['image0' + str(i) for i in range(1, nimgs + 1)]
height, width = image_list[0].shape[:2]
show_images(image_list, label_list_imgs)

"""
src_roi = np.array([
    (width * 0.25, height * 0.5), (width * 0.75, height * 0.5), 
    (width * 0.9, height-10), (width * 0.1, height-10)
    ], dtype=np.int16)

label_list_roi = ['roi_show_image0' + str(i) for i in range(1, nimgs + 1)]
roi_show_img_list = roi_area(image_list, label_list_roi, src_roi)
roi_img_list = [imread('../output_images/roi_show_image0' + str(i) + '.png') for i in range(1, nimgs + 1)]
show_images(roi_img_list, label_list_roi)
"""

"""
src_warp = np.array([
    (width * 0.25, height * 0.5), (width * 0.75, height * 0.5), 
    (width * 0.9, height-10), (width * 0.1, height-10)
    ], dtype=np.float32)
dst_warp = np.array([
    (0, 0), (width, 0),
    (width, height), (0, height)
], dtype=np.float32)

label_list_warp = ['warped_image0' + str(i) for i in range(1, nimgs + 1)]
warped_show_img_list = sky_view(image_list, label_list_warp, src_warp, dst_warp)
warped_img_list = [imread('../output_images/warped_image0' + str(i) + '.png') for i in range(1, nimgs + 1)]
show_images(warped_img_list, label_list_warp)
"""