Stefan Rickli
Stefan Rickli

Reputation: 153

OpenCV imshow window too large - blurred image

In OpenCV-Python when I create a namedWindow using cv2.resizeWindow with the dimensions of the image that I want to display, the window doesn't get resized properly.

import numpy as np
import cv2

window_title = 'image'

img = cv2.imread('test.jpg', cv2.IMREAD_COLOR)
height, width = img.shape[:-1]

cv2.namedWindow(window_title, cv2.WINDOW_NORMAL)
cv2.resizeWindow(window_title, width, height)
cv2.imshow(window_title, img)
cv2.waitKey(0)
cv2.destroyAllWindows()

See the attached screenshot to see the results.

test.jpg is part of a screenshot of the VS Code window, 800x600 pixels. The image window clearly is too large after the resize.

How can I easily resize the window to the correct size such that the displayed image doesn't get blurred?

I'm using Python 3.7.2, OpenCV 3.4.2, Windows 10 64-bit.

Upvotes: 1

Views: 1990

Answers (1)

Stefan Rickli
Stefan Rickli

Reputation: 153

DanMašek correctly noticed the 125% scaling of the OpenCV window compared to the original image size, which lead me to the solution.

This behavior is a result of the UI Scaling feature of more recent versions of Windows. (Have a look under "Settings\System\Display\Scaling")

Since OpenCV doesn't mark its GUI windows as "DPI Aware", Windows scales them to whichever percentage the user has specified.

(Another side effect is that win32gui.GetWindowRect() returns seemingly incorrect coordinates as described here)


Workaround

Go to python.exe's path, right-click the executable, choose 'Properties' and under the tab 'Compatibility' hit 'Change high DPI settings'. Then activate 'Override high DPI scaling behavior', set 'Scaling performed by' to 'Application'.

This will change the behavior for all sessions that this python.exe serves, though. One could use virtual environments to overcome this limitation.


Solution

This SO article describes how one can set the scaling behavior on a per-session level within the Python code.

Upvotes: 2

Related Questions