首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

python 用OpenCV 将图片转视频

  • 24-03-17 22:29
  • 3258
  • 10446
blog.csdn.net
  1. import os
  2. import cv2
  3. import numpy as np
  4. cv2.VideoWriter()参数 cv2.VideoWriter() 是 OpenCV 中用于创建视频文件的类。它的参数如下:
  5. filename:保存视频的文件名。
  6. fourcc:指定视频编解码器的 FourCC 代码,用于将视频压缩成指定格式,例如:“XVID”、“MJPG”, "mp4v"等。可以使用 cv2.VideoWriter_fourcc() 函数来获取 FourCC 代码。
  7. fps:指定视频帧率,即每秒显示的帧数。
  8. frameSize:指定视频帧的大小,即视频的分辨率,可以使用 (width, height) 形式的元组来指定。
  9. isColor:指定是否为彩色视频。如果为 True,则为彩色视频;如果为 False,则为灰度视频。
  10. 其中,前三个参数是必需的,后两个参数是可选的。例如:
  11. fps = 25
  12. cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), fps, (640, 480))
  13. def resize_img():
  14. target_size = (1000, 1000) # 所有图片缩放设置一致尺寸,目标尺寸
  15. path = './images'
  16. path_new = './images_new'
  17. if not os.path.exists(path_new):
  18. os.makedirs(path_new)
  19. filelists = []
  20. imglist = []
  21. for i in os.listdir(path):
  22. file_path = os.path.join(path, i)
  23. print(file_path)
  24. img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), cv2.IMREAD_COLOR)
  25. size = img.shape
  26. h, w = size[0], size[1]
  27. target_h, target_w = target_size[1], target_size[0]
  28. # 确定缩放的尺寸
  29. scale_h, scale_w = float(h / target_h), float(w / target_w)
  30. print(f'scale_h:{scale_h}, scale_w:{scale_w}')
  31. scale = max(scale_h, scale_w) # 选择最大的缩放比率
  32. new_w, new_h = int(w / scale), int(h / scale)
  33. # 缩放后其中一条边和目标尺寸一致
  34. resize_img = cv2.resize(img, (new_w, new_h))
  35. # 图像上、下、左、右边界分别需要扩充的像素数目
  36. top = int((target_h - new_h) / 2)
  37. bottom = target_h - new_h - top
  38. left = int((target_w - new_w) / 2)
  39. right = target_w - new_w - left
  40. print(f'top:{top} bottom:{bottom} left:{left} right:{right}')
  41. cv2.imwrite(os.path.join(path_new, f'new_{i}'), resize_img) # 写入本地文件
  42. # 填充至 target_w * target_h
  43. pad_img = cv2.copyMakeBorder(resize_img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0, 0])
  44. # cv2.imshow('img', pad_img)
  45. # cv2.waitKey(1000)
  46. filelists.append(os.path.join(path_new, f'new_{i}'))
  47. imglist.append(pad_img)
  48. return filelists, imglist
  49. def cut_img(scale):
  50. path = './images'
  51. path_new = './images_new'
  52. if not os.path.exists(path_new):
  53. os.makedirs(path_new)
  54. filelists = []
  55. imglist = []
  56. for i in os.listdir(path):
  57. file_path = os.path.join(path, i)
  58. print(file_path)
  59. img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), cv2.IMREAD_COLOR)
  60. size = img.shape
  61. h, w = size[0], size[1]
  62. rate1 = scale.split(':')
  63. w1 = int((w - w * int(rate1[0]) / int(rate1[1])) / 2)
  64. w2 = int(w - (w - w * int(rate1[0]) / int(rate1[1])) / 2)
  65. resize_img = img[0:h, w1:w2]
  66. cv2.imwrite(os.path.join(path_new, f'new_{i}'), resize_img) # 写入本地文件
  67. filelists.append(os.path.join(path_new, f'new_{i}'))
  68. imglist.append(resize_img)
  69. return filelists, imglist
  70. def cut_img1(images, scale):
  71. imglist = []
  72. filelists = []
  73. for i in images:
  74. img_url = i
  75. file_name = img_url.split('/')[-1]
  76. path_new = f'./images_new/{file_name}'
  77. try:
  78. res = requests.get(img_url)
  79. except:
  80. continue
  81. if 'RIFF' in str(res.content)[:500] or 'GIF' in str(res.content)[:500]:
  82. file_name = file_name.split('.')[0] + '.jpg'
  83. path_new1 = f'./images_new/{file_name}'
  84. img = Image.open(BytesIO(res.content)).convert('RGB')
  85. img.save(path_new1)
  86. img = cv2.imdecode(np.fromfile(path_new1, dtype=np.uint8), cv2.IMREAD_COLOR)
  87. else:
  88. image = np.asarray(bytearray(res.content), dtype="uint8")
  89. img = cv2.imdecode(image, cv2.IMREAD_COLOR)
  90. size = img.shape
  91. h, w = size[0], size[1]
  92. rate1 = scale.split(':')
  93. w1 = int((w - w * int(rate1[0]) / int(rate1[1])) / 2)
  94. w2 = int(w - (w - w * int(rate1[0]) / int(rate1[1])) / 2)
  95. resize_img = img[0:h, w1:w2]
  96. imglist.append(resize_img)
  97. filelists.append(resize_img.shape)
  98. return filelists, imglist
  99. def image_to_video():
  100. scale = '1:1' # 裁剪比例,并保持高度不变
  101. # scale = '3:4'
  102. # scale = '9:16'
  103. filelists, imglist = cut_img(scale) # 裁剪
  104. # filelists, imglist = resize_img() # 缩放
  105. fourcc = cv2.VideoWriter.fourcc(*'mp4v')
  106. im = cv2.imread(filelists[0])
  107. print(im.shape)
  108. shape1 = (im.shape[1], im.shape[0]) #需要转为视频的图片的尺寸, 视频的分辨率
  109. print('shape1:', shape1)
  110. fps = 1
  111. writer = cv2.VideoWriter('./output.mp4', fourcc, fps , shape1)
  112. # for file_path in filelists:
  113. # img = cv2.imread(file_path)
  114. # writer.write(img)
  115. for i in imglist:
  116. writer.write(i)
  117. writer.release()
  118. image_to_video()

 我们无法打开output3.mp4。这可能是因为文件类型不受支
持、文件扩展名不正确或文件已损坏,0xC00D36C4

如果生成的视频报这个错,一般是视频的分辨率 设置的不匹配

  1. import os
  2. import cv2
  3. import numpy as np
  4. cv2.VideoWriter()参数 cv2.VideoWriter() 是 OpenCV 中用于创建视频文件的类。它的参数如下:
  5. filename:保存视频的文件名。
  6. fourcc:指定视频编解码器的 FourCC 代码,用于将视频压缩成指定格式,例如:“XVID”、“MJPG”, "mp4v"等。可以使用 cv2.VideoWriter_fourcc() 函数来获取 FourCC 代码。
  7. fps:指定视频帧率,即每秒显示的帧数。
  8. frameSize:指定视频帧的大小,即视频的分辨率,可以使用 (width, height) 形式的元组来指定。
  9. isColor:指定是否为彩色视频。如果为 True,则为彩色视频;如果为 False,则为灰度视频。
  10. 其中,前三个参数是必需的,后两个参数是可选的。例如:
  11. fps = 25
  12. cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), fps, (640, 480))
  13. def resize_img():
  14. target_size = (1000, 1000) # 所有图片缩放设置一致尺寸,目标尺寸
  15. path = './images'
  16. path_new = './images_new'
  17. if not os.path.exists(path_new):
  18. os.makedirs(path_new)
  19. filelists = []
  20. imglist = []
  21. for i in os.listdir(path):
  22. file_path = os.path.join(path, i)
  23. print(file_path)
  24. img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), cv2.IMREAD_COLOR)
  25. size = img.shape
  26. h, w = size[0], size[1]
  27. target_h, target_w = target_size[1], target_size[0]
  28. # 确定缩放的尺寸
  29. scale_h, scale_w = float(h / target_h), float(w / target_w)
  30. print(f'scale_h:{scale_h}, scale_w:{scale_w}')
  31. scale = max(scale_h, scale_w) # 选择最大的缩放比率
  32. new_w, new_h = int(w / scale), int(h / scale)
  33. # 缩放后其中一条边和目标尺寸一致
  34. resize_img = cv2.resize(img, (new_w, new_h))
  35. # 图像上、下、左、右边界分别需要扩充的像素数目
  36. top = int((target_h - new_h) / 2)
  37. bottom = target_h - new_h - top
  38. left = int((target_w - new_w) / 2)
  39. right = target_w - new_w - left
  40. print(f'top:{top} bottom:{bottom} left:{left} right:{right}')
  41. cv2.imwrite(os.path.join(path_new, f'new_{i}'), resize_img) # 写入本地文件
  42. # 填充至 target_w * target_h
  43. pad_img = cv2.copyMakeBorder(resize_img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0, 0])
  44. # cv2.imshow('img', pad_img)
  45. # cv2.waitKey(1000)
  46. filelists.append(os.path.join(path_new, f'new_{i}'))
  47. imglist.append(pad_img)
  48. return filelists, imglist
  49. def cut_img(scale):
  50. path = './images'
  51. path_new = './images_new'
  52. if not os.path.exists(path_new):
  53. os.makedirs(path_new)
  54. filelists = []
  55. imglist = []
  56. for i in os.listdir(path):
  57. file_path = os.path.join(path, i)
  58. print(file_path)
  59. img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), cv2.IMREAD_COLOR)
  60. size = img.shape
  61. h, w = size[0], size[1]
  62. rate1 = scale.split(':')
  63. w1 = int((w - w * int(rate1[0]) / int(rate1[1])) / 2)
  64. w2 = int(w - (w - w * int(rate1[0]) / int(rate1[1])) / 2)
  65. resize_img = img[0:h, w1:w2]
  66. cv2.imwrite(os.path.join(path_new, f'new_{i}'), resize_img) # 写入本地文件
  67. filelists.append(os.path.join(path_new, f'new_{i}'))
  68. imglist.append(resize_img)
  69. return filelists, imglist
  70. def cut_img1(images, scale):
  71. imglist = []
  72. filelists = []
  73. for i in images:
  74. img_url = i
  75. file_name = img_url.split('/')[-1]
  76. path_new = f'./images_new/{file_name}'
  77. try:
  78. res = requests.get(img_url)
  79. except:
  80. continue
  81. if 'RIFF' in str(res.content)[:500] or 'GIF' in str(res.content)[:500]:
  82. file_name = file_name.split('.')[0] + '.jpg'
  83. path_new1 = f'./images_new/{file_name}'
  84. img = Image.open(BytesIO(res.content)).convert('RGB')
  85. img.save(path_new1)
  86. img = cv2.imdecode(np.fromfile(path_new1, dtype=np.uint8), cv2.IMREAD_COLOR)
  87. else:
  88. image = np.asarray(bytearray(res.content), dtype="uint8")
  89. img = cv2.imdecode(image, cv2.IMREAD_COLOR)
  90. size = img.shape
  91. h, w = size[0], size[1]
  92. rate1 = scale.split(':')
  93. w1 = int((w - w * int(rate1[0]) / int(rate1[1])) / 2)
  94. w2 = int(w - (w - w * int(rate1[0]) / int(rate1[1])) / 2)
  95. resize_img = img[0:h, w1:w2]
  96. imglist.append(resize_img)
  97. filelists.append(resize_img.shape)
  98. return filelists, imglist
  99. def image_to_video():
  100. scale = '1:1' # 裁剪比例,并保持高度不变
  101. # scale = '3:4'
  102. # scale = '9:16'
  103. filelists, imglist = cut_img(scale) # 裁剪
  104. # filelists, imglist = resize_img() # 缩放
  105. fourcc = cv2.VideoWriter.fourcc(*'mp4v')
  106. im = cv2.imread(filelists[0])
  107. print(im.shape)
  108. shape1 = (im.shape[1], im.shape[0]) #需要转为视频的图片的尺寸, 视频的分辨率
  109. print('shape1:', shape1)
  110. fps = 1
  111. writer = cv2.VideoWriter('./output.mp4', fourcc, fps , shape1)
  112. # for file_path in filelists:
  113. # img = cv2.imread(file_path)
  114. # writer.write(img)
  115. for i in imglist:
  116. writer.write(i)
  117. writer.release()
  118. image_to_video()

 我们无法打开output3.mp4。这可能是因为文件类型不受支
持、文件扩展名不正确或文件已损坏,0xC00D36C4

如果生成的视频报这个错,一般是视频的分辨率 设置的不匹配

注:本文转载自blog.csdn.net的FOAF-lambda的文章"https://blog.csdn.net/lwdfzr/article/details/135158033"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

114
音视频
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top