cv2窗口大小可调整并保持比例

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后端支持标志:

  • WINDOW_NORMAL或WINDOW_AUTOSIZE
    WINDOW_NORMAL使您可以调整大小窗口,而WINDOW_AUTOSIZE自动调整窗口大小以适应显示图像(参见imshow),您无法手动更改窗口大小。
  • WINDOW_FREERATIO或WINDOW_KEEPRATIO
    WINDOW_FREERATIO调整图像不考虑其比例,而WINDOW_KEEPRATIO保持图像比例。
  • WINDOW_GUI_NORMAL或WINDOW_GUI_EXPANDED
    WINDOW_GUI_NORMAL是绘制窗口的旧方法没有状态栏和工具栏,而WINDOW_GUI_EXPANDED是一个新的增强GUI。
    默认情况下,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)
    """

你可能感兴趣的:(Python,OpenCV)