2014-05-07 55 views
3

我正在使用看門狗庫來檢測何時在特定文件夾中創建新圖像。當看門狗檢測到新創建的圖像時,我使用SimpleCV/OpenCV啓動一些圖像處理功能。在Python中使用看門狗處理圖像

但是,照片是從Raspberry Pi相機拍攝的,並且從下面的錯誤中我不相信整個圖像會在第一次出現在目錄中時被保存。 (基本上文件被保存爲「碎片」或多種形式)。

請注意,當我複製粘貼&的圖像到相應的文件夾,腳本運行成功。

問:只有在整個文件被保存後,纔有辦法啓動圖像處理嗎?

import time 
from SimpleCV import Image 
from watchdog.observers import Observer 
from watchdog.events import FileSystemEventHandler 

class ExampleHandler(FileSystemEventHandler): 
    def on_created(self, event): 
     image = Image(event.src_path) 
     do image processing stuff 
     print "Got event for file %s" % event.src_path 

observer = Observer() 
event_handler = ExampleHandler() # create event handler 
observer.schedule(event_handler, path='/path/to/images') # set observer to use created handler in directory 
observer.start() 

# sleep until keyboard interrupt, then stop + rejoin the observer 
try: 
    while True: 
     time.sleep(1) 
except KeyboardInterrupt: 
    observer.stop() 

observer.join() 

錯誤轉儲:

Exception in thread Thread-1: 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner 
    self.run() 
    File "/usr/local/lib/python2.7/dist-packages/watchdog/observers/api.py", line 241, in run 
    self.dispatch_events(self.event_queue, self.timeout) 
    File "/usr/local/lib/python2.7/dist-packages/watchdog/observers/api.py", line 408, in dispatch_events 
    self._dispatch_event(event, watch) 
    File "/usr/local/lib/python2.7/dist-packages/watchdog/observers/api.py", line 403, in _dispatch_event 
    handler.dispatch(event) 
    File "/usr/local/lib/python2.7/dist-packages/watchdog/events.py", line 361, in dispatch 
    _method_map[event_type](event) 
    File "picture_classifier_cube.py", line 11, in on_created 
    image = Image(event.src_path) 
    File "/usr/local/lib/python2.7/dist-packages/SimpleCV/ImageClass.py", line 1073, in __init__ 
    self._pil = pil.open(self.filename).convert("RGB") 
    File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1980, in open 
    raise IOError("cannot identify image file") 
IOError: cannot identify image file 

編輯更新處理器識別新的文件後,睡了幾秒鐘後,我收到了不同的錯誤。

class ExampleHandler(FileSystemEventHandler): 
    def on_created(self, event): 
     time.sleep(3) 
     cans = Image(event.src_path) 

錯誤

IOError: [Errno 2] No such file or directory: '/path/to/images/test.jpg~' 

注意,我捕捉與下面的皮命令的圖像:raspistill -o 'test.jpg'

+0

做到這一點或者,你可以只是做一個try/catch ...如果你不關心其他錯誤。 –

回答

1

雖然有可能不知道某些如果一種方法文件完成寫入而不修改寫入的程序,您可以監視文件大小:

from os import stat 
from time import sleep 

def wait_for_write_finish(filename): 
    last_size, size= -1, 0 
    while size!=last_size: 
     sleep(1) 
     last_size, size= size, stat(filename).st_size 

您可能需要與合適的線程