Live Webcam Drawing using OpenCV

Last Updated : 03 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let us see how to draw the movement of objects captured by the webcam using OpenCV. Our program takes the video input from the webcam and tracks the objects we are moving. After identifying the objects, it will make contours precisely. After that, it will print all your drawing on the output screen.
 

python3




# importing the modules
import cv2
import numpy as np
   
# set Width and Height of output Screen
frameWidth = 640
frameHeight = 480
   
# capturing Video from Webcam
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
   
# set brightness, id is 10 and
# value can be changed accordingly
cap.set(10,150)
    
# object color values
myColors = [[5, 107, 0, 19, 255, 255],
            [133, 56, 0, 159, 156, 255],
            [57, 76, 0, 100, 255, 255],
            [90, 48, 0, 118, 255, 255]]
   
# color values which will be used to paint
# values needs to be in BGR
myColorValues = [[51, 153, 255],          
                 [255, 0, 255],
                 [0, 255, 0],           
                 [255, 0, 0]]
  
# [x , y , colorId ] 
myPoints = []  
     
# function to pick color of object
def findColor(img, myColors, myColorValues):
  
    # converting the image to HSV format
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    count = 0
    newPoints = []
       
    # running for loop to work with all colors
    for color in myColors:
        lower = np.array(color[0:3])
        upper = np.array(color[3:6])
        mask = cv2.inRange(imgHSV,lower,upper)
        x, y = getContours(mask)
  
        # making the circles
        cv2.circle(imgResult, (x,y), 15,
                   myColorValues[count], cv2.FILLED)
        if x != 0 and y != 0:
            newPoints.append([x,y,count])
        count += 1
    return newPoints
    
   
# contours function used to improve accuracy of paint
def getContours(img):
    _, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_NONE)
    x, y, w, h = 0, 0, 0, 0
       
    # working with contours
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 500:
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
            x, y, w, h = cv2.boundingRect(approx)
    return x + w // 2, y
    
   
# draws your action on virtual canvas
def drawOnCanvas(myPoints, myColorValues):
    for point in myPoints:
        cv2.circle(imgResult, (point[0], point[1]),
                   10, myColorValues[point[2]], cv2.FILLED)
    
# running infinite while loop so that
# program keep running until we close it
while True:
    success, img = cap.read()
    imgResult = img.copy()
  
    # finding the colors for the points
    newPoints = findColor(img, myColors, myColorValues)
    if len(newPoints)!= 0:
        for newP in newPoints:
            myPoints.append(newP)
    if len(myPoints)!= 0:
  
        # drawing the points
        drawOnCanvas(myPoints, myColorValues)
    
    # displaying output on Screen
    cv2.imshow("Result", imgResult)
       
    # condition to break programs execution
    # press q to stop the execution of program
    if cv2.waitKey(1) and 0xFF == ord('q'): 
        break


Output : 
 

 



Previous Article
Next Article

Similar Reads

Face Detection using Python and OpenCV with webcam
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
4 min read
Python - Displaying real time FPS at which webcam/video file is processed using OpenCV
We will be displaying the real-time processing FPS of the video file or webcam depending upon our choice.FPS or frame per second or frame rate can be defined as number of frames displayed per second. A video can be assumed as a collection of images or we can say frames which are displayed at some rate to produce motion. if you wish to identify the
4 min read
Webcam QR code scanner using OpenCV
In this article, we're going to see how to perform QR code scanning using a webcam. Before starting, You need to know how this process is going to work. Firstly you need to open your webcam, and you've to run your python program to make it ready to scan the QR code. You can take the Qr code picture on your mobile and show the picture in front of yo
3 min read
Detect the RGB color from a webcam using Python - OpenCV
Prerequisites: Python NumPy, Python OpenCV Every image is represented by 3 colors that are Red, Green and Blue. Let us see how to find the most dominant color captured by the webcam using Python. Approach: Import the cv2 and NumPy modulesCapture the webcam video using the cv2.VideoCapture(0) method.Display the current frame using the cv2.imshow() m
2 min read
Saving Operated Video from a webcam using OpenCV
OpenCV is a vast library that helps in providing various functions for image and video operations. With OpenCV, we can perform operations on the input video. OpenCV also allows us to save that operated video for further usage. For saving images, we use cv2.imwrite() which saves the image to a specified file location. But, for saving a recorded vide
4 min read
Drawing with Mouse on Images using Python-OpenCV
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will try to draw on images with the help of the mo
3 min read
Drawing a cross on an image with OpenCV
In this article, we are going to discuss how to draw a cross on an image using OpenCV-Python. We can draw an overlay of two lines one above another to make a cross on an image. To draw a line on OpenCV, the below function is used. Syntax: cv2.line(image, starting Point, ending Point, color, thickness) Parameters: Image - The source image on which y
5 min read
Add image to a live camera feed using OpenCV-Python
In this article, we are going to learn how to insert an image in your live camera feed using OpenCV in Python. Stepwise ImplementationStep 1: Importing the libraries CV reads and stores all the images as a NumPy array. We need the NumPy library to manipulate the image and as expected we need the cv2 module. C/C++ Code # importing libraries import c
4 min read
Extract Video Frames from Webcam and Save to Images using Python
There are two libraries you can use: OpenCV and ImageIO. Which one to choose is situation-dependent and it is usually best to use the one you are already more familiar with. If you are new to both then ImageIO is easier to learn, so it could be a good starting point. Whichever one you choose, you can find examples for both below: ImageIOInstallatio
2 min read
Save frames of live video with timestamps - Python OpenCV
Images are very important data nowadays from which we can obtain a lot of information which will helpful for analysis. Sometimes data to be processed can be in the form of video. To process this kind of data we have to read video extract frames and save them as images. Security camera videos we have seen that there is a timestamp and date at top of
3 min read
How to capture a image from webcam in Python?
In this article, we will discuss how to capture an image from the webcam using Python. We will use OpenCV and PyGame libraries. Both libraries include various methods and functions to capture an image and video also. By using, these vast libraries we need to write only 4 to 5 lines of code to capture an image. Method 1: Using OpenCV OpenCV library
3 min read
How to show webcam in TkInter Window - Python
Python offers various modules for creating GUI applications, out of which, Tkinter lets users do various tasks inside their app. Thus, while creating a GUI app, have you ever felt the need to let the user open the camera on a specific condition? Don't know, how to achieve that. Continue reading this article further to know about how to open the cam
5 min read
WebCam Motion Detector in Python
This python program will allow you to detect motion and also store the time interval of the motion. Requirement: Python3OpenCV(libraries)Pandas(libraries) Install Requirements : Install Python3, install Pandas and OpenCV libraries. Main Logic : Videos can be treated as stack of pictures called frames. Here I am comparing different frames(pictures)
4 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Python - Drawing design using arrow keys in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this article we will see how we can
3 min read
Python | Drawing different shapes on PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip instal
3 min read
Python | Creating a Simple Drawing App in kivy
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Drawing App: In this we are going to create a simple drawing App with th
4 min read
PyCairo - Drawing different type of line caps
In this article, we will learn how we can draw different line caps types using PyCairo in python. The line caps are endpoints of lines. Steps of Implementation : Import the Pycairo module.Create a SVG surface object and add context to it.Setting color of the context & line widthSetting of line cap style using set_line_cap( )Creating a line. The
3 min read
Wand Drawing() function in Python
Another module for wand is wand.drawing. This module provides us with some very basic drawing functions. wand.drawing.Drawing object buffers instructions for drawing shapes into images, and then it can draw these shapes into zero or more images. Syntax : with Drawing() as draw: Note: In the above syntax "as draw" is just a nomenclature and can be a
1 min read
PYGLET – Drawing Mouse Cursor for Window
In this article we will see how we can draw mouse cursor for window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an
2 min read
PYGLET – Drawing Label
In this article we will see how we can draw a label on the window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an en
2 min read
PYGLET – Drawing Multiple Sprites
In this article, we will see how we can draw multiple sprites on the window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to
3 min read
PYGLET – Drawing Rectangle
In this article we will see how we can draw rectangle on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an enti
2 min read
PYGLET – Drawing Line
In this article, we will see how we can draw line on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire s
3 min read
PYGLET – Drawing Arc
In this article we will see how we can draw arc on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire scr
3 min read
PYGLET – Drawing Circle
In this article we will see how we can draw circles on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire
2 min read
PyCairo - Drawing different Pen dashes
Each line can be drawn with different pen dashes. A pen dash can be defined as the style of a line. The dash pattern is specified by the set_dash( ) method. The pattern is set by the dash list which of floating value. They can set the on and off part of the dashes in pattern. The dashes is used by the stroke( ) method to create a line pattern. If t
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg