Reputation: 43
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:
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:
So, I'd like to know a way that I could see the whole image pretty and fine in a shorter window.
Upvotes: 4
Views: 17016
Reputation: 2003
When cv2.imshow()
creates a new window, it passes the flag cv::WINDOW_AUTOSIZE
, preventing resize.
To resize an already existent window, you have to disable this flag:
import cv2
import numpy as np
if __name__ == '__main__':
cv2.imshow('image', np.ones((128, 128, 3)))
cv2.setWindowProperty('image', 1, cv2.WINDOW_NORMAL)
cv2.waitKey()
cv2.resizeWindow('image', 512, 512)
cv2.waitKey()
exit()
Upvotes: 2
Reputation: 18925
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]
):
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!
Upvotes: 18
Reputation: 2854
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)
Upvotes: 4