stc_vid2frames.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import sys
  2. import os
  3. import numpy as np
  4. import shutil
  5. import argparse
  6. import torch
  7. import torchvision
  8. from tqdm import tqdm
  9. def main():
  10. parser = argparse.ArgumentParser(add_help=True)
  11. parser.add_argument('--dataroot',
  12. default='.',
  13. help='Dataset root directory')
  14. parser.add_argument('--src_vid_path', default='archive/training/videos/',
  15. help='Name of folder where `avi` files exist')
  16. parser.add_argument('--tar_vid_frame_path', default='converted/train',
  17. help='Name of folder to save extracted frames.')
  18. parser.add_argument('--src_npy_path', default='archive/test_pixel_mask/',
  19. help='Name of folder where `npy` frame mask exist')
  20. parser.add_argument('--tar_anno_path', default='converted/pixel_mask',
  21. help='Name of folder to save extracted frame annotation')
  22. parser.add_argument('--extension', default='jpg',
  23. help="File extension format for the output image")
  24. args = parser.parse_args()
  25. src_dir = os.path.join(args.dataroot, args.src_vid_path)
  26. tar_dir = os.path.join(args.dataroot, args.tar_vid_frame_path)
  27. try:
  28. os.makedirs(tar_dir)
  29. except FileExistsError:
  30. print(F'{tar_dir} already exists, remove whole tree and recompose ...')
  31. shutil.rmtree(tar_dir)
  32. os.makedirs(tar_dir)
  33. vid_list = os.listdir(src_dir)
  34. for i, vidname in enumerate(tqdm(vid_list)):
  35. vid = torchvision.io.read_video(os.path.join(src_dir, vidname), pts_unit='sec')[0]
  36. target_folder = os.path.join(tar_dir, vidname[:-4])
  37. try:
  38. os.makedirs(target_folder)
  39. except FileExistsError:
  40. print(F'{target_folder} already exists, remove the directory recompose ...')
  41. shutil.rmtree(target_folder)
  42. os.makedirs(target_folder)
  43. for i, frame in enumerate(vid):
  44. frame = (frame / 255.).permute(2, 0, 1) #HWC2CHW
  45. torchvision.utils.save_image(frame,
  46. F'{target_folder}/{i:03}.{args.extension}')
  47. src_dir = os.path.join(args.dataroot, args.src_npy_path)
  48. tar_dir = os.path.join(args.dataroot, args.tar_anno_path)
  49. try:
  50. os.makedirs(tar_dir)
  51. except FileExistsError:
  52. print(F"{tar_dir} already exists, remove whole tree and recompose ...")
  53. shutil.rmtree(tar_dir)
  54. os.makedirs(tar_dir)
  55. frame_anno = os.listdir(src_dir)
  56. for _f in tqdm(frame_anno):
  57. fn = _f[:-4]
  58. target_folder = os.path.join(tar_dir, fn)
  59. os.makedirs(target_folder)
  60. px_anno = np.load(F"{src_dir}/{fn}.npy").astype(np.float)
  61. for i, px_frame in enumerate(px_anno):
  62. torchvision.utils.save_image(torch.from_numpy(px_frame).unsqueeze(0), # CHW, 1 channel
  63. F"{target_folder}/{i:03}.{args.extension}")
  64. if __name__ == '__main__':
  65. main()