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

Python中基于矩阵值实现256×256图像逐像素着色方法问询

Solution: Implementing draw_tile for Value-to-Color Image Generation

Got it, let's break down how to build this draw_tile function efficiently. The core idea is mapping each value in your input matrix to its corresponding RGBA color, then scaling that small color grid up to your desired image size. Here's a complete, ready-to-use implementation:

import numpy as np
from PIL import Image

# Define color mappings for different types. Extend this with your own schemes as needed.
COLOR_MAPS = {
    'example': {
        -64: (0, 0, 0, 255),       # Solid black
        -8: (25, 25, 25, 255),      # Dark gray
        8: (40, 200, 200, 255),     # Light cyan (placeholder for your example)
        10: (45, 255, 255, 255),    # Bright cyan
        22: (150, 150, 255, 255),   # Soft blue
        50: (100, 255, 100, 255)    # Light green
    },
    # Add more types here, e.g., 'heatmap', 'grayscale', etc.
}

def draw_tile(matrix: np.matrix, type: str, img_size: tuple) -> Image:
    """
    Generates an RGBA image from a value matrix, mapping values to colors based on the specified type.
    
    Args:
        matrix: Input numpy matrix containing values to map to colors.
        type: String key corresponding to a color map in COLOR_MAPS.
        img_size: Tuple of (width, height) for the output image.
        
    Returns:
        PIL Image object in RGBA mode, scaled to img_size.
        
    Raises:
        ValueError: If the specified type is not found in COLOR_MAPS.
    """
    # Retrieve the color map for the given type
    color_map = COLOR_MAPS.get(type)
    if not color_map:
        raise ValueError(f"Unsupported type '{type}'. Available types: {list(COLOR_MAPS.keys())}")
    
    # Convert numpy matrix to a regular array for easier manipulation
    matrix_array = np.asarray(matrix)
    
    # Vectorize the value-to-color mapping for fast processing
    def map_val_to_rgba(val):
        # Default to transparent black if value isn't in the color map
        return color_map.get(val, (0, 0, 0, 0))
    
    vectorized_mapper = np.vectorize(map_val_to_rgba, otypes=[np.uint8, np.uint8, np.uint8, np.uint8])
    
    # Apply mapping to get separate RGBA channels
    r, g, b, a = vectorized_mapper(matrix_array)
    
    # Combine channels into a single RGBA array
    color_matrix = np.stack([r, g, b, a], axis=-1)
    
    # Create base image from the color matrix
    base_img = Image.fromarray(color_matrix.astype(np.uint8), mode='RGBA')
    
    # Resize to desired size using nearest neighbor to keep sharp color blocks
    resized_img = base_img.resize(img_size, resample=Image.Resampling.NEAREST)
    
    return resized_img

# Example usage
if __name__ == "__main__":
    test_matrix = np.matrix([[-64, -64, -64], [-8, 10, 8], [10, 50, 22]])
    output_img = draw_tile(test_matrix, 'example', (256, 256))
    output_img.save("tile_example.png")
    output_img.show()

Key Notes:

  • Color Scheme Flexibility: The COLOR_MAPS dictionary lets you define multiple color schemes (controlled by the type parameter). Add new entries here for different value-to-color rules.
  • Efficient Processing: Using np.vectorize ensures we handle matrix values quickly, even for larger input matrices.
  • Unknown Values: If a value in your matrix isn’t in the color map, we default to transparent black ((0,0,0,0)). Adjust this in the map_val_to_rgba function if you prefer a different fallback.
  • Sharp Scaling: We use Image.Resampling.NEAREST to resize the image, which preserves solid color blocks instead of blurring them—perfect for tile-based visuals.

内容的提问来源于stack exchange,提问作者Степан Молостов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:18:55