Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Open CV
  • scikit-image
  • pycairo
  • Pyglet
  • Python
  • Numpy
  • Pandas
  • Python Database
  • Data Analysis
  • ML Math
  • Machine Learning
  • NLP
  • Deep Learning
  • Deep Learning Interview Questions
  • ML Projects
  • ML Interview Questions
  • 100 Days of Machine Learning
Open In App
Next Article:
Python OpenCV: Meanshift
Next article icon

Python OpenCV: Meanshift

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. 

Meanshift

The idea behind meanshift is that in meanshift algorithm every instance of the video is checked in the form of pixel distribution in that frame. We define an initial window, generally a square or a circle for which the positions are specified by ourself which identifies the area of maximum pixel distribution and tries to keep track of that area in the video so that when the video is running our tracking window also moves towards the region of maximum pixel distribution. The direction of movement depends upon the difference between the center of our tracking window and the centroid of all the k-pixels inside that window.
Meanshift is a very useful method to keep track of a particular object inside a video. Meanshift can separate the static background of a video and the moving foreground object.

Examples: 

1. The tracking windows is tracking the football.  

2. The tracking window is tracking the juggling ball. 

3. The tracking window is tracking the football player. 

Python3
# Python program to demonstrate # meanshift    import numpy as np import cv2    # read video cap = cv2.VideoCapture('sample.mp4')   # retrieve the very first  # frame from the video _, frame = cap.read()   # set the region for the # tracking window p, q, r, s # put values according to yourself p, q, r, s = 150, 150, 460, 100 track_window = (r, p, s, q)        # create the region of interest r_o_i = frame[p:p + q, r:r + s]  # converting BGR to HSV format hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)   # apply mask on the HSV frame mask = cv2.inRange(hsv,                     np.array((0., 61., 33.)),                    np.array((180., 255., 255.)))  # get histogram for hsv channel roi = cv2.calcHist([hsv], [0], mask,                     [180], [0, 180])  # normalize the retrieved values cv2.normalize(roi, roi, 0, 255,                cv2.NORM_MINMAX)   # termination criteria, either 15  # iteration or by at least 2 pt termination = (cv2.TERM_CRITERIA_EPS |                 cv2.TERM_CRITERIA_COUNT                , 15, 2 )   while(True):     _, frame = cap.read()       frame = cv2.resize(frame,                         (1280, 720),                         fx = 0,                         fy = 0,                         interpolation = cv2.INTER_CUBIC)       # convert BGR to HSV format     hsv = cv2.cvtColor(frame,                         cv2.COLOR_BGR2HSV)          bp = cv2.calcBackProject([hsv],                               [0],                               roi,                               [0, 180],                               1)       # applying meanshift to get the new region     _, track_window = cv2.meanShift(bp,                                      track_window,                                      termination)       # Draw track window on the frame     x, y, w, h = track_window     vid = cv2.rectangle(frame, (x, y),                          (x + w, y + h),                          255, 2)          # show results     cv2.imshow('tracker', vid)       k = cv2.waitKey(1) & 0xff     if k == ord('q'):         break          # release cap object cap.release()  # destroy all opened windows cv2.destroyAllWindows() 

Output: Some frames from the output video

Disadvantages of using meanshift

There are 2 main disadvantages of using the Meanshift for object tracking.  

  • The size of the tracking window remains the same irrespective of the distance of the object from the camera.
  • The Window will track the object only when it is in the region of that object. So we must hardcode our position of the window carefully. 

Next Article
Python OpenCV: Meanshift

K

KaranGupta5
Improve
Article Tags :
  • Python
  • OpenCV
  • Python-OpenCV
Practice Tags :
  • python

Similar Reads

    Python OpenCV Cheat Sheet
    The Python OpenCV Cheat Sheet is your complete guide to mastering computer vision and image processing using Python. It's designed to be your trusty companion, helping you quickly understand the important ideas, functions, and techniques in the OpenCV library. Whether you're an experienced developer
    15+ min read
    imreadmulti() in Python Opencv
    OpenCV (Open Source Computer Vision) library primarily focuses on image and video processing. To load a single image through OpenCV, imread() function is used. However, to load multiple images in a single object, imreadmulti() function is used. Images within a file are considered as a page. Although
    4 min read
    Python OpenCV - Canny() Function
    Canny edge detection algorithm is used in computer vision for identifying edges within an image. It helps in highlighting boundaries which are important for tasks like object detection and image segmentation. In this article, we will see how OpenCV's built-in Canny() function detects edges in an ima
    3 min read
    Python OpenCV - BFMatcher() Function
    In this article, we will be going to implement Python OpenCV - BFMatcher() Function. Prerequisites: OpenCV, matplotlib What is BFMatcher() Function? BFMatcher() function is used in feature matching and used to match features in one image with other image. BFMatcher refers to a Brute-force matcher th
    3 min read
    Python OpenCV | cv2.imshow() method
    OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.imshow() method is used to display an image in a window. The window automatically fits the image size. Syntax: cv2.imshow(window_name, image)Parameters: window_name: A string representing the name of the wi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences