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

OpenCV读取路径文件报错(-215:Assertion failed)如何解决?

问题核心原因

你触发报错的根本原因是路径拼接错误:你的images_dir和masks_dir路径末尾没有带路径分隔符/,直接和文件名拼接后会生成无效路径,比如会得到/content/drive/MyDrive/dataset/imagesxxx.jpg而不是预期的/content/drive/MyDrive/dataset/images/xxx.jpg,OpenCV找不到对应文件就会返回None,后续调用cv2.cvtColor传入空值就触发了断言报错。

具体修改方案

1. 优化文件名读取逻辑(可选但推荐)

你当前用numpy处理文件名的逻辑冗余,还可能误读非图片文件,建议简化为如下代码:

import os
import numpy as np
import cv2

# 路径末尾统一加/,或者后续用os.path.join拼接更稳妥
images_dir = '/content/drive/MyDrive/dataset/images/'
masks_dir = '/content/drive/MyDrive/dataset/masks/'

# 仅保留jpg格式的图像,提取文件名前缀
filenames = []
for f in os.listdir(images_dir):
    if f.lower().endswith('.jpg'):
        filenames.append(os.path.splitext(f)[0])
# 排序后转numpy数组(如果后续需要numpy操作可保留,否则直接用列表即可)
filenames = np.sort(filenames)

2. 修正数据增强函数的路径拼接和异常判断

修改文件读取部分,用os.path.join自动适配路径分隔符,同时增加读取成功校验,避免异常中断:

def augment_dataset(count):
    '''Function for data augmentation
        Input:
            count - total no. of images after augmentation = initial no. of images * count
        Output:
            writes augmented images (input images & segmentation masks) to the working directory
    '''
    transform_1 = augment(512, 512)
    transform_2 = augment(480, 480)
    transform_3 = augment(512, 512)
    transform_4 = augment(800, 800)
    transform_5 = augment(1024, 1024)
    transform_6 = augment(800, 800)
    transform_7 = augment(1600, 1600)
    transform_8 = augment(1920, 1280)
    
    for i in range(count):
        for file in filenames:
            tile = file.split('_')[1]
            # 用os.path.join拼接路径,自动处理路径分隔符
            img_path = os.path.join(images_dir, f"{file}.jpg")
            mask_path = os.path.join(masks_dir, f"{file}.png")
            
            # 读取图像并校验非空
            img = cv2.imread(img_path)
            if img is None:
                print(f"警告:图像读取失败,路径为{img_path},已跳过")
                continue
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            
            # 读取掩码并校验非空
            mask = cv2.imread(mask_path)
            if mask is None:
                print(f"警告:掩码读取失败,路径为{mask_path},已跳过")
                continue
            mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
            
            # 后续你的数据增强、文件写入逻辑接在这里即可

3. 额外排查方案

如果修改后仍有少量文件报错,可以打印拼接后的路径,手动到对应目录检查文件是否存在、文件名大小写是否匹配,确认掩码后缀确实为png、图像确实为jpg格式即可。

内容的提问来源于stack exchange,提问作者Mo.be

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:45:03