在终端或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()
你缺少一个导入。
import numpy as np
另外,当在指定的延迟时间内(在你的例子中是2ms)没有按键时,waitkey返回-1。所以 cv2.waitKey(2)
调用评估到一个真值,并且 break
是执行。将其改为
if cv2.waitKey(2) == ord("q"):
break
只有当你按下按键时,才会停止循环。q
我还注意到,右键会先打开一个上下文菜单。下面是解决方法的链接。为什么在我的OpenCV imshow()窗口中右击会打开一个下拉菜单?