# -*- 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

# 中间输入的代码
# 将数组存在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]


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




print(num_arr1)
t3=time.time()
for i in num_arr11:
    for j in num_arr22:
        # record.append(abs(i[0] - j[0]))
        record.append(math.sqrt((i[0][0] - j[0][0]) ** 2 +(i[0][1] - j[0][1]) ** 2 ) )

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

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

