# -*- coding: UTF-8 -*-
# 作者：huanhuilong
# 标题：滤镜2
# 描述：迷你滤镜 PS 版本2


import numpy as np
import cv2

from scipy import misc, ndimage, signal
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image


def plot_two(left, right):
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)
    ax1.imshow(left)
    ax2.imshow(right)
    plt.show()


def cv_2d_conv_lower_pass_filer(img_src):
    # prepare the 5x5 shaped filter
    kernel = np.array([[1, 1, 1, 1, 1],
                       [1, 1, 1, 1, 1],
                       [1, 1, 1, 1, 1],
                       [1, 1, 1, 1, 1],
                       [1, 1, 1, 1, 1]])
    kernel = kernel/sum(kernel)

    # filter the source image
    img_rst = cv2.filter2D(img_src, -1, kernel)
    return img_rst


def cv_2d_conv_high_pass_filter(img_src):
    # edge detection filter
    kernel = np.array([[0.0, -1.0, 0.0],
                       [-1.0, 4.0, -1.0],
                       [0.0, -1.0, 0.0]])

    kernel = kernel/(np.sum(kernel) if np.sum(kernel) != 0 else 1)

    # filter the source image
    img_rst = cv2.filter2D(img_src, -1, kernel)
    return img_rst


def cv_2d_conv_customer_filter(img_src):
    # edge detection filter
    kernel = np.array([[-1.0, -1.0],
                       [2.0, 2.0],
                       [-1.0, -1.0]])

    kernel = kernel/(np.sum(kernel) if np.sum(kernel) != 0 else 1)

    # filter the source image
    img_rst = cv2.filter2D(img_src, -1, kernel)
    return img_rst


def select_filter(image):
    print(image.shape)
    filters = [
        {
            'option': 'lcov',
            'name': '2维卷积低通滤镜( filter2D )',
            'filter': lambda: cv_2d_conv_lower_pass_filer(image)
        },
        {
            'option': 'hcov',
            'name': '2维卷积高通滤镜( filter2D )',
            'filter': lambda: cv_2d_conv_high_pass_filter(image)
        },
        {
            'option': 'ccov',
            'name': '2维卷积自定义滤镜( filter2D )',
            'filter': lambda: cv_2d_conv_customer_filter(image)
        },
    ]

    print("本迷你PS软件支持以下滤镜：")
    filter_dict = {}
    for filter in filters:
        filter_dict[filter['option']] = filter
        print("* {} : {}".format(filter['option'], filter['name']))

    options = '/'.join(list(map(lambda f: f['option'], filters)))

    while True:
        ret = input(f"请选择滤镜[ {options}]:")
        filter = filter_dict.get(ret)
        if filter is None:
            print("不支持的选项，请重新选择。")
        else:
            return filter['filter']()


if __name__ == '__main__':
    image = misc.face()
    blurred = select_filter(image)
    plot_two(image, blurred)
