中心から一定の距離 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