I have a folder which is being written continuously with files (from a Raspberry Pi). I want to run a Python code which will read files (and process them) from the same folder. I start the Python code after say 5 files have been written into the folder. But then the code stops after it has processed 5 files. Any suggestions as to how to "stream" the files from this dynamically updated folder into my Python code?
Thanks
I am using the following code and was wondering if there is another solution:
import os
import time
import numpy as np
from PIL import Image
import datetime
# get the data & time of an image output is str with format '%Y:%m:%d
%H:%M:%S'
def get_date_taken(path):
return Image.open(path)._getexif()[36867]
# get the difference in time between two images in seconds
def getTimeDiffBetwImages(path1,path2):
a1 = get_date_taken(path1)
a2 = get_date_taken(path2)
b1 = datetime.datetime.strptime(a1,'%Y:%m:%d %H:%M:%S')
b2 = datetime.datetime.strptime(a2,'%Y:%m:%d %H:%M:%S')
return (b1-b2).total_seconds()
def getDiffImgs(img1,img2):
a = img1.shape
diff = np.zeros((a[0],a[1],a[2]),dtype = "uint8")
for i in range(0,a[0]):
for j in range(0,a[1]):
for k in range(0,a[2]):
diff[i,j,k] = abs(int(img2[i,j,k]) - int(img1[i,j,k]))
return diff
folder = "D:/work"
file_num = 0
img_prev = []
last_file = None
while True:
for f in os.listdir(folder):
path1 = os.path.join(folder,f)
if not(last_file == None):
path2 = os.path.join(folder,last_file)
time_diff = getTimeDiffBetwImages(path1,path2)
else:
time_diff = 0
if time_diff >= 0:
print(f)
im = cv2.imread(os.path.join(folder,f))
img_curr = np.copy(im)
fname = "Diff_" + f
if file_num > 0:
diff = getDiffImgs(img_prev,img_curr)
cv2.imwrite(fname,diff)
img_prev = np.copy(img_curr)
file_num += 1
time.sleep(10) # additional processing but just delay out here
last_file = f