每當按下某個鍵時,我都會嘗試更改在實時攝像機源的輸出幀上繪制的圓圈的顏色。當我按下“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,但我沒有看到輸出框架視窗上的圓圈顏色有任何變化,它保持藍色。
我什至嘗試宣告顏色的全域變數并在按下鍵時對其進行更新,但效果不佳
任何幫助或實作這一目標的建議將不勝感激。
uj5u.com熱心網友回復:
主要問題是在顯示影像之前,您的綠色圓圈始終被藍色圓圈覆寫。
將 移動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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452766.html
