Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize the window obtained from cv2.imshow()?

I started learning OpenCV today and I wrote a short code to upload (I don't know, if it's the right term) a random image:

enter image description here

It works fine, and I can open the image, but what I get is a big window and I can't see the full image unless I scroll it:

enter image description here

So, I'd like to know a way that I could see the whole image pretty and fine in a shorter window.

like image 624
Annie Wojciek Avatar asked Oct 17 '25 17:10

Annie Wojciek


2 Answers

The actual "problem" comes from imshow itself, and is the following:

If the window was not created before this function, it is assumed creating a window with cv::WINDOW_AUTOSIZE.

Looking at the corresponding description at the WindowFlags documentation page, we get:

the user cannot resize the window, the size is constrainted by the image displayed.

So, to work around this, you must set up the window manually using namedWindow, and then resize it accordingly using resizeWindow.

Let's see this code snippet:

import cv2

# Read image
image = cv2.imread('path/to/your/image.png')

# Window from plain imshow() command
cv2.imshow('Window from plain imshow()', image)

# Custom window
cv2.namedWindow('custom window', cv2.WINDOW_KEEPRATIO)
cv2.imshow('custom window', image)
cv2.resizeWindow('custom window', 200, 200)

cv2.waitKey(0)
cv2.destroyAllWindows()

An exemplary output would look like this (original image size is [400, 400]):

Output

Using cv2.WINDOW_KEEPRATIO, the image is always fitted to the window, and you can resize the window manually, if you want.

Hope that helps!

like image 186
HansHirse Avatar answered Oct 20 '25 07:10

HansHirse


You can resize the image keeping the aspect ratio same and display it.

#Display image
def display(img, frameName="OpenCV Image"):
    h, w = img.shape[0:2]
    neww = 800
    newh = int(neww*(h/w))
    img = cv2.resize(img, (neww, newh))
    cv2.imshow(frameName, img)
    cv2.waitKey(0)
like image 24
flamelite Avatar answered Oct 20 '25 07:10

flamelite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!