10-视频图像读取与保存
1. 截取图像的ROI区域并保存
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import cv2 2 3 img_01 = cv2.imread("E:\\zpp\\ImageLabel\\test\\0.jpg") 4 5 # img_01_gray = cv2.cvtColor(img_01, cv2.COLOR_BGR2GRAY) 6 # res, img_01_bin = cv2.threshold(img_01_gray, 20, 255, cv2.THRESH_BINARY) 7 8 9 path = "E:\\zpp\\ImageLabel\\test\\" 10 11 savePath = "E:\\zpp\\ImageLabel\\test_new\\" 12 13 for i in range(30): 14 15 if(i>9): 16 img_path = path +str(i) +".jpg" 17 img_02 = cv2.imread(img_path) 18 19 img_save_path = savePath +str(i) +".jpg" 20 21 crop_img = img_02[140:1360, 20:1070,:] 22 img_01[150:1370, 200:1250, :] = crop_img 23 24 # cv2.imshow("01", crop_img) 25 cv2.imshow("02", img_01) 26 cv2.imwrite(img_save_path, img_01) 27 28 cv2.waitKey(1)
2. 读取连续帧图像,可对每帧图像进行处理,然后保存为视频文件;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import cv2 2 3 #图片路径 4 imgPath = "E:\\zpp\\ImageLabel\\02_CamAnnoTool\\" 5 #输出视频路径 6 video_dir = 'E:\\zpp\\ImageLabel\\02_CamAnnoTool\\out.avi' 7 #帧率 8 fps = 30 9 #图片数 10 num = 6 11 #图片尺寸 12 img_size = (1920, 1080) 13 14 fourcc = cv2.VideoWriter_fourcc('M','J','P','G') #opencv3.0 15 videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size) 16 frame_count =0 17 18 for i in range(123): 19 20 imgName = imgPath + str(i)+ ".jpg" 21 frame = cv2.imread(imgName) 22 23 if i == 122: 24 frame_count = 150 25 26 27 28 for j in range(frame_count): 29 frame = cv2.resize(frame, (1920,1080)) 30 videoWriter.write(frame) 31 32 else: 33 frame_count = 50 34 35 36
3. 读取视频图像,可对每帧图像进行处理,然后保存为新的视频文件。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import cv2 2 3 #输出视频路径 4 video_dir = 'E:\\zpp\\ImageLabel\\04_CamAnnoTool\\out.avi' 5 6 #帧率 7 fps = 30 8 #图片数 9 num = 6 10 #图片尺寸 11 img_size = (1920, 1080) 12 13 fourcc = cv2.VideoWriter_fourcc('M','J','P','G') #opencv3.0 14 videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size) 15 16 17 cap = cv2.VideoCapture("F:/FFOutput/6.mp4")#打开视频 18 i=0 19 while cap.isOpened(): 20 ret,frame = cap.read()#读取视频返回视频是否结束的bool值和每一帧的图像 21 22 if frame is None: 23 break 24 25 cv2.imshow('a',frame) 26 cv2.waitKey(1) 27 28 frame = cv2.resize(frame, (1920,1080)) 29 videoWriter.write(frame) 30 31 # cv2.imwrite("F:/image/Demo04/"+str(i)+".bmp",frame) 32 i = i+1 33 # cv2.destroyAllWindows() 34 35 img = cv2.imread("E:\\zpp\\ImageLabel\\02_CamAnnoTool\\70.jpg") 36 37 for j in range(50): 38 frameEnd = cv2.resize(img, (1920,1080)) 39 videoWriter.write(frameEnd) 40 41 print(i)