import numpy as np

def correlation(testimage, angrange, brange, sigma):
    imgsize = testimage.shape

    if len(imgsize) > 2:
        testimage = np.dot(testimage, [0.299, 0.587, 0.114])  # Перевод в оттенки серого

    xsize = imgsize[1]
    ysize = imgsize[0]
    subimage = testimage.astype(float)

    medianint = np.median(testimage[testimage > 0])
    angles = np.arange(angrange[0], angrange[3], angrange[1])
    trans = np.arange(brange[0], brange[3], brange[1])
    corrmap = np.zeros((len(angles), len(trans)))

    for thetaind in range(len(angles)):
        for bind in range(len(trans)):
            theta = angles[thetaind]
            b = trans[bind]
             
            refline = reference_line_gen(xsize, ysize, theta, b, sigma)
            temp = refline * subimage
            temp2 = np.sum(temp)
            temp3 = temp2 / medianint
            corrmap[thetaind, bind] = temp3

    return corrmap


import numpy as np

def reference_line_gen(xsize, ysize, theta, b, sigma):
    Xmesh, Ymesh = np.meshgrid(np.arange(1, xsize+1), np.arange(1, ysize+1))

    Xmesh = Xmesh - xsize / 2
    Ymesh = Ymesh - ysize / 2

    angle = (theta * np.pi) / 180
    dist = b - (Xmesh * np.sin(angle)) - (Ymesh * np.cos(angle))
    distance = ((dist * dist) / (sigma * sigma))
    result = np.exp(-distance)

    return result


import numpy as np

def max_intensity_finding(correlation_map, dist_input=None):
    if dist_input is not None:
        distance_threshold = dist_input
    else:
        distance_threshold = 10
    
    size_corr = correlation_map.shape
    label_map = np.zeros(size_corr)
    xgrid, ygrid = np.meshgrid(np.arange(1, size_corr[1] + 1), np.arange(1, size_corr[0] + 1))
    
    for indx in range(size_corr[1]):
        for indy in range(size_corr[0]):
            dist = np.sqrt((xgrid - indx) ** 2 + (ygrid - indy) ** 2)
            pixuseful = dist < distance_threshold
            if correlation_map[indy, indx] >= np.max(correlation_map[pixuseful]):
                label_map[indy, indx] = 1
    
    label_map[correlation_map == 0] = 0
    
    return label_map



def sub_window_analysis(correlation_map, dist_input):
    imgsize = np.array(correlation_map.shape)
    sgimgsize = imgsize.astype(np.float32)
    sgsubimgsz = imgsize.astype(np.float32)
    sgtestimage = imgsize.astype(np.float32)
    sigma = imgsize.astype(np.float32)
    
    if imgsize[0] % subimgsz[0] != 0 or imgsize[1] % subimgsz[1] != 0:
        print('The subimage size does not match the whole image size')
        return
    
    angles = np.arange(angrange[0], angrange[1], angrange[2])
    trans = np.arange(brange[0], brange[1], brange[2])
    corr = np.zeros((len(angles), len(trans), imgsize[0] // subimgsz[0], imgsize[1] // subimgsz[1]))
    xsize = sgimgsize[1]
    ysize = sgimgsize[0]
    Xmesh, Ymesh = np.meshgrid(np.arange(xsize), np.arange(ysize))
    Xmesh = np.mod(Xmesh, subimgsz[1])
    Ymesh = np.mod(Ymesh, subimgsz[0])
    Xmesh = Xmesh - sgsubimgsz[1] / 2
    Ymesh = Ymesh - sgsubimgsz[0] / 2

    for thetaind in range(len(angles)):
        for bind in range(len(trans)):
            theta = angles[thetaind]
            b = single(trans[bind])
            angle = (theta * np.pi) / 180
            dist = b - (Xmesh * np.sin(angle)) - (Ymesh * np.cos(angle))
            distpw = (dist ** 2) / (sigma ** 2)
            refline = np.exp(-distpw)
            temp = refline * sgtestimage
            temp2 = temp.reshape(subimgsz[0], imgsize[0] // subimgsz[0], subimgsz[1], imgsize[1] // subimgsz[1])
            temp3 = np.sum(temp2, axis=1)
            temp4 = np.squeeze(np.sum(temp3, axis=2))
            corr[thetaind, bind, :, :] = temp4


    corrsz = corr.shape
    spcorr = corr.reshape(corrsz[0] * corrsz[2], corrsz[1] * corrsz[3])
    colsubimgs = sgtestimage.reshape(subimgsz[0], imgsize[0] // subimgsz[0], subimgsz[1], imgsize[1] // subimgsz[1])
    return spcorr, colsubimgs
    


# Загрузка изображения и предварительная обработка
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY)

image = cv2.GaussianBlur(image, (3, 3), 0)

# Параметры алгоритма
angrange = [0, 5, 45]  # Диапазон углов
brange = [-10, 1, 10]  # Диапазон сдвигов
sigma = 1.0  # Сигма для функции расстояния

# Вызов алгоритма
corr_map = correlation(image, angrange, brange, sigma)
label_map = max_intensity_finding(corr_map)

# Визуализация результатов
plt.imshow(corr_map)
plt.show()
plt.imshow(label_map)
plt.show()


ИСПРАВЬ ОшИБКУ:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-133-d00ffd76c746> in <cell line: 129>()
    127 
    128 # Вызов алгоритма
--> 129 corr_map = correlation(image, angrange, brange, sigma)
    130 label_map = max_intensity_finding(corr_map)
    131 

<ipython-input-133-d00ffd76c746> in correlation(testimage, angrange, brange, sigma)
     12 
     13     medianint = np.median(testimage[testimage > 0])
---> 14     angles = np.arange(angrange[0], angrange[3], angrange[1])
     15     trans = np.arange(brange[0], brange[3], brange[1])
     16     corrmap = np.zeros((len(angles), len(trans)))

IndexError: list index out of range