parse_video_rgb.m 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. function parse_video_rgb()
  2. %
  3. % Parsing video (*.mp4/*.avi) file(s) into image (*.jpg) files
  4. % Written by Hio-Been Han, 2023-08-23
  5. %
  6. %% (1) Get file info & set save directory
  7. % [file_list, vid_directory] = uigetfile('*.*','MultiSelect','on');
  8. vid_directory_single = './data_BIDS/stimuli/video/Single/';
  9. vid_directory_group = './data_BIDS/stimuli/video/Group/';
  10. if ~isdir('./data_BIDS/stimuli/video_parsed'), mkdir('./data_BIDS/stimuli/video_parsed'); end
  11. write_directory_single = './data_BIDS/stimuli/video_parsed/Single/';
  12. write_directory_group = './data_BIDS/stimuli/video_parsed/Group/';
  13. if ~isdir(write_directory_single), mkdir(write_directory_single); end
  14. if ~isdir(write_directory_group), mkdir(write_directory_group); end
  15. file_counter = 1;
  16. file_list = cell([3,64+8]);
  17. % Single
  18. for mouse = 1:8
  19. for day = 1:2
  20. for trial = 1:4
  21. file_list{1,file_counter} = vid_directory_single;
  22. file_list{2,file_counter} = sprintf('Day%d-Trial%d-Mouse%d.avi',day,trial,mouse);
  23. file_list{3,file_counter} = write_directory_single;
  24. file_counter = file_counter + 1;
  25. end
  26. end
  27. end
  28. % Group
  29. for day = 1:2
  30. for trial = 1:4
  31. file_list{1,file_counter} = vid_directory_group;
  32. file_list{2,file_counter} = sprintf('Day%d-Trial%d-Group.avi',day,trial);
  33. file_list{3,file_counter} = write_directory_group;
  34. file_counter = file_counter + 1;
  35. end
  36. end
  37. %% (2) Parse & save video into JPEG files
  38. save_format = '.jpg';
  39. for fileIdx = 1:length(file_list)
  40. % Set save directory
  41. vid_directory = file_list{1,fileIdx};
  42. fname = file_list{2,fileIdx};
  43. img_directory = file_list{3,fileIdx};
  44. uniqname = fname(1:end-4);
  45. vidname = [vid_directory fname];
  46. save_directory = [img_directory uniqname '/'];
  47. if ~isdir(save_directory), mkdir(save_directory); end
  48. % Read frames
  49. v = VideoReader( [ vidname ]);
  50. nFrames = v.Duration * v.FrameRate;
  51. for frameIdx = 1:7200
  52. if v.hasFrame
  53. frame = v.readFrame();
  54. % Save frame
  55. imgname_write = [num2str(sprintf('frame-%06d',frameIdx))...
  56. '-' uniqname save_format];
  57. imwrite(frame , [ save_directory imgname_write ] )
  58. end
  59. end
  60. end