You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于掩码从图像(二维数组)特定坐标提取像素值?

Solution: Extract Pixel Values Using Circular Masks at Local Maxima Coordinates

Let’s walk through a practical implementation that ties together your existing peak_local_max output and the createCircularMask function to extract pixel values from your 512×512 image stack.

1. First, Complete the Circular Mask Function

Your provided createCircularMask snippet is incomplete—here’s the full, functional version that handles edge cases (like when the mask would go beyond the image bounds):

import numpy as np

def createCircularMask(h, w, center=None, radius=None):
    if center is None:
        center = [int(w/2), int(h/2)]
    if radius is None:
        # Auto-adjust radius to fit within image if no value is provided
        radius = min(center[0], center[1], w-center[0], h-center[1])
    
    # Create a grid of coordinates across the image
    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y - center[1])**2)
    
    # Generate boolean mask: True inside the circle, False outside
    mask = dist_from_center <= radius
    return mask

2. Core Logic: Extract Pixel Values at Each Local Maximum

The key idea is to iterate over each (x, y) coordinate from peak_local_max, generate a circular mask centered at that point, then use the mask to pull out the relevant pixel values from the image.

Step 1: Confirm Local Maxima Coordinate Order

Note that peak_local_max returns coordinates in (row, column) order (which maps to (y, x) in standard image pixel terms). If you’re working with (x, y) positions, you’ll need to swap the columns:

from skimage.feature import peak_local_max

# Example: Load a single frame from your stack (replace with your actual data)
tmp_frame = np.random.randint(0, 4000, size=(512, 512))  # Dummy test data

# Get local maxima (returns (y, x) by default)
local_max_coords = peak_local_max(tmp_frame, min_distance=15, threshold_abs=3000)
# Convert to (x, y) if that's your preferred format
local_max_xy = local_max_coords[:, [1, 0]]

Step 2: Extract Pixels for Each Maximum

Define a helper function to extract pixels using the mask—you can choose to collect raw pixel values, or compute statistics like mean/sum depending on your needs:

def extract_pixels_at_max(image, max_coords, mask_radius=10):
    h, w = image.shape
    extracted_data = []
    
    for (x, y) in max_coords:
        # Create mask centered at the current maximum coordinate
        mask = createCircularMask(h, w, center=(x, y), radius=mask_radius)
        # Extract all pixels where the mask is True
        masked_pixels = image[mask]
        # Store data (customize this based on what you need)
        extracted_data.append({
            'coords': (x, y),
            'raw_pixels': masked_pixels,
            'mean_intensity': np.mean(masked_pixels),
            'total_intensity': np.sum(masked_pixels)
        })
    
    return extracted_data

Step 3: Process Your Entire Image Stack

If you’re working with a stack of images, wrap the extraction in a loop over each frame:

# Example: Process a full image stack (shape: (num_frames, 512, 512))
image_stack = np.random.randint(0, 4000, size=(10, 512, 512))  # Dummy stack
all_frame_data = []

for frame_idx, frame in enumerate(image_stack):
    # Get local maxima for the current frame
    local_max_coords = peak_local_max(frame, min_distance=15, threshold_abs=3000)
    local_max_xy = local_max_coords[:, [1, 0]]
    # Extract pixel data for this frame's maxima
    frame_results = extract_pixels_at_max(frame, local_max_xy, mask_radius=10)
    all_frame_data.append({
        'frame_number': frame_idx,
        'maxima_results': frame_results
    })

3. Edge Case Handling

  • Maxima near image edges: The createCircularMask function automatically shrinks the radius if the center is too close to the edge (if you don’t specify a fixed radius). If you want a fixed radius regardless of edges, you can crop the mask to avoid out-of-bounds errors.
  • Performance: For large stacks, consider using parallel processing (e.g., joblib) or vectorized operations to speed up extraction.

内容的提问来源于stack exchange,提问作者S. Nielsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:47:56