为何无法读取tools_list中全部图片?TypeError报错求助
问题解决思路
错误根源
- 路径不完整:
os.listdir("tools")仅返回文件名,未包含tools/前缀,cv.imread会在当前工作目录查找文件,自然找不到,返回None。 - 未过滤文件类型:若
tools目录存在非.png文件,cv.imread加载会失败,同样返回None。 - 当尝试将
None赋值给frame[0:125, 0:1280]时,numpy数组无法接受None作为赋值对象,直接触发TypeError。
修复步骤
- 生成完整文件路径:遍历
tools目录时,用os.path.join拼接目录与文件名,确保cv.imread能定位到正确文件。 - 过滤仅保留.png文件:只处理后缀为
.png的文件,避免加载无效文件。 - 检查加载结果:过滤掉加载失败(返回
None)的元素,同时调整图片尺寸与目标切片匹配,避免后续尺寸不匹配报错。
修改后的代码
import os import cv2 as cv import numpy as np import mediapipe as mp mp_hands = mp.solutions.hands # 生成完整路径+过滤png文件 tools_dir = "tools" tools_list = [os.path.join(tools_dir, elem) for elem in os.listdir(tools_dir) if elem.lower().endswith(".png")] print(tools_list) # 加载图片并过滤失败项,同时调整尺寸匹配切片 images_list = [] for img_path in tools_list: img = cv.imread(img_path) if img is not None: img = cv.resize(img, (1280, 125)) images_list.append(img) else: print(f"加载失败:{img_path}") print(images_list) mode = "selection mode" brush_thickness = 15 mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands xp, yp = 0, 0 capture = cv.VideoCapture(0) black = (0,0,0) white = (255,255,255) blue = (255,0,0) red = (0,0,255) green = (0,255,0) yellow = (0,255,255) brown = (0, 75, 150) image_number = 0 color = black image_canvas = np.zeros((720, 1280, 3), np.uint8) # 确保有可用图片再进入循环 if not images_list: print("没有成功加载任何图片,请检查tools目录下的png文件") else: with mp_hands.Hands(min_detection_confidence = 0.8, min_tracking_confidence = 0.5, max_num_hands = 2) as hands: while True: flag, frame = capture.read() if not flag: print("无法读取摄像头帧") break frame = cv.resize(frame, (1280, 720)) # 防止索引越界 image_number = image_number % len(images_list) frame[0:125, 0:1280] = images_list[image_number] # 此处可添加原有的手部检测、绘图等逻辑 cv.imshow("Frame", frame) if cv.waitKey(1) & 0xFF == ord('q'): break capture.release() cv.destroyAllWindows()
额外说明
- 新增图片尺寸调整,确保和
frame[0:125, 0:1280]的1280×125尺寸一致,避免尺寸不匹配报错。 - 加入
image_number取模处理,防止切换图片时索引越界。 - 添加空图片列表、摄像头帧读取失败的判断,提升代码健壮性。
内容的提问来源于stack exchange,提问作者Cebuc Alexandru Bogdan
相关产品推荐
相关产品推荐

