问题
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:
1
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:
2
So, I'd like to know a way that I could see the whole image pretty and fine in a shorter window.
回答1:
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)
回答2:
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!
来源:https://stackoverflow.com/questions/58405119/how-to-resize-the-window-obtained-from-cv2-imshow