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

基于自定义数据集的Mask R-CNN实例分割出现IndexError求助

解决Mask R-CNN自定义数据集加载时的IndexError问题

问题原因

你的错误源于图像索引从0开始:512×512的图像,宽度方向的有效索引范围是0~511,但skimage.draw.polygon生成的坐标中出现了512,超出了数组边界。常见诱因包括:

  • 标注的多边形坐标直接使用了图像的实际像素尺寸(比如512),而非索引值(应到511)
  • 多边形边缘计算时,生成的像素点超出了图像的有效索引范围

解决方案

在使用坐标更新mask前,先过滤或裁剪掉超出图像边界的坐标,确保所有索引都在有效范围内。

修改后的完整代码片段

def load_mask(self, image_id):
    """Generate instance masks for an image.
   Returns:
    masks: A bool array of shape [height, width, instance count] with
        one mask per instance.
    class_ids: a 1D array of class IDs of the instance masks.
    """
    # If not a Dog-Cat dataset image, delegate to parent class.
    image_info = self.image_info[image_id]
    if image_info["source"] != "object":
        return super(self.__class__, self).load_mask(image_id)

    # Convert polygons to a bitmap mask of shape
    # [height, width, instance_count]
    info = self.image_info[image_id]
    if info["source"] != "object":
        return super(self.__class__, self).load_mask(image_id)
    num_ids = info['num_ids']
    mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
                    dtype=np.uint8)
    for i, p in enumerate(info["polygons"]):
        # Get indexes of pixels inside the polygon and set them to 1
        rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
        
        # 过滤超出图像边界的无效坐标
        valid_indices = (rr >= 0) & (rr < info["height"]) & (cc >= 0) & (cc < info["width"])
        rr = rr[valid_indices]
        cc = cc[valid_indices]
        
        # 也可以用clip函数直接裁剪到有效范围(二选一即可)
        # rr = np.clip(rr, 0, info["height"] - 1)
        # cc = np.clip(cc, 0, info["width"] - 1)

        mask[rr, cc, i] = 1

    # Return mask, and array of class IDs of each instance. Since we have
    # one class ID only, we return an array of 1s
    # Map class names to class IDs.
    num_ids = np.array(num_ids, dtype=np.int32)
    return mask, num_ids #np.ones([mask.shape[-1]], dtype=np.int32)

额外优化建议

  • 检查标注数据:确认所有多边形的all_points_x最大值不超过info["width"]-1,all_points_y最大值不超过info["height"]-1,从源头上避免越界问题。
  • 如果标注是基于图像实际尺寸创建的,可以在加载标注时直接对坐标减1,统一转换为索引格式。

内容的提问来源于stack exchange,提问作者Lim Cheng Wei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:45:31