绘制一个简单的图像,显示它,然后关闭它



我正在尝试做一些简单的绘图。我想使用 opencv (cv2),因为在第二个项目中,我必须显示一个小动画(矩形,大小取决于变量;每 X 秒更新一次)。但是,我没有图像处理库和opencv的经验。

我遇到了很多问题,其中之一是我不知道如何显示/关闭图像。我正在创建的图像是一个简单的固定十字架,黑色;在浅灰色背景上:

import numpy as np
import cv2
screen_width = 1024
screen_height = 768
img = np.zeros((screen_height, screen_width, 3), np.uint8) # Black image
img = img + 210 # light gray
screen_center = (screen_width//2, screen_height//2)
rect_width = int(0.2*screen_width)
rect_height = int(0.02*screen_height)
xP1 = screen_center[0] - rect_width//2
yP1 = screen_center[1] + rect_height//2
xP2 = screen_center[0] + rect_width//2
yP2 = screen_center[1] - rect_height//2
cv2.rectangle(img, (xP1, yP1), (xP2, yP2), (0, 0, 0), -1)
xP1 = screen_center[0] - rect_height//2
yP1 = screen_center[1] + rect_width//2
xP2 = screen_center[0] + rect_height//2
yP2 = screen_center[1] - rect_width//2
cv2.rectangle(img, (xP1, yP1), (xP2, yP2), (0, 0, 0), -1)

注意:如果有更好的方法来创建它,我也有兴趣:)

我的目标是让第一个项目具有以下代码结构:

img = load_saved_img() # The created fixation cross
display_image()
add_text_to_image('texte to add')
# do stuff
# for several minutes
while something:
do_this()
remove_text_from_image() # Alternatively, go back to the initial image/change the image
# do stuff
# for several minutes
while something:
do_this()
close_image()

我知道我可以用cv2.putText()添加文本,并且我可以通过这种方式创建带有文本的第二个图像。我不知道的是我如何管理不同图像的显示;尤其是在背景上"做事"时以轻量级的方式。大多数人似乎使用不适合cv2.waitKey(),因为我不想有任何用户输入,并且因为它似乎类似于程序基本上暂停的time.sleep()

欢迎任何提示,即使在其他库和实现:)

正如@Miki所提议的,.imshow().waitKey(1)的组合正在发挥作用。

cv2.imshow(window, img)
cv2.waitKey(1)

但是,这些不能与time.sleep()一起使用来暂停程序。有时,显示不会更新。例如,在 3 秒倒计时中:

import time
import cv2
window = 'Name of the window'
def countdown(window, images):
"""
images = [image3, image2, image1]
"""
for img in images:
cv2.imshow(window, img)
cv2.waitKey(1)
time.sleep(1)

有时会跳过其中一个显示器。相反,如果在此期间预计没有键盘输入,则将cv2.waitKey()参数更改为1000(需要计时器)并删除time模块的使用效果最佳。

最新更新