jjzjj

python - 看门狗和 matplotlib : Processing an image and displaying results when a new file comes in directory

coder 2023-08-15 原文

我正在尝试创建一个简单的应用程序,其中

  1. 图像被推送到目录中(由外部进程)

  2. Python 看门狗触发,图像由函数处理,结果显示在窗口中

作业持续运行,当图像进入目录时触发处理功能。结果的绘图窗口应该只用新结果更新,而不是关闭窗口然后重新绘图。

下面的代码不显示结果。绘图窗口保持空白然后崩溃。如果 matplotlib 以外的东西可以轻松完成这项工作,那也很好。

# plt is matplotlib.pyplot

def process_and_plot(test_file):
    y, x = getresults(test_file) # function which returns results on image file

    y_pos = range(len(y))
    plt.figure(num=1,figsize=(20,10))
    plt.bar(y_pos, y, align='center')
    plt.xticks(y_pos, x)
    plt.show()

# to trigger the proess_and_plt function when a new file comes in directory 

class ExampleHandler(FileSystemEventHandler):
    def on_created(self, event): 
        print event.src_path
        process_and_plot(event.src_path)

event_handler = ExampleHandler() 
observer.schedule(event_handler, path='path/to/directory')
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

最佳答案

为了让您的代码正常工作,我唯一需要做的就是将 plt.show() 替换为 plt.pause(.001),这是非在暂停之前阻塞并更新和显示图形(参见 docs )。

关于 SO 的最佳相关答案似乎是 this .有一些建议使用 plt.show(False)plt.ion() 使 plt.show() 成为非阻塞; Matplotlib 2.2.4 都不适合我。

这里是完整的代码,因为问题中的代码遗漏了几行:

import matplotlib.pyplot as plt, time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

def process_and_plot(test_file):
    #y, x = getresults(test_file) # function which returns results on image file
    y, x = [2, 4, 3], [0, 1, 2]

    y_pos = range(len(y))
    plt.figure(num=1,figsize=(20,10))
    plt.title(test_file)
    plt.bar(y_pos, y, align='center')
    plt.xticks(y_pos, x)
    plt.pause(.001)

# to trigger the proess_and_plt function when a new file comes in directory 

class ExampleHandler(FileSystemEventHandler):
    def on_created(self, event):
        print event.src_path
        process_and_plot(event.src_path)

event_handler = ExampleHandler()
observer = Observer()
observer.schedule(event_handler, path='/path/to/directory')
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

关于python - 看门狗和 matplotlib : Processing an image and displaying results when a new file comes in directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55804259/

有关python - 看门狗和 matplotlib : Processing an image and displaying results when a new file comes in directory的更多相关文章

随机推荐