OpenCV display window on top with focus

From Noah.org
Revision as of 04:59, 27 March 2019 by Root (talk | contribs) (Created page with "Category: Engineering I found that all I needed to do was set my main window to fullscreen then back to normal. I did not need to open a separate window. I did not need t...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search


I found that all I needed to do was set my main window to fullscreen then back to normal. I did not need to open a separate window. I did not need to display a dummy image. I did not need to call waitKey.

OpenCV2 has a bug where when a window is created it will be created below the terminal window and not have focus. To force focus you need to set the window to fullscreen and then back to normal. Do this right after creating the window and you will get the least amount of screen disruption. You may see the screen flicker black, but that's the unfortunate compromise to get around this bug.

These are the two key instructions to force a window to the top and set focus:

cv2.setWindowProperty(WindowName,cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
cv2.setWindowProperty(WindowName,cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_NORMAL)

This is an example that shows the whole thing working in a program. See what happens if you comment out the two key instructions:

#!/usr/bin/env python
import cv2
import numpy

WindowName="Main View"
view_window = cv2.namedWindow(WindowName,cv2.WINDOW_NORMAL)

# These two lines will force the window to be on top with focus.
cv2.setWindowProperty(WindowName,cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
cv2.setWindowProperty(WindowName,cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_NORMAL)

# The rest of this does not matter. This just shows an image on
# your main view window. This could be the rest of your program.
img = numpy.zeros((400,400,3), numpy.uint8)
for x in range(0,401,100):
    for y in range(0,401,100):
        cv2.line(img,(x,0),(0,y),(128,128,254),1)
        cv2.line(img,(x,399),(0,y),(254,128,128),1)
        cv2.line(img,(399,y),(x,399),(128,254,128),1)
        cv2.line(img,(399,y),(x,0),(254,254,254),1)
cv2.imshow(WindowName, img)
cv2.waitKey(0)
cv2.destroyWindow(WindowName)