【OpenCV】python pyinotify video player 利用 OpenCV + inotify 製作即時影片播放器 sample code (內含範例程式碼)

前言

inotify 能幫助我們偵測某個資料夾出現的檔案,
搭配上 OpenCV,我們就能製作出即時影片播放器。

關於 inotify 基礎概念

inotify 是取用 linux 底下的系統自動監聽檔案變化的方式,
pyinotify 就是他的 python 版本實作,
當我們獲得了系統給的 event,我們會得到該檔案的「絕對路徑」,
我們就能再進一步依照此絕對路徑做對應的資料操作。

注意:inotify的功能目前只在 linux 系統能使用,mac 上不能使用哦~ (自己親自測試過QQ)

關於 inotify,可以參考這幾篇文章:

相關參數

  • WATCH_FOLDER_0 = 圖片會出現的位置
  • time.sleep(0.005): 為保險起見,我們 delay 0.005 秒, 防止圖片未完整複製的問題。
  • sample code

    import pyinotify
    import os
    import cv2
    import time
    
    WATCH_FOLDER_0 = './oriimage/'
    
    
    def show_screen(path):
        time.sleep(0.005)
        img = cv2.imread(path)
    
        print(img.shape)
    
        shape = img.shape
        # shape = (int(shape[1]/2), int(shape[0]/2))
        shape = (int(shape[1]), int(shape[0]))
        img = cv2.resize(img, shape, interpolation=cv2.INTER_CUBIC)
    
        # -------------------- show screen -------------------- #
    
        cv2.namedWindow('rtsp', cv2.WINDOW_NORMAL)
        cv2.resizeWindow('rtsp', shape[0], shape[1])
        cv2.imshow('rtsp', img)
        cv2.waitKey(1)
    
        # os.remove(path)
    
    
    class MyEventHandler(pyinotify.ProcessEvent):
        def process_IN_CREATE(self, event):
            print("CREATE event:", event.pathname)
            path = event.pathname
            if path.endswith(".jpg"):
                show_screen(path)
    
    
    def main():
        pyinotify_flags = pyinotify.IN_CREATE
    
        # watch manager
        wm = pyinotify.WatchManager()
        wm.add_watch(WATCH_FOLDER_0, pyinotify_flags, rec=False)
    
        # event handler
        eh = MyEventHandler()
    
        # notifier
        notifier = pyinotify.Notifier(wm, eh)
        notifier.loop()
    
    
    if __name__ == '__main__':
        main()