Reputation: 59
I've looked around and can't find a specific answer to my solution and my brain is fried at this point. I'm trying to create an mp4 video based on some .bmp files in a folder. However, I want the files ordered by earliest modified date for the video. So I'm using the oldest date modified. I found some stuff on here about using os.path.getmtime, however if I add that it's telling me it can't find the file. I'm guessing it's because the files are located on a network and not in my local path where python is installed. Here is my code. I've confirmed everything else works, so all I need is to find out how to sort the files.
import cv2
import numpy as np
import os
from os.path import isfile, join
#change this to the path where the pictures are located
pathIn= #MyPathWhichIsOnANetworkNotWherePythonIsInstalled
#input your video name & video type:
vid_name = "FirstCalPics.mp4"
#change this to the path where the video should be saved:
pathSave = #AlsoAPathWhichIsOnANetworkNotWherePythonIsInstalled
#set your fps here:
fps = 10
pathOut = pathSave + vid_name
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#Sort files based on date modified:
files.sort(key=os.path.getmtime) #<--- HERE'S THE ISSUE
for i in range(len(files)):
filename=pathIn + "\\" + files[i]
#reading each files
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
#inserting the frames into an image array
frame_array.append(img)
out = cv2.VideoWriter(pathOut, fourcc, fps, size)
for i in range(len(frame_array)):
# writing to a image array
out.write(frame_array[i])
out.release()
Upvotes: 2
Views: 5793
Reputation: 4799
The reason why it says it doesn't show up as a file when you try to use just os.path.getmtime
is because you're checking just path
, when you also have a directory: pathIn
.
You can either use join
when sorting:
files.sort(key=lambda f: os.path.getmtime(join(pathIn, f)))
Or, (and the syntax depends on your version of Python) you can directly store the full file path initially:
files = [fullPath for path in os.listdir(pathIn) if isfile((fullPath := join(pathIn, f)))]
This alleviates the need for filename=pathIn + "\\" + files[i]
later on in your code.
Upvotes: 3