current position:Home>Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
2022-01-30 09:43:49 【Program yuan one_ Shining Xiaomei】
Use Python,OpenCV Of Meanshift and Camshift Algorithm to find and track objects in video
This blog will show you how to use Meanshift and Camshift Algorithm to find and track objects in video .
**MeanShift: Uniform shift
Camshift(Continuously Adaptive Meanshift) Continuous adaptive uniform shift **
-
cv2.meanShift(): Meanshift Even shift can always find a window with the largest pixel distribution , And track the object ;
-
cv2.CamShift(): CAMshift yes Meanshift The optimization of the , It will continuously automatically resize the window , And calculate the direction of the best fitting ellipse . It again applies the mean transformation with the new scaled search window and the position of the previous window , Until the required accuracy is achieved ;
1. design sketch
The official sample ——Meanshift The effect diagram of uniform displacement is as follows :
The official sample ——CAMshift The effect diagram of continuous adaptive average shift is as follows :
You can see Camshift It will automatically adjust the size and rotation of the box , It can better fit the tracked object ;
2. Source code
2.1 MeanShift
# Use MeanShift Average shift sum CAMshift(Continuously Adaptive Meanshift) Continuously adaptive equalization to find and track objects
# CAMshift yes MeanShift The optimization of the , It will continuously automatically resize the window , And calculate the direction of the best fitting ellipse . It again applies the mean transformation with the new scaled search window and the position of the previous window , Until the required accuracy is achieved ;
import numpy as np
import cv2
cap = cv2.VideoCapture('images/slow_traffic_small.mp4')
# Get the first frame of the video
ret, frame = cap.read()
# Set the initial window position
x, y, w, h = 300, 200, 100, 50 # Hard coded location
track_window = (x, y, w, h)
# Set the tracking object ROI
roi = frame[y:y + h, x:x + w]
# Only consider HSV The color of
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
# In order to avoid wrong values due to low light , Use cv2.inRange() Function to discard low light value .
mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
# Set termination criteria ,10 Iterations or moves at least 1pt
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
while (1):
ret, frame = cap.read()
if ret == True:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)
# application meanshift Get new location
ret, track_window = cv2.meanShift(dst, track_window, term_crit)
# Draw it on the image
x, y, w, h = track_window
img2 = cv2.rectangle(frame, (x, y), (x + w, y + h), 255, 2)
cv2.imshow('img2', img2)
k = cv2.waitKey(60) & 0xff
if k == 27:
break
else:
cv2.imwrite(chr(k) + ".jpg", img2)
else:
break
cv2.destroyAllWindows()
cap.release()
Copy code
2.2 Camshift(Continuously Adaptive Meanshift) Continuous adaptive uniform shift
# Use MeanShift Average shift sum CAMshift(Continuously Adaptive Meanshift) Continuously adaptive equalization to find and track objects
# CAMshift yes MeanShift The optimization of the , It will continuously automatically resize the window , And calculate the direction of the best fitting ellipse . It again applies the mean transformation with the new scaled search window and the position of the previous window , Until the required accuracy is achieved ;
import numpy as np
import cv2
cap = cv2.VideoCapture('images/slow_traffic_small.mp4')
# Get the first frame of the video
ret, frame = cap.read()
# Set the initial window position
x, y, w, h = 300, 200, 100, 50 # Hard coded location
track_window = (x, y, w, h)
# Set the tracking object ROI
roi = frame[y:y + h, x:x + w]
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
# Set termination conditions , iteration 10 Move once or at least 1pt
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
while (1):
ret, frame = cap.read()
if ret == True:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)
# application camshift Get new location
# Returns a rotated rectangle and box parameter ( Used to pass as a search window in the next iteration )
# It first applies the mean transformation . once meanshift convergence , It updates the size of the window , And calculate the direction of the best fitting ellipse . It again applies the mean transformation with the new scaled search window and the position of the previous window . The process continues until the required accuracy is met .
ret, track_window = cv2.CamShift(dst, track_window, term_crit)
# Draw on the image
pts = cv2.boxPoints(ret)
pts = np.int0(pts)
img2 = cv2.polylines(frame, [pts], True, 255, 2)
cv2.imshow('img2', img2)
# cv2.waitKey(0)
k = cv2.waitKey(60) & 0xff
if k == 27:
break
else:
cv2.imwrite(chr(k) + ".jpg", img2)
else:
break
cv2.destroyAllWindows()
cap.release()
Copy code
3. Reference resources
copyright notice
author[Program yuan one_ Shining Xiaomei],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300943477510.html
The sidebar is recommended
- Similarities and differences of five pandas combinatorial functions
- Python beginner's eighth day ()
- Necessary knowledge of Python: take you to learn regular expressions from zero
- Get your girlfriend's chat records with Python and solve the paranoia with one move
- My new book "Python 3 web crawler development practice (Second Edition)" has been recommended by the father of Python!
- From zero to familiarity, it will take you to master the use of Python len() function
- Python type hint type annotation guide
- leetcode 108. Convert Sorted Array to Binary Search Tree(python)
- For the geometric transformation of Python OpenCV image, let's first talk about the extraordinary resize function
- leetcode 701. Insert into a Binary Search Tree (python)
guess what you like
-
For another 3 days, I sorted out 80 Python datetime examples, which must be collected!
-
Python crawler actual combat | using multithreading to crawl lol HD Wallpaper
-
Complete a python game in 28 minutes, "customer service play over the president card"
-
The universal Python praise machine (commonly known as the brushing machine) in the whole network. Do you want to know the principle? After reading this article, you can write one yourself
-
How does Python compare file differences between two paths
-
Common OS operations for Python
-
[Python data structure series] linear table - explanation of knowledge points + code implementation
-
How Python parses web pages using BS4
-
How do Python Network requests pass parameters
-
Python core programming - decorator
Random recommended
- Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
- leetcode 110. Balanced Binary Tree(python)
- Django uses Django celery beat to dynamically add scheduled tasks
- The bear child said "you haven't seen Altman" and hurriedly studied it in Python. Unexpectedly
- Optimization iteration of nearest neighbor interpolation and bilinear interpolation algorithm for Python OpenCV image
- Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
- Use of Python partial()
- Python game development, pyGame module, python implementation of angry birds
- leetcode 1104. Path In Zigzag Labelled Binary Tree(python)
- Save time and effort. 10 lines of Python code automatically clean up duplicate files in the computer
- Learn python, know more meat, and be a "meat expert" in the technical circle. One article is enough
- [Python data structure series] "stack (sequential stack and chain stack)" -- Explanation of knowledge points + code implementation
- Datetime module of Python time series
- Python encrypts and decrypts des to solve the problem of inconsistency with Java results
- Chapter 1: introduction to Python programming-4 Hello World
- Summary of Python technical points
- 11.5K Star! An open source Python static type checking Library
- Chapter 2: Fundamentals of python-1 grammar
- [Python daily homework] day4: write a function to count the number of occurrences of each number in the incoming list and return the corresponding dictionary.
- Python uses turtle to express white
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
- Base64 encryption and decryption in Python
- Chapter 2: Fundamentals of python-2 variable
- Python garbage collection summary
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
- Python draws a spinning windmill with turtle
- Deep understanding of Python features
- A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
- Python opencv Canny edge detection knowledge supplement
- Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
- Python: faker extension package