給opencv函式寫乙個python裝飾器

2021-10-18 18:30:00 字數 1475 閱讀 7731

今天,在python下找到了乙個類似的工具,叫pyimagewatch. 雖然沒有完全理解其使用,但其思路可以參考一下:實現相關功能的方式就是給相應的opencv函式寫乙個裝飾器。比如想檢視乙個opencv函式的執行結果(watcher功能),實現所用的**如下:

class checker:

"""checker for opencv functions."""

def __init__(self, cv_function_name: str):

"""checker for opencv functions."""

cv.namedwindow(cv_function_name)

self.cv_function_name = cv_function_name

self.cv_function = getattr(cv, cv_function_name)

def start(self, decorator):

"""starts checking the opencv function."""

setattr(cv, self.cv_function_name, decorator())

def stop(self):

"""stops checking the opencv function."""

setattr(cv, self.cv_function_name, self.cv_function)

class watcher(checker):

"""watcher for opencv functions."""

def watch(self):

"""decorator to watch an opencv function."""

@wraps(self.cv_function)

result = self.cv_function(*args, **kwargs)

cv.imshow(self.cv_function_name, result)

cv.waitkey()

return result

def start(self):

"""starts watching the opencv function."""

super().start(self.watch)

其中checker是基類,watcher是派生類。checker建構函式需要傳入乙個opencv函式名,checker.start函式將opencv函式與相應的裝飾器函式繫結;裝飾器函式是由watcher.watch函式生成的。可以看到watcher.watch是乙個典型的裝飾器函式,其功能是除了執行原有的opencv函式之外,還對函式結果進行了顯示cv.imshow(self.cv_function_name, result)這體現了裝飾器函式的核心:得到乙個增強函式,替換原有函式,並保持一樣的名字。python裝飾器的知識可以參考:

寫乙個記憶體拷貝函式

include using namespace std void mymemcpy void out pdst,void in psrc,int in ilen if pdest psrc pdest cout the dest point is large than src else cout t...

寫乙個函式,實現strstr

要求 寫乙個函式,實現strstr,即從乙個字串中查詢另乙個字串的位置,如 strstr 12345 34 返回值為2,在2號位置找到字串34。include include include using namespace std int strstr char str,char str1 else...

python寫乙個服務 Python寫乙個服務

coding utf 8 import json from urllib.parse import parse qs from wsgiref.server import make server 定義函式,引數是函式的兩個引數,都是python本身定義的,預設就行了。定義檔案請求的型別和當前請求成功...