I"每当按下某个键时,我都试图改变在实时摄像机馈送的输出帧上绘制的圆圈的颜色。当我按下"c"键时,我希望圆圈的颜色从蓝色变为绿色。我正在尝试以下方法来实现
# import the opencv library
import cv2
global circle_color
circle_color = (255,0,0)
# define a video capture object
vid = cv2.VideoCapture(0)
while(True):
# Capture the video frame
# by frame
ret, frame = vid.read()
cv2.circle(img=frame, center = (250,250), radius =100, color =circle_color, thickness=-1)
# Display the resulting frame
cv2.imshow('frame', frame)
# the 'q' button is set as the
# quitting button you may use any
# desired button of your choice
if cv2.waitKey(1) & 0xFF == ord('q'):
break
elif cv2.waitKey(1) & 0xFF == ord('c'):
# circle_color == (0,255,0)
cv2.circle(img=frame, center = (250,250), radius =100, color =(0,255,0), thickness=-1)
print("pressed c")
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
当我尝试这个代码并按下"c"键时,我只看到控制台输出为按下c,但我没有看到输出框窗口上的圆圈颜色有任何变化,它保持蓝色。
我甚至试着声明全局颜色变量,并在按键时更新它,但效果不佳
如有任何帮助或建议,我们将不胜感激。
主要问题是在显示图像之前,您的绿色圆圈总是被蓝色圆圈覆盖。
将cv2.imshow('frame', frame)
移动到while循环的末尾。
我会这样做:
# import the opencv library
import cv2
key_pressed = False
# define a video capture object
vid = cv2.VideoCapture(0)
while(True):
# Capture the video frame
# by frame
ret, frame = vid.read()
circle_color = (0, 255, 0) if key_pressed else (255, 0, 0)
cv2.circle(img=frame, center = (250,250), radius =100, color = circle_color, thickness=-1)
# the 'q' button is set as the
# quitting button you may use any
# desired button of your choice
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
elif key & 0xFF == ord('c'):
# circle_color == (0,255,0)
key_pressed = True
print("pressed c")
else:
key_pressed = False
# Display the resulting frame
cv2.imshow('frame', frame)
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
如果你想在按下按键后仍然保持颜色,你应该覆盖circle_color:
# import the opencv library
import cv2
# define a video capture object
vid = cv2.VideoCapture(0)
circle_color = (255, 0, 0)
while(True):
# Capture the video frame
# by frame
ret, frame = vid.read()
cv2.circle(img=frame, center = (250,250), radius =100, color = circle_color, thickness=-1)
# the 'q' button is set as the
# quitting button you may use any
# desired button of your choice
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
elif key & 0xFF == ord('c'):
circle_color = (0, 255, 0)
print("pressed c")
# Display the resulting frame
cv2.imshow('frame', frame)
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()