#  -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from skimage import measure, data, color
import cv2
import os


def Edge_Extract(root, root2, root3):
    img_root = os.path.join(root)
    edge_root = os.path.join(root2)
    binary_root = os.path.join(root3)

    if not os.path.exists(edge_root):
        os.mkdir(edge_root)

    if not os.path.exists(binary_root):
        os.mkdir(binary_root)

    file_names = os.listdir(img_root)
    img_name = []

    for name in file_names:
        if not name.endswith('.jpg'):
            assert "This file %s is not JPG" % (name)
        img_name.append(os.path.join(img_root, name[:-4]+'.jpg'))

    index = 0

    for image in img_name:
        img = cv2.imread(image, 0)
        ret, img = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)
        cv2.imwrite(binary_root + '/' + file_names[index], img)
        print(index)
        contours = measure.find_contours(img, 0.5)
        plt.axis('off')
        fig = plt.gcf()
        fig.set_size_inches(2.56 / 3, 2.56 / 3)
        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())
        plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
        plt.margins(0, 0)
        ax1 = fig.subplots(1, 1)
        ax1.spines['top'].set_visible(False)
        ax1.spines['right'].set_visible(False)
        ax1.spines['bottom'].set_visible(False)
        ax1.spines['left'].set_visible(False)
        rows, cols = img.shape
        ax1.axis([0, rows, cols, 0])
        ax1.plot(contours[0][:, 1], contours[0][:, 0], linewidth=10, color='red')
        ax1.plot(contours[1][:, 1], contours[1][:, 0], linewidth=10, color='red')
        # for n, contour in enumerate(contours):
        #     ax1.plot(contour[:, 1], contour[:, 0], linewidth=5, color='blue')
        fig.savefig(edge_root + '/' + file_names[index], dpi=300, pad_inches=0)
        # plt.savefig(edge_root + '/' + file_names[index], dpi=300, pad_inches=0)
        index += 1
    return 0


if __name__ == '__main__':
    root = 'D:/result_contract/Otherkind/Tongue/20191119/ioulabel2_notall/'
    root2 = 'D:/result_contract/Otherkind/Tongue/20191119/ioulabel2_edge_find_contours_notall/'
    root3 = 'D:/result_contract/Otherkind/Tongue/20191119/ioulabel2_binary_notall/'
    Edge_Extract(root, root2, root3)
