import numpy as np
from skimage.morphology import medial_axis
def Crack_measure(_mask_cv_gray,dsx=(123-30)*1000/35*0.004387636):
    '''裂缝实际尺寸测量'''
    '''输入：单个裂缝分割图像
       过程：。
       返回：最终绘制的结果图、最终落水人员（坐标、类别、置信度），
    '''
    # 图像转化
    ###READ
    img = np.array(_mask_cv_gray.astype(np.int32))
    image0 = binary = img
    ###SKELETONIZATION
    img_skeletonized, distance = medial_axis(image0, return_distance=True)
    #print(img_skeletonized)
    img_skeletonized = np.array(img_skeletonized.astype(np.int32))
    ###COMPUTING WIDTH
    dist_on_skel = distance * img_skeletonized

    width = dist_on_skel[dist_on_skel != 0] * 2
    for i in range(len(width)):
        if width[i] <= 2.0:
            width[i] = width[i]
        else:
            width[i] = width[i] - 2
    ###OUTPUT
    real_length = np.count_nonzero(img_skeletonized) *dsx # Each pixel remaining after
    real_mean_width = np.mean(width)*dsx
    real_max_width = np.max(width)*dsx
    real_min_width = np.min(width)*dsx

    return real_length,real_mean_width,real_max_width,real_min_width