使用Pyrealsense相机捕获帧时出现OpenCV错误求助
Pyrealsense相机流获取时OpenCV颜色映射错误排查与修复
错误信息
在从Pyrealsense相机获取流时,终端抛出如下错误:
Error capturing frames: OpenCV(4.11.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\colormap.cpp:736: error: (-5:Bad argument) cv::ColorMap only supports source images of type CV_8UC1 or CV_8UC3 in function 'cv::colormap::ColorMap::operator ()'
相关代码
def get_frames(self): """Get frames from the camera""" try: self.log.debug("Waiting for frames...") self.frames = self.pipeline.wait_for_frames() depth_frame = self.frames.get_depth_frame() color_frame = self.frames.get_color_frame() # Check for valid frames if not depth_frame or not color_frame: return None, None, None #Convert images to numpy arrays for input to OpenCV depth_image = np.asanyarray(depth_frame.get_data()) color_image = np.asanyarray(color_frame.get_data()) # Apply colormap on depth image depth_colormap = cv2.normalize(depth_image, None, 0, 255, cv2.NORM_MINMAX) depth_colormap = np.uint8(depth_colormap) depth_colormap = cv2.applyColorMap(depth_colormap, cv2.COLORMAP_JET) combined_image = np.hstack((color_image, depth_colormap)) return depth_image, color_image, combined_image except Exception as e: self.log.error(f"Error capturing frames: {e}") return None, None, None
错误原因
OpenCV的cv2.applyColorMap函数要求输入图像必须是单通道8位无符号整数(CV_8UC1)或三通道8位无符号整数(CV_8UC3)。RealSense深度帧原生是16位(uint16)数据,代码中cv2.normalize默认会保留输入的uint16类型,后续手动转np.uint8可能出现隐性的类型/通道不匹配问题,导致输入不符合函数要求。
修复方案
直接在cv2.normalize中指定输出类型为CV_8U,跳过后续手动类型转换,确保输出是符合要求的单通道8位图像:
修改深度图处理代码如下:
# Apply colormap on depth image # 直接在normalize时指定输出类型为CV_8U,避免类型转换问题 depth_colormap = cv2.normalize(depth_image, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U) depth_colormap = cv2.applyColorMap(depth_colormap, cv2.COLORMAP_JET)
额外验证(可选)
如果问题仍然存在,可以在调用cv2.applyColorMap前添加一行代码,强制确保图像为单通道:
# 强制转为单通道 depth_colormap = np.expand_dims(depth_colormap, axis=-1)
内容的提问来源于stack exchange,提问作者Nchimunya
相关产品推荐
相关产品推荐

