'May I ask how could I detect a circle in video and get the coordinate from it

I have a code like this below which can detect the ball from the picture, but may I ask how could I transform it to detect the video version and get the ball's coordinate at each frame?

import cv2
import numpy as np
img = cv2.imread('maze1.jpg')#讀取圖片
img=cv2.resize(img, (0,0), fx=0.2,fy=0.2)
GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#灰度化
GrayImage= cv2.medianBlur(GrayImage,5)#中值模糊
ret,th1 = cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY
th2 = cv2.adaptiveThreshold(GrayImage,255,cv2.ADAPTIVE_THRESH_MEAN_C,  cv2.THRESH_BINARY,3,5)  


Solution 1:[1]

The way openCV usually works with video is to read each frame, analyse and/or modify the frame, and then display it.

So your approach above can be applied to each individual frame of the video, or to every 'nth' frame if that is good enough for your needs or you have performance issues with your target solution and platform.

If you look at some of the examples in the openCv docs you will see this type of loop - e.g.:

while True:
    //This example is reading a frame from a camera but
    //you cxan read from a file also
    ret, frame = capture.read()
    if frame is None:
        break
    
    //Do your work on the farme here - this example is 
    //applying a mask, in your case you would detect 
    //your object. You can also add a counter and only
    //do the work every 'nth' frame 
    fgMask = backSub.apply(frame)
    
    
    cv.rectangle(frame, (10, 2), (100,20), (255,255,255), -1)
    cv.putText(frame, str(capture.get(cv.CAP_PROP_POS_FRAMES)), (15, 15),
               cv.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,0))
    
    //Now display the modified frame - in your case you 
    //might highlight the detected circle or you could
    //just display it unchnaged
    cv.imshow('Frame', frame)
    cv.imshow('FG Mask', fgMask)
    
    keyboard = cv.waitKey(30)
    if keyboard == 'q' or keyboard == 27:
        break

You can see the full masking example and other examples here: https://docs.opencv.org/3.4/d1/dc5/tutorial_background_subtraction.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mick