我有以下代碼:
import cv2
from random import randrange
cap = cv2.VideoCapture(0) #record webcam
while True:
ret, frame = cap.read() #get feed from webcam
h, w = frame.shape[:2] #height, width
randomWidth = randrange(30,w-30)
randomHeight = randrange(70,h-30)
coordinates = (randomWidth, randomHeight)
circle = cv2.circle(frame, coordinates, 30, (0,0,255), -1) #circle
cv2.imshow('webcam', frame) #show webcam
if cv2.waitKey(1) == ord('q'): #press 'q' to close
break
cap.release()
cv2.destroyAllWindows()
我的目標是每次運行程式時在隨機位置顯示圓圈。然而,使用當前的代碼,圓圈在整個螢屏上跳躍,每一幀都在隨機位置繪制。如何修改此代碼,以便以隨機寬度和高度繪制圓并保持在該位置,直到我退出程式?
uj5u.com熱心網友回復:
您正在每次迭代中重新計算坐標,這就是圓不斷移動的原因。您只想計算coordinates一次,然后繼續使用該值。這是一種方法:
import cv2
from random import randrange
cap = cv2.VideoCapture(0) #record webcam
ret, frame = cap.read() #get feed from webcam
h, w = frame.shape[:2] #height, width
randomWidth = randrange(30, w-30)
randomHeight = randrange(70, h-30)
coordinates = (randomWidth, randomHeight)
while True:
ret, frame = cap.read() #get feed from webcam
circle = cv2.circle(frame, coordinates, 30, (0,0,255), -1) #circle
cv2.imshow('webcam', frame) #show webcam
if cv2.waitKey(1) == ord('q'): #press 'q' to close
break
cap.release()
cv2.destroyAllWindows()
在frame一次回圈之前,用來獲得隨機坐標,然后繼續回圈更新與圈處于固定坐標框架被取出。
如果您的要求可能涉及更改frame.shape或在某些情況下可能需要在回圈中重新計算坐標,則使用如下條件可以更靈活,因為coordinates is None可以替換為不同的條件:
import cv2
from random import randrange
cap = cv2.VideoCapture(0) #record webcam
coordinates = None
while True:
ret, frame = cap.read() #get feed from webcam
if coordinates is None:
h, w = frame.shape[:2] #height, width
randomWidth = randrange(30, w-30)
randomHeight = randrange(70, h-30)
coordinates = (randomWidth, randomHeight)
circle = cv2.circle(frame, coordinates, 30, (0,0,255), -1) #circle
cv2.imshow('webcam', frame) #show webcam
if cv2.waitKey(1) == ord('q'): #press 'q' to close
break
cap.release()
cv2.destroyAllWindows()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403279.html
標籤:
