OpenCV Python - 在网络摄像头视频源中的随机位置绘制圆圈

OpenCV Python - Draw circle at random position in webcam video feed

我有以下代码:

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()

我的目标是每次 运行 程序时都在随机位置显示圆圈。但是,使用当前代码,圆在整个屏幕上跳跃,在每一帧的随机位置绘制。我如何修改这段代码,使圆圈以随机宽度和高度绘制并保持在该位置直到我退出程序?

您在每次迭代中都在重新计算坐标,这就是圆不断移动的原因。您只想计算 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()