繁体   English   中英

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

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

我有一个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坐标处应用我的蒙版以获得局部最大值周围的和像素值并将它们存储在列表中。

但是,我可以找到一个允许我只在两个数组中应用掩码给定位置的函数?

以下代码段显示如何获取特定坐标处的图像的局部总和。 请注意,局部和是在固定半径的圆形掩模内计算的(可能需要调整代码以将半径从一个位置更改为另一个位置)。

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)

结果

人们通常使用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]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM