S. Nielsen
S. Nielsen

Reputation: 115

Extract pixel values from image (2d array) at specific coordinates using mask

I have an image stack of 512x512 pixel from which I extract a list of x and y coordinates for local maxima using peak_local_max(tmp_frame, min_distance=15,threshold_abs=3000) which return me the pixel coordinates in a numpy array.

Using the code below I generate a mask:

def createCircularMask(h, w, center=None, radius=None):

    if center is None: # use the middle of the image
        center = [int(w/2), int(h/2)]
    if radius is None: # use the smallest distance between the center and image walls
        radius = min(center[0], center[1], w-center[0], h-center[1])

    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)

    mask = dist_from_center <= radius
    return mask

I want to apply my mask at my x and y coordinate to get the sum pixel values around the local maxima and store them in a list.

I can, however not find a function that allows me to only apply the mask a given locations in the 2D array?

Upvotes: 3

Views: 2496

Answers (2)

Tonechas
Tonechas

Reputation: 13723

The following snippet shows you how to obtain the local sum of an image at specific coordinates. Notice that the local sum is computed inside a circular mask of fixed radius (maybe you need to tweak the code to change the radius from one position to another).

import numpy as np

np.random.seed(2018)
img = np.random.random(size=(512, 512))
rows, cols = np.ogrid[:img.shape[0], :img.shape[1]]

coords = [[100, 100], [200, 300], [300, 100], [400, 400]]
radius = 75

local_sum = []
for row, col in coords:
    mask = np.sqrt((rows - row)**2 + (cols - col)**2) <= radius
    local_sum.append(np.sum(mask*img))

Results can be displayed as follows:

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

fig, ax = plt.subplots(1, 1)
ax.imshow(img, cmap='gray')
for i, [row, col] in enumerate(coords):
    ax.add_patch(Circle((col, row), radius=radius, color='red'))
    plt.text(col, row, '{:.2f}'.format(local_sum[i]), ha='center', va='center')
plt.show(fig)

results

Upvotes: 1

Ashlou
Ashlou

Reputation: 694

people usually use scipy kernel convolution. please let me know if this suits your question.

from scipy import ndimage
a = np.array([[1, 2, 0, 0],[5, 3, 0, 4], [0, 0, 0, 7],[9, 3, 0, 0]])
k = np.array([[1,1,1],[1,1,0],[1,0,0]])

ndimage.convolve(a, k, mode='constant', cval=0.0)
array([[11, 10,  7,  4],
       [10,  3, 11, 11],
       [15, 12, 14,  7],
       [12,  3,  7,  0]])

Upvotes: 0

Related Questions