使用掩码从图像(2D数组)中提取特定坐标处的像素值

3
我有一个512x512像素的图像堆栈,我使用peak_local_max(tmp_frame, min_distance=15,threshold_abs=3000)提取局部最大值的x和y坐标列表,该函数返回numpy数组中的像素坐标。
使用以下代码生成掩码:
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

我想在给定的x和y坐标处应用我的掩模,以获取局部极大值周围的像素值之和,并将它们存储在列表中。

然而,我找不到仅允许我在2D数组中给定位置应用掩模的函数?


你是在尝试在极值周围进行某种内核卷积吗? - Ashlou
实际上,理想情况下是在图像特定位置应用核函数并得到总和。 - S. Nielsen
2个回答

1
以下代码片段展示了如何获取特定坐标处图像的局部和。请注意,局部和是在固定半径的圆形掩模内计算的(也许您需要调整代码以更改从一个位置到另一个位置的半径)。
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))

结果可以如下所示展示:
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


0

人们通常使用Scipy内核卷积。如果这符合您的问题,请告诉我。

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]])

谢谢,不过这会在图像的所有点上运行内核 - 我只想在5个特定位置运行它: [[211,2],[332,223],[123,432],[12,3],[154,326]]然后从上述位置运行的内核中提取5个值。 - S. Nielsen
创建一个二维子数组,将其放入您的图像中。 - Ashlou
你可以从图像中提取矩形区域,将其与掩膜相乘并求和,即reg = np.sum(img [20:30,40:50] * mask)。 - user8190410

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接