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

基于Python实现含物料RGB图像的网格掩码生成功能

问题与解决方案

问题描述

处理RGB编码图像文件,背景为紫色(RGB(37, 150, 190)),物料指所有非背景像素。现有两个图表:右侧逐个展示图像文件中的tile,左侧为掩码图。需实现:若右侧tile对应的网格内存在物料,则左侧掩码图的对应网格填充为白色。当前思路正确但不知具体实现。

实现步骤与修改后代码

核心逻辑:

  • 明确网格边界范围,将512x512图像划分为5x5网格
  • 对每个tile检测是否存在非背景像素
  • 若存在物料,将左侧掩码图对应网格填充为白色
  • 实时更新左右图表展示

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt
from wsi_utils.wsi import WSI, Slide, Path

plt.rcParams['lines.linewidth'] = 0.1

# 初始化WSI
wsi = WSI()

# 读取掩码文件与tiles
mask_file = Slide(wsi, Path("60d21e3e6ddf4448d476c7d0.msk"))
tiles = mask_file.read_tiles(10, [-1])

# 图像尺寸与初始掩码图(黑色)
img_size = (512, 512)
img = np.zeros(img_size, dtype=np.uint8)

# 网格线坐标,扩展为完整的边界区间
x_coords = [64, 192, 320, 448]
y_coords = [64, 192, 320, 448]
x_bounds = [0] + x_coords + [512]
y_bounds = [0] + y_coords + [512]
grid_count = len(x_bounds) - 1  # 5x5网格

# 创建子图
fig, axs = plt.subplots(1, 2, figsize=(12, 4))

# 绘制网格线
for x in x_coords:
    axs[0].axvline(x=x, color='white')
    axs[1].axvline(x=x, color='white')
for y in y_coords:
    axs[0].axhline(y=y, color='white')
    axs[1].axhline(y=y, color='white')

# 背景色定义
bg_color = np.array([37, 150, 190])

# 遍历每个tile,更新掩码图
for idx, tile in enumerate(tiles):
    tile_data = tile[0].data
    # 计算当前tile对应的网格索引(假设tiles按行优先顺序排列:0-4为第一行,5-9为第二行...)
    grid_row = idx // grid_count
    grid_col = idx % grid_count
    
    # 检测tile中是否存在非背景像素
    has_material = np.any(np.any(tile_data != bg_color, axis=2))
    
    if has_material:
        # 获取对应网格的坐标范围
        y_start, y_end = y_bounds[grid_row], y_bounds[grid_row+1]
        x_start, x_end = x_bounds[grid_col], x_bounds[grid_col+1]
        # 填充该网格为白色(255)
        img[y_start:y_end, x_start:x_end] = 255
    
    # 更新左右图表
    axs[0].imshow(img, cmap='gray')
    axs[1].imshow(tile_data)
    plt.pause(1)

plt.show()

关键代码解释

  1. 网格边界扩展:将原网格线坐标扩展为包含0和512的完整区间,方便快速定位每个网格的像素范围。
  2. 物料检测:通过嵌套np.any()判断,只要tile内存在任意一个非背景像素,就判定该网格包含物料。
  3. 网格填充:根据tile的索引(按行优先顺序)匹配对应网格,将该区域掩码图像素设为255(白色)。
  4. 实时更新:每次循环刷新左右图表并暂停1秒,实现逐个tile的动态展示效果。

内容的提问来源于stack exchange,提问作者umba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:42:24