# -*- coding: UTF-8 -*-
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   多边形等距缩放.py
@data    ：2021/7/5 15:53
@Desciption :
@Version  :
@License :
'''

import cv2
import numpy as np

def contours_2_list(data):
    """将opencv读取的边界numpy数组（3个维度）转化为list（2个维度）
    Args:
     data为数组


    Returns:
        list（2个维度）
    """
    yyy = data[0]
    # print(yyy)
    list_contours = []
    for i in range(yyy.shape[0]):
       list_contours.append([yyy[i][0][0], yyy[i][0][1]])
    return list_contours



def scale(data, sec_dis):
    """多边形等距缩放
    Args:
        data: 多边形按照逆时针顺序排列的的点集
        sec_dis: 缩放距离

    Returns:
        缩放后的多边形点集
    """
    num = len(data)
    scal_data = []
    for i in range(num):
        x1 = data[(i) % num][0] - data[(i - 1) % num][0]
        y1 = data[(i) % num][1] - data[(i - 1) % num][1]
        x2 = data[(i + 1) % num][0] - data[(i) % num][0]
        y2 = data[(i + 1) % num][1] - data[(i) % num][1]

        d_A = (x1 ** 2 + y1 ** 2) ** 0.5
        d_B = (x2 ** 2 + y2 ** 2) ** 0.5

        Vec_Cross = (x1 * y2) - (x2 * y1)
        if (d_A * d_B==0):
            continue
        sin_theta = Vec_Cross / (d_A * d_B)
        if (sin_theta==0):
            continue
        dv = sec_dis / sin_theta

        v1_x = (dv / d_A) * x1
        v1_y = (dv / d_A) * y1

        v2_x = (dv / d_B) * x2
        v2_y = (dv / d_B) * y2

        PQ_x = v1_x - v2_x
        PQ_y = v1_y - v2_y

        Q_x = data[(i) % num][0] + PQ_x
        Q_y = data[(i) % num][1] + PQ_y
        scal_data.append([Q_x, Q_y])
    return scal_data

# 1.读入图片
# img = cv2.imread('demo/171.png')
img = cv2.imread('image/171.jpg')
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)


list_contours=contours_2_list(contours)

# for i in range(yyy.shape[0]):
#   list_contours.append([yyy[i][0][0],yyy[i][0][1]])

data=list_contours


data1 = scale(data,-150)
print(data1)
# temp = np.ones((img_gray.shape[0],img_gray.shape[1],3), np.uint8) * 255
temp = np.zeros((img_gray.shape[0],img_gray.shape[1],3), np.uint8) * 255
# cv2.polylines(temp, data1, 1, 255)
cv2.polylines(temp,[np.array(data1, dtype=np.int32)],True, (255, 0, 0), 5)
# cv2.polylines(temp , [np.array(data1 , dtype=np.int32)], True, (0, 0, 255), 1)

cv2.namedWindow("boundary",cv2.WINDOW_NORMAL);
cv2.resizeWindow("boundary", 640, 480);
cv2.imshow("boundary",temp)

# cv2.imshow ("img",temp)
cv2.imwrite("1.jpg",temp)
cv2.waitKey(0)
