0

什么是从在距中心一定距离 K 处创建同心正方形的元素中获取值的最快方法。我编写了使用 访问每个元素值的代码numpy.ndarray.item,但结果很差。为了帮助您可视化同心正方形,这里是它的图片

注意

如果正方形的中心位于并非所有正方形元素都在矩阵中的那个位置,则只应计算可见元素。例子

更好的解决方案是,如果我可以在numpy.isclose对同心正方形的元素数组进行方法之后得到元素的总和。

这是当前代码:

def valid_pixel(image, pixel):
    """
    Returns True if pixel is inside the image boundaries.
    """
    width, height = image.shape
    x, y = pixel
    return 0 <= x < width and 0 <= y < height


def calculate_delta(indexed_img, C, k, pixel, h):
    """
    Returns sum of elements all over the distance k that have the same value as parameter C
    """
    x, y = pixel
    c_sum = 0
    v = 1 - h
    for i in range(0, k + 1):
        new_pixel = (x + h * i, y + v * i)
        if valid_pixel(indexed_img, new_pixel) and C == indexed_img.item(new_pixel):
            c_sum += 1
    return c_sum


def color_correlation(indexed_img, colors_map, Ci, Cj, k):
    correl_sum = 0
    for x, y in colors_map.get(Ci, iter(())):
        # this part of code returns sum of elements which create square with center in (x,y) and have the same value as parameter Cj 
        correl_sum += calculate_delta(indexed_img, Cj, 2 * k, (x - k, y + k), 1) + \
                      calculate_delta(indexed_img, Cj, 2 * k, (x - k, y - k), 1) + \
                      calculate_delta(indexed_img, Cj, 2 * k - 2, (x - k, y - k + 1), 0) + \
                      calculate_delta(indexed_img, Cj, 2 * k - 2, (x + k, y - k + 1), 0)

    return correl_sum
4

0 回答 0