我有一个正在与文件连续写入的文件夹(来自Raspberry Pi)。我想运行一个Python代码,该代码将从同一文件夹中读取文件(并对其进行处理)。在将5个文件写入文件夹后,我启动了Python代码。但是然后代码在处理了5个文件后停止。关于如何将文件从此动态更新的文件夹“流化”到我的Python代码中的任何建议?
谢谢
我正在使用以下代码,想知道是否还有其他解决方案:
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
答案 0 :(得分:0)
如果在添加5个文件时正在读取文件夹。它可能只保留这五个文件的日志。添加的任何新文件都不会反映出来。我认为一个好的解决方案是将要添加到目录中的文件的set()作为主要内容。在处理文件集中的文件时,如果最后一个文件到来,则可以再次检查目录中是否有任何新文件,并将它们添加到该文件集中。保持循环直到不满足您的首选条件。
我希望它会有所帮助。谢谢。