问题描述
我正在尝试创建一个全屏 opencv 窗口(大小为 1920x1080),它应该在 opencv 窗口的中间位置显示图像(620x365)。不幸的是,图像也被扩展到全屏。这怎么可能?需要设置哪些属性?我使用的是 opencv 2.4.12 版。
mvn scoverage:report
当我使用下面的例子时,我得到一个全屏的 opencv 窗口和一个真实大小的图像,但在窗口的左上角而不是中间位置。
import cv2
imgwindow = 'show my image'
image = cv2.imread('./myimage.jpg')
cv2.namedWindow(imgwindow,cv2.WINDOW_norMAL)
cv2.setwindowProperty(imgwindow,cv2.WND_PROP_FULLSCREEN,cv2.cv.CV_CAP_PROP_FORMAT)
cv2.imshow(imgwindow,image)
cv2.waitKey(0)
cv2.destroyAllWindows()
这是当窗口全屏但图像也扩展到全屏时的示例图片:
这就是我正在寻找的情况:全屏窗口和放置在中间的真实大小的图像:
解决方法
如果您只使用 cv2.imshow 而没有先使用 cv2.namedWindow 声明它,则 OpenCV 以原始大小加载图像。
因此,通过跳过 cv2.namedWindow,您可以实现以原始大小加载图像的目标。从那里您可以使用 cv2.moveWindow 移动窗口。您所需要做的就是计算要加载的位置。以下代码中的公式:
import cv2
import ctypes
# Get the window size and calculate the center
user32 = ctypes.windll.user32
win_x,win_y = [user32.GetSystemMetrics(0),user32.GetSystemMetrics(1)]
win_cnt_x,win_cnt_y = [user32.GetSystemMetrics(0)/2,user32.GetSystemMetrics(1)/2]
# load image
imgwindow = 'show my image'
image = cv2.imread('./myimage.jpg')
# Get the image size information
off_height,off_width = image.shape[:2]
off_height /= 2
off_width /= 2
# Show image and move it to center location
image = cv2.resize(image,(win_x,win_y))
cv2.imshow(imgwindow,image)
cv2.moveWindow(imgwindow,0)
cv2.waitKey(0)
cv2.destroyAllWindows()