video2images.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import cv2
  2. from datetime import datetime
  3. from pathlib import Path
  4. from module.logger import logger
  5. from tasks.base_task import BaseTask
  6. from tasks.Hyakkiyakou.assets import HyakkiyakouAssets
  7. class TransformVideo(HyakkiyakouAssets):
  8. def __init__(self, change_channel: bool = False, interval: float = 2):
  9. """
  10. @param interval: 视频帧间隔,默认2
  11. @param change_channel: 修改视频通道数,默认False
  12. """
  13. self.change_channel = change_channel
  14. self.interval = interval
  15. def run(self, video: str | Path, save_path: str | Path):
  16. """
  17. @param video: 视频的路径,可以是单个视频也可以是一个文件夹
  18. @param save_path: 保存的路径
  19. @return:
  20. """
  21. if isinstance(video, str):
  22. video = Path(video)
  23. if not isinstance(video, Path):
  24. logger.error(f'{video} is not a valid path')
  25. return
  26. if isinstance(save_path, str):
  27. save_path = Path(save_path)
  28. if not isinstance(save_path, Path):
  29. logger.error(f'{save_path} is not a valid path')
  30. return
  31. save_path.mkdir(parents=True, exist_ok=True)
  32. if video.is_dir():
  33. for video_file in video.iterdir():
  34. self.parse_one(video_file, save_path)
  35. else:
  36. self.parse_one(video, save_path)
  37. def parse_one(self, video: Path, save_path: Path = None, mode: int = 2):
  38. """
  39. 单次解析一个视频
  40. @param mode: 0:左边 1:右边 2: 两边
  41. @param video:
  42. @param save_path:
  43. @return:
  44. """
  45. if isinstance(video, str):
  46. video = Path(video)
  47. if not save_path:
  48. save_path = video.parent / f'images_{video.stem}'
  49. if isinstance(save_path, str):
  50. save_path = Path(save_path)
  51. save_path.mkdir(parents=True, exist_ok=True)
  52. # 获取时间戳的str形式,用来命名图片
  53. datetime_now = datetime.now().strftime('%Y%m%dT%H%M%S')
  54. logger.info(f'Start transform video {video}')
  55. cap = cv2.VideoCapture(str(video))
  56. if not cap.isOpened():
  57. logger.error(f'{video} open failed')
  58. return
  59. fps = cap.get(cv2.CAP_PROP_FPS)
  60. frame_skip = int(fps * self.interval)
  61. count_frame = 0 # 抽帧用的
  62. index_frame = 0 # 记录
  63. while 1:
  64. ret, frame = cap.read()
  65. if not ret:
  66. break
  67. # 抽帧
  68. count_frame += 1
  69. if count_frame % frame_skip != 0:
  70. continue
  71. h, w, _ = frame.shape
  72. if h == 720 and w == 1280:
  73. pass
  74. elif h == 720 and w != 1280:
  75. frame = frame[:, 0:1280]
  76. elif w != 1280 and h != 720:
  77. frame = cv2.resize(frame, (1280, 720))
  78. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  79. # 检查是否是百鬼夜行中
  80. # if not self.I_CHECK_RUN.match(frame, threshold=0.5):
  81. # continue
  82. if not self.change_channel:
  83. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  84. index_frame += 1
  85. h, w, _ = frame.shape
  86. match mode:
  87. case 0:
  88. img_a = frame[h-640:, 0:640]
  89. img_b = None
  90. case 1:
  91. img_a = None
  92. img_b = frame[h-640:, 640:1280]
  93. case 2:
  94. img_a = frame[h-640:, 0:640]
  95. img_b = frame[h-640:, 640:1280]
  96. case _:
  97. raise ValueError('mode must be 0, 1, or 2')
  98. if img_a is not None:
  99. cv2.imwrite(str(save_path / f'{datetime_now}_{index_frame:05d}a.png'), img_a)
  100. if img_b is not None:
  101. cv2.imwrite(str(save_path / f'{datetime_now}_{index_frame:05d}b.png'), img_b)
  102. cap.release()
  103. logger.info(f'{video} done')
  104. if __name__ == '__main__':
  105. VIDEO = r'C:\Users\Ryland\Downloads\202404031513.mp4'
  106. # SAVE_PATH = 'D:/Project/Hyakkiyakou/OnmyojiAutoScript-hyakkiyakou/temp/sources_images'
  107. t = TransformVideo(change_channel=True, interval=0.1)
  108. t.parse_one(VIDEO, mode=2)