我有一个文件夹,这是正在不断写入文件(从树莓皮)。我想运行一个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
如果在添加5个文件时正在读取文件夹。它可能只记录这五个文件。添加的任何新文件都不会反映出来。我认为一个好的解决方案是将一组文件添加到目录中。在处理集合中的文件时,如果出现最后一个文件,则可以再次检查目录中的任何新文件,并将它们添加到该集合中。保持这个循环直到你的首选条件不满足。你知道吗
希望对你有帮助。谢谢。你知道吗
相关问题 更多 >
编程相关推荐