DEV Community

codemee
codemee

Posted on • Edited on

OpenCV 的 waitKey() 與 0xFF

使用過 OpenCV 的人想必都寫過類似以下的程式:

>>> cap = cv2.VideoCapture(0)
>>>
>>> while True:
...     ret, f = cap.read()
...     cv2.imshow('hello', f)
...     k = cv2.waitKey(1) & 0xFF
...     print(k)
...     if k == ord('q'):
...         break
Enter fullscreen mode Exit fullscreen mode

大部分的教學都告訴你要在叫用 waitKey() 後與 0xFF 做 & 運算, 把高位元內容清掉, 只留下最低一個位元組的按鍵碼。這是因為過去 waitKey() 傳回值中除了最低位元組的 ASCII 碼以外, 在高位元可能會包含有像是 Ctrl 等其他按鍵的旗標, 因此必須將高位元清除。不過在 OpenCV 3.2 之後, waitKey() 預設就會幫你清除高位元資料, 只留下最低一個位元組, 這可從原始碼中看到:

int cv::waitKey(int delay)
{
    CV_TRACE_FUNCTION();
    int code = waitKeyEx(delay);
#ifndef WINRT
    static int use_legacy = -1;
    if (use_legacy < 0)
    {
        use_legacy = getenv("OpenCV_LEGACY_WAITKEY") != NULL ? 1 : 0;
    }
    if (use_legacy > 0)
        return code;
#endif
    return (code != -1) ? (code & 0xff) : -1;
}
Enter fullscreen mode Exit fullscreen mode

所以其實現在叫用 waitKey() 已經不需要將傳回值與 0xFF 做 & 運算了。如果你還是想要原本的 waitKey(), 可以改用在原始碼裡面看到的 waitKeyEx(), 它傳回的就是沒有經過 & 運算的值。

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay