使用OpenCV保存水下增强视频时格式不支持无法播放的问题
问题分析与解决
你的视频无法播放主要是以下几个原因导致的,对应修复方法如下:
- 视频尺寸不匹配:创建
VideoWriter时指定的分辨率是(640,480),但代码中通过resize将帧缩放到了原尺寸的50%,处理后的img_bgr尺寸和写入器的尺寸不一致,这会导致视频文件结构损坏。需要让写入器的分辨率和处理后帧的实际尺寸保持一致。 - 未释放
VideoWriter资源:代码只释放了VideoCapture,但没有调用out.release(),这会导致视频文件没有正确完成收尾操作,无法被播放器识别。 - 未检查帧读取状态:循环中没有判断
ret是否为True,当视频读取完毕后,frame会是None,继续处理会引发错误,也会破坏写入的视频文件。 - 数据类型不匹配:对
img_lab[:,:,0]进行乘法和裁剪后,数据可能变成浮点型,而OpenCV要求图像是uint8类型,需要转换后再写入。
修改后的完整代码
import cv2 import numpy as np cap = cv2.VideoCapture('Images/tubb.mp4') # 获取原视频帧率,保证保存视频的速度和原视频一致 fps = cap.get(cv2.CAP_PROP_FPS) # 先读取一帧获取处理后的实际尺寸 ret, frame = cap.read() if not ret: print("无法读取视频文件") exit() frame_resized = cv2.resize(frame, (0,0), fx=0.5, fy=0.5) h, w = frame_resized.shape[:2] fourcc = cv2.VideoWriter_fourcc(*'XVID') # 使用处理后的实际尺寸创建视频写入器 out = cv2.VideoWriter('output.avi', fourcc, fps, (w, h)) # 处理刚才提前读取的第一帧 if ret: frame1 = frame_resized frame1[:,:,2] = cv2.equalizeHist(frame1[:,:,2]) img_lab = cv2.cvtColor(frame1, cv2.COLOR_BGR2LAB) # 裁剪后转换为uint8类型,符合OpenCV图像要求 img_lab[:,:,0] = np.clip(img_lab[:,:,0] * 1.5, 0, 255).astype(np.uint8) img_bgr = cv2.cvtColor(img_lab, cv2.COLOR_LAB2BGR) cv2.imshow('original new', frame_resized) cv2.imshow('output', img_bgr) cv2.imshow('original', frame) out.write(img_bgr) # 循环处理剩余帧 while ret: ret, frame = cap.read() if not ret: break frame_resized = cv2.resize(frame, (0,0), fx=0.5, fy=0.5) cv2.imshow('original new', frame_resized) frame1 = frame_resized frame1[:,:,2] = cv2.equalizeHist(frame1[:,:,2]) img_lab = cv2.cvtColor(frame1, cv2.COLOR_BGR2LAB) img_lab[:,:,0] = np.clip(img_lab[:,:,0] * 1.5, 0, 255).astype(np.uint8) img_bgr = cv2.cvtColor(img_lab, cv2.COLOR_LAB2BGR) cv2.imshow('output', img_bgr) cv2.imshow('original', frame) out.write(img_bgr) if cv2.waitKey(6) == 27: break # 释放所有资源,包括视频写入器 cap.release() out.release() cv2.destroyAllWindows()
额外说明
- 使用原视频的帧率
fps代替固定值20.0,能保证保存的视频播放速度和原视频一致。 - 确保
VideoWriter初始化时的尺寸参数是(宽度, 高度),和处理后帧的尺寸顺序完全匹配。 - 对图像做数值运算后,必须转换为
uint8类型,避免写入时出现数据格式异常。
内容的提问来源于stack exchange,提问作者Neel Kheni
相关产品推荐
相关产品推荐

