import cv2
videoCapture = cv2.VideoCapture('test.mp4')
cv2.namedWindow('name', cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
while True:
ret, frame = videoCapture.read()
if ret is True:
cv2.imshow('name', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
videoCapture.release()
cv2.destroyAllWindows()
关键是在cv2.imshow
之前设置好窗口的属性cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO
。
PS:我在PyCharm社区版上测试可用,换成专业版就没有保持比例了,可能是专业版调用的后端不是Qt,而是独立出来的窗体。
Qt后端支持标志:
flags == WINDOW_AUTOSIZE | WINDOW_KEEPRATIO |WINDOW_GUI_EXPANDED
cv2.namedWindow源码注释
"""
namedWindow(winname[, flags]) -> None
. @brief Creates a window.
.
. The function namedWindow creates a window that can be used as a placeholder for images and
. trackbars. Created windows are referred to by their names.
.
. If a window with the same name already exists, the function does nothing.
.
. You can call cv::destroyWindow or cv::destroyAllWindows to close the window and de-allocate any associated
. memory usage. For a simple program, you do not really have to call these functions because all the
. resources and windows of the application are closed automatically by the operating system upon exit.
.
. @note
.
. Qt backend supports additional flags:
. - **WINDOW_NORMAL or WINDOW_AUTOSIZE:** WINDOW_NORMAL enables you to resize the
. window, whereas WINDOW_AUTOSIZE adjusts automatically the window size to fit the
. displayed image (see imshow ), and you cannot change the window size manually.
. - **WINDOW_FREERATIO or WINDOW_KEEPRATIO:** WINDOW_FREERATIO adjusts the image
. with no respect to its ratio, whereas WINDOW_KEEPRATIO keeps the image ratio.
. - **WINDOW_GUI_NORMAL or WINDOW_GUI_EXPANDED:** WINDOW_GUI_NORMAL is the old way to draw the window
. without statusbar and toolbar, whereas WINDOW_GUI_EXPANDED is a new enhanced GUI.
. By default, flags == WINDOW_AUTOSIZE | WINDOW_KEEPRATIO | WINDOW_GUI_EXPANDED
.
. @param winname Name of the window in the window caption that may be used as a window identifier.
. @param flags Flags of the window. The supported flags are: (cv::WindowFlags)
"""