What is the fastest way to get values from elements that creates concentric square on some distance K from the center. I wrote code where I access every element value with numpy.ndarray.item
, but it has shown poor results. To help you visualize concentric squares here is picture of it
Note:
If center of sqaures is on that position that not all of square elements are in matrix then only visible elements shoud count. Example
Even better solution will be if I can get sum of elements after numpy.isclose
method on array of elements from concentric square.
Here is current code:
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