如果你想在一个while循环中保持窗口的固定大小,你可以在while循环外面调用cv2.namedWindow()和cv2.resizeWindow()函数,确保窗口的设置只发生一次。然后在循环中使用cv2.imshow()显示图像即可。
import cv2
# 读取图像
image = cv2.imread("image.jpg")
# 创建窗口并设置大小
cv2.namedWindow("Window Name", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Window Name", 800, 600)
# 进入主循环
while True:
# 在窗口上显示图像
cv2.imshow("Window Name", image)
# 检测键盘输入,如果按下 ESC 键则退出循环
key = cv2.waitKey(1) & 0xFF
if key == 27: # ASCII码中 ESC 键的值为27
break
# 关闭窗口
cv2.destroyAllWindows()