DEV Community

parmarjatin4911@gmail.com
parmarjatin4911@gmail.com

Posted on

Ant Motion Tracking with Python and OpenCV!

🔍 Explore the mesmerizing world of Ant Motion Tracking using Python and OpenCV! 🐜💻 Uncover the secrets of precise motion detection with our easy-to-follow tutorial. Subscribe for more coding insights and stay at the forefront of tech innovation! 🚀📈

Implementation code

Now, let's dive into the implementation. Ant Motion Tracking implementation using Python and the OpenCV library. This assumes that you have prior knowledge of setting up Python and installing the necessary libraries.:

CODE

import cv2
import numpy as np

Initialize video capture

cap = cv2.VideoCapture('ant.mov') # Replace with your video file

Create background subtractor

fgbg = cv2.createBackgroundSubtractorMOG2()

Create an empty list to store the ant positions

ant_positions = []

while True:
ret, frame = cap.read()
if not ret:
break

Apply background subtraction

fgmask = fgbg.apply(frame)

Remove noise using morphological operations

kernel = np.ones((5, 5), np.uint8)
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel)

Find contours in the binary mask

contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

Draw bounding boxes and circles around moving objects (ants)

for contour in contours:
if cv2.contourArea(contour) > 500: # Adjust the area threshold as needed
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

Calculate the centroid of the bounding box

cx, cy = x + w // 2, y + h // 2

Draw a circle at the centroid

cv2.circle(frame, (cx, cy), 10, (0, 0, 255), -1)

Save the ant position

ant_positions.append((cx, cy))

Display the original video and the processed video

cv2.imshow('Original Video', frame)
cv2.imshow('Foreground Mask', fgmask)

if cv2.waitKey(30) & 0xFF == 27: # Press 'Esc' to exit
break

cap.release()
cv2.destroyAllWindows()

Save the above script as a Python file (e.g., streamlit run app.py ) and run it on your os system . The script upload iamge from the machine, performs analyze images , and displays the live feedback.

Conclusion

In conclusion, this Python and OpenCV implementation showcases a simple yet effective Ant Motion Tracking system. By leveraging computer vision techniques, we've created a program that detects motion, making it a versatile tool for various applications. This project serves as a foundation for further exploration and customization, empowering developers to delve into the exciting realm of computer vision and real-time object tracking. Happy coding! 🚀🐜💻

Top comments (0)