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

单张图像自定义函数增强报错:TypeError: Can't convert object to 'str' for 'filename'

问题排查与解决

错误原因

核心问题是变量path的类型在循环中发生了冲突:

  1. 初始时path是字符串类型的图像路径,第一次调用自定义函数(如crop(path))时,函数接收路径并返回处理后的图像数组。
  2. 执行path=fun后,path变成了图像数组,但你的crop/resize/flip/h_flip函数仍然期望接收字符串路径,第二次调用时就会触发TypeError: Can't convert object to 'str' for 'filename'。

修复方案

1. 提前加载原始图像

先一次性把图像加载为数组,后续所有增强操作都基于图像数组处理,不再依赖路径:

import cv2 as cv
import random
import matplotlib.pyplot as plt

# 提前加载原始图像
img = cv.imread('img dir')  # 替换为你的实际图像路径
# 自定义增强函数列表(需确保所有函数接收图像数组,返回处理后的图像数组)
funs = [crop, resize, flip, h_flip] 
n = 3

plt.figure(figsize=(10,12))
current_img = img.copy()
for i in range(n):
    random.shuffle(funs)
    # 用当前图像数组作为函数输入
    current_img = random.choice(funs)(current_img)
    plt.subplot(3,3,i+1)
    plt.imshow(cv.cvtColor(current_img, cv.COLOR_BGR2RGB))
    plt.axis('off')

plt.show()

2. 修正自定义函数的输入类型

检查你的自定义函数,确保它们接收图像数组而非路径:
错误写法(接收路径):

def crop(img_path):
    img = cv.imread(img_path)
    # 裁剪逻辑
    return cropped_img

正确写法(接收图像数组):

def crop(img):
    # 直接对传入的图像数组执行裁剪
    cropped_img = img[100:300, 100:300]  # 示例裁剪区域,按需修改
    return cropped_img

额外优化

如果希望每次增强都基于原始图像(而非链式叠加增强),把图像副本的创建放到循环内部即可:

for i in range(n):
    random.shuffle(funs)
    current_img = random.choice(funs)(img.copy())  # 每次用原始图像的副本处理
    # 后续绘图代码不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:15:35