# -*- coding: UTF-8 -*-
import cv2
import time
import numpy as np
import skimage.exposure
'''
两个区域间最短距离
https://www.cnpython.com/qa/1329750
'''

import math


def downsample(num_arr,downsample_rate):
    '''
    下采样数组，隔着downsample_rate个数取一个值
    num_arr为数组
    downsample_rate为采用概率，为1-n的正整数
    '''
    num_arr_temp=[]
    for i in range(len(num_arr)//downsample_rate-1):
        num_arr_temp.append(num_arr[i*downsample_rate])
    return num_arr_temp


def array_distance(arr1,arr2):
    '''
    计算两个数组中，每任意两个点之间L2距离
    arr1和arr2都必须是numpy数组
    且维度分别是mx2，nx2
    输出数组维度为mxn
    '''
    m,_=arr1.shape
    n,_=arr2.shape
    arr1_power = np.power(arr1, 2)
    xxx=arr1_power[:, 0]
    arr1_power_sum = arr1_power[:, 0] + arr1_power[:, 1]   #第1区域，x与y的平方和
    yyy=arr1_power_sum
    arr1_power_sum = np.tile(arr1_power_sum, (n, 1))       #将arr1_power_sum沿着y轴复制n倍，沿着x轴复制1倍，这里用于与arr2进行计算。 nxm 维度
    zzz=arr1_power_sum
    arr1_power_sum = arr1_power_sum.T                      #将arr1_power_sum进行转置
    arr2_power = np.power(arr2, 2)
    arr2_power_sum = arr2_power[:, 0] + arr2_power[:, 1]       #第2区域，x与y的平方和
    arr2_power_sum = np.tile(arr2_power_sum, (m, 1))           #将arr1_power_sum沿着y轴复制m倍，沿着x轴复制1倍，这里用于与arr1进行计算。   mxn 维度
    dis = arr1_power_sum + arr2_power_sum - (2 * np.dot(arr1, arr2.T))   #np.dot(arr1, arr2.T)矩阵相乘，得到xy的值。
    dis = np.sqrt(dis)
    return dis

# 中间输入的代码
# 将数组存在num_arr1和num_arr2中

t1=time.time()
# 1.读入图片
# img = cv2.imread('demo/171.png')
img = cv2.imread('demo/9.png')
t2=time.time()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

contours, thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# 2.寻找轮廓(多边界)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, 2)


# 3.轮廓数组转为列表(多边界)
list_contours=[]
record=[]
num_arr1=contours[0]
num_arr2=contours[1]


ssss1=np.squeeze(num_arr1, 1)
ssss2=np.squeeze(num_arr2, 1)


# 3.对边界进行下采样，减小点数量。
num_arr11=downsample(num_arr1,10)   #下采样边界点
num_arr22=downsample(num_arr2,10)   #下采样边界点




print(num_arr1)
t3=time.time()

dist_arr=array_distance(ssss1,ssss2)
min_dist=dist_arr[dist_arr>0].min()

print(min_dist)




# print('两区域最小距离',min(record))
t4=time.time()

print('读图时间:%s 找边界时间:%s 区域最短距离计算时间:%s'%(t2-t1,t3-t2,t4-t3))

