首页 > 解决方案 > 无法在 Python 中使用 namedWindow 绘制图像

问题描述

在终端或 Spyder 中运行我的代码时会打开一个图像。但是左键或右键都没有动作。这是我写的代码:

import cv2
import matplotlib.pyplot as plt

def drawCircle(event,x,y,flags,param):

    if event == cv2.EVENT_LBUTTONDOWN: #(If Left button of mouse clicked)
        cv2.circle(img,(x,y),radius = 100, color =(255,0,0),thickness=-1)
    if event == cv2.EVENT_RBUTTONDOWN: #(If Right button of mouse clicked)
        cv2.circle(img,(x,y),radius = 100, color =(0,255,0),thickness=-1)

img= np.zeros(shape=(512,512,3),dtype=np.int8)
cv2.namedWindow("someimage")

cv2.setMouseCallback("someimage", drawCircle)

while True:
    cv2.imshow("someimage",img)
    if cv2.waitKey(2):
        break

cv2.destroyAllWindows()

标签: pythonopencv

解决方案


您缺少导入:

import numpy as np

此外,当在指定的延迟(在您的情况下为 2 毫秒)内没有按下任何键时,waitkey 返回-1。所以cv2.waitKey(2)call 评估为一个真实的值并被break执行。将其更改为

if cv2.waitKey(2) == ord("q"):
    break

这只会在您按下键时停止循环q

我还注意到右键单击将首先打开一个上下文菜单。这是解决方案的链接:
为什么右键单击会在我的 OpenCV imshow() 窗口中打开下拉菜单?


推荐阅读