Posts

Showing posts with the label Python

REPLACE GREEN SCREEN USING OPENCV AND PYTHON 🤓

Image
In this post, we are going to discuss how to replace a video which is having green screen background with a background image using OpenCV and Python🐍. To understand this, you have to know how to detect colors using OpenCV and Python and you can check out by clicking here 🐱‍🏍. Input video and background image😄: Code😄: Output😄:  I hope it will help you😊.

PARANTHESIS CHECKER IMPLEMENTATION USING PYTHON - STACK APPLICATON👩‍💻👨‍💻

In this post, we are going to see one of the stack application's implementations which is a parenthesis checker and also the stack has several other applications like      🎯 R everse a string,       🎯 U ndo mechanism in editors,       🎯 R ecursion,       🎯 E xpression conversion, and so on. Here, I am using the 'queue' module to implement the stack in python. You can implement the stack without using the 'queue' module and you can check out  here x Code😃 :  I hope it will help you😊

MOTION DETECTION AND TRACKING USING OPENCV AND PYTHON

In this post, we are going to see how to detect and track movements(simply motion detection and tracking) using the OpenCV module. At first, you need to install the OpenCV-python module, to install the module just open your command prompt and type, pip install OpenCV-python Then hit enter, it will install the module automatically. After installing the module, just import the module and write the basic code to read the video. # import the opencv module import cv2 # capturing video capture = cv2.VideoCapture( "videos/input.mp4" ) After that, we have to get the two frames from the video or webcam and find the difference between the two frames, which is nothing but if there is a movement that occurs between the frames there might be a difference.  So, here we are trying to get the difference using the  cv2.absdiff() function in the OpenCV module and this method takes two parameters which are the two frames. # find difference between two frames diff = cv2.absdiff(img_1 , img_2) T...

COLOR DETECTION USING OPENCV AND PYTHON

Image
In this post, we are going to see how the colors are detected by the OpenCV module.  The first step to get into this is just install the modules as I mentioned below and import the modules, then read the input image and convert the BGR (Blue, Green, Red) image to HSV (Hue, Saturation, Variance) image then find the lower and higher HSV value of the color which you want to detect from the HSV color map (Shown below),  Then, we have to generate the mask of the color which we chose. So, we will use the cv2.inRange() function to generate the mask. Just pass the input image, lower HSV value higher HSV Value. This will generate a masked image of the input image and assign the masked image to the variable (mask). To detect the color we have to use the cv2.bitwise_and() function and pass the input image as the first and second argument and the third argument will be the mask and store this in the variable (detected_image). detected_image will be the final output of our progra...

FACE MESH USING PYTHON

Image
     The face mesh is a face geometry solution that estimates 468 3D face landmarks in real-time even on mobile devices. The output of the following code will be like this, Packages to install :  pip install opencv-python. pip install mediapipe. Program :  import cv2 import mediapipe as mp import time # Creating objects for face mesh mpFaceMesh = mp.solutions.face_mesh faceMesh = mpFaceMesh.FaceMesh( max_num_faces = 2 ) # Creating objects for drawing utilities mpDraw = mp.solutions.drawing_utils drawSpecs = mpDraw.DrawingSpec( thickness = 1 , circle_radius = 1 , color =( 0 , 255 , 0 )) # Capturing video from the web cam video = cv2.VideoCapture( 0 ) previousTime = 0 currentTime = 0 while True : success , img = video.read() # Converting BGR image to RGB image imgRGB = cv2.cvtColor(img , cv2.COLOR_BGR2RGB) # Getting landmark points and storing in multiFaceLandmarks variable result = faceMesh.process(imgRGB) multiFaceLanmarks ...

FACE DETECTION USING MEDIAPIPE AND PYTHON

Packages to install :  pip install opencv-python. pip install mediapipe. Program :  # Face Detection using mediapipe with python import cv2 import mediapipe as mp import time # Creating objects for detecting face mpFaceDetection = mp.solutions.face_detection mpDraw = mp.solutions.drawing_utils faceDetection = mpFaceDetection.FaceDetection() # Capturing video from the web cam video = cv2.VideoCapture( 0 ) currentTime = 0 previousTime = 0 while True : success , img = video.read() # Converting BGR image to RGB image RGBimg = cv2.cvtColor(img , cv2.COLOR_BGR2RGB) # Getting landmark points and storing in multiHandLandmarks variable result = faceDetection.process(RGBimg) # This 'if' block will run when it's having the face landmark points if result.detections: for index , detection in enumerate (result.detections): score = detection.score[ 0 ] * 100 boundingBox = detection.location_data.relative_bounding_box ...

CAPTURING AND SAVING VIDEO FROM THE WEBCAM USING OPENCV AND PYTHON

     The following python program shows how to save the video in your machine which is captured through the webcam. cv2.VideoWriter(filename.mp4, fourcc, fps, frame size) is the method used in the code. Program :  import cv2 # Capturing videos from the webcam video = cv2.VideoCapture( 0 ) # Defining codec fourcc = cv2.VideoWriter_fourcc(* "XVID" ) # Creating videowriter object out = cv2.VideoWriter( "asdf.mp4" , fourcc , 20.0 , ( 640 , 480 )) while video.isOpened(): success , img = video.read() if success: # writing frame by frame to the video file out.write(img) cv2.imshow( "Video" , img) key = cv2.waitKey( 1 ) if key == 13 : exit () else : break out.release()

DETECTING AND BLUR THE FACE USING OPENCV AND PYTHON

Image
    The following python code shows the conversion process of the detected face to blur using the OpenCV module. The method is used to convert blur is GaussianBlur(Source, ksize, sigmaX) . source: The image. ksize  : (kernel.width, kernel.height). kernel width and kernel height can differ but they must be positive and odd. Program :  import cv2 trainedDataset = cv2.CascadeClassifier( "haarcascade_frontalface_default.xml" ) img = cv2.imread( "images/Elon Musk.jpg" ) faces = trainedDataset.detectMultiScale(img) for x , y , w , h in faces: cv2.rectangle(img , (x , y , w , h) , ( 50 , 50 , 50 ) , 2 ) img[y:y + h , x:x + w] = cv2.GaussianBlur(img[y:y + h , x:x + w] , ( 93 , 93 ) , 0 ) cv2.imshow( "Image" , img) cv2.waitKey( 0 ) Output :  If you have any doubts in the code please refer face detection in image file using python .

BASIC POSE DETECTION AND TRACKING USING PYTHON

Image
     High fidelity human body pose tracking, inferring up to 33 3D full-body landmarks from RGB video frames. The 33 full-body landmarks will be like,  And, The output will be like this,  Packages to install :  pip install opencv-python. pip install mediapipe. Program :  # Pose Estimation with Python import cv2 import mediapipe as mp import time # Capturing video from the web cam video = cv2.VideoCapture( "videos/running.mp4" ) # Creating object for pose detection myPose = mp.solutions.pose pose = myPose.Pose() mpDraw = mp.solutions.drawing_utils currentTime = 0 previousTime = 0 while True : success , img = video.read() # Converting BGR image to RGB image RGBimg = cv2.cvtColor(img , cv2.COLOR_BGR2RGB) img = cv2.resize(img , None, fx = 0.15 , fy = 0.15 ) # Getting landmark points and storing in poseLandmarks variable result = pose.process(RGBimg) poseLandmarks = result.pose_landmarks # This 'if' block will run when it's h...

BASIC HAND TRACKING USING PYTHON

Image
     Basically, the hand tracking is based on the 21 landmarks in 3D with multi-hand support, based on high-performance palm detection and hand landmark model. The 21 hand landmarks will be like,  And, The output will be like this,  Packages to install :  pip install opencv-python. pip install mediapipe. Program :  # Hand Tracking with python import cv2 import mediapipe as mp import time # Capturing video from the web cam video = cv2.VideoCapture( 0 ) # Creating objects for hands mpHands = mp.solutions.hands hands = mpHands.Hands() previousTime = 0 currentTime = 0 while True : success , img = video.read() # Converting BGR image to RGB image RGBimg = cv2.cvtColor(img , cv2.COLOR_BGR2RGB) # Getting landmark points and storing in multiHandLandmarks variable result = hands.process(RGBimg) multiHandLandmarks = result.multi_hand_landmarks # This 'if' block will run when it's having the handlandmark points if multiHandLandmarks...

DETECTING ACCURACY LEVEL OF THE KNOWN AND TEST FACES USING PYTHON

Image
The following code shows the accuracy level of the trained face and test face. If the value is small, then the accuracy is high. Packages to install :  pip install openCV. pip install Face Recognition. pip install numpy. Images used :       Trained Face                               Test Face   Program :  # Detecting accuracy level of the trained image and test image import cv2 import face_recognition import numpy as np # known image imgElon = face_recognition.load_image_file( "images/Elon Musk.jpg" ) # imgElon=cv2.imread("images/Elon Musk.jpg") imgElon = cv2.cvtColor(imgElon , cv2.COLOR_BGR2RGB) # Test image imgElonTest = face_recognition.load_image_file( "images/Elon Musk Test.jpg" ) # imgElon=cv2.imread("test images/Elon Musk Test.jpg") imgElonTest = cv2.cvtColor(imgElonTest , cv2.COLOR_BGR2RGB) # known image location & encodings faceLoc = ...

PYTHON PROGRAM TO CHECK THE GIVEN NUMBER IS POWER OF 2

Image
To check the given number is power of 2, simply take the log of the number on base 2 and if you get an integer then number is power of 2. To get the log of the number on base 2 use the module math and use log2() function, the log2() function returns the float value. To get the integer value just compare the ceil and floor value of the float value. If the ceil and floor value is equal, then it must be a integer. Program :  # Program to check the given number is power of 2 import math def isPowerOfTwo (num): return math.ceil(math.log2(num)) == math.floor(math.log2(num)) num = int ( input ( "Enter number: " )) if (isPowerOfTwo(num)): print ( f" { num } is a power of 2" ); else : print ( f" { num } is not a power of 2" ); Output : 

PYTHON PROGRAM TO CHECK THE GIVEN NUMBER IS PRIME OR NOT

Image
The condition to check the given number is prime or not is the number is only divisible by one and by itself. Program :  # Program to check the given number is prime or not def checkingPrime(num): prime = True for i in range( 2 , num): if num%i == 0 : prime = False # multiply and divide by i value = f" { i } times { num // i } is { num } " print(value) break else : prime = True return prime num = int(input( "Enter number: " )) if num > 1 : if checkingPrime(num): print( f" { num } is a prime number" ) else : print( f"So, { num } is not a prime number" ) else : print( "The number must be greater than 1" ) Output : 

PASSWORD GENERATOR USING PYTHON

Image
Program :  import random import string lower = string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz upper = string.ascii_uppercase # ABCDEFGHIJKLMNOPQRSTUVWXYZ letters = string.ascii_letters # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ punc = string.punctuation # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ digits = string.digits # 0123456789 def password (length , num= False, strength= "risky" ): """length -> no of characters, num -> if True returns password with numbers, strength -> risky, weak, strong""" pwd = "" # If the value of default variable strength is 'risky' if strength == "risky" : if num: length = length - 2 for i in range ( 2 ): pwd = pwd + random.choice(digits) for i in range (length): pwd = pwd + random.choice(lower) # If the value of default variable strength is 'weak' ...

USER MANAGEMENT USING FLASK FRAMEWORK AND MySQL DATABASE IN PYTHON

Image
Package Installation :   pip install flask pip install flask-mysqldb Program : # User Management in python using Flask framework and MySQL Database from flask import Flask , render_template , url_for , request , redirect , flash from flask_mysqldb import MySQL app = Flask(__name__) # This takes the filename as a parameter # MySQL Connection app.config[ "MYSQL_HOST" ] = "localhost" app.config[ "MYSQL_USER" ] = "root" # Database Username app.config[ "MYSQL_PASSWORD" ] = "Enter the password" # Database Password app.config[ "MYSQL_DB" ] = "crud" # Database Name app.config[ "MYSQL_CURSORCLASS" ] = "DictCursor" mysql = MySQL(app) # Loading Home Page @app.route ( "/" ) # Home Page def home (): cursor = mysql.connection.cursor() # SELECT Query query = "SELECT * FROM users" cursor.execute(query) result = cursor.fetchall() return render_template...

MYSQL DATABASE CONNECTIVITY IN PYTHON

Image
MySQL Database Connectivity :  First you need to setup Apache , phpMyAdmin and MySQL.  To know the setup procedure  click here . As a example here I am using  Users  for table name and  Id ,  Name ,  Age ,  City   for field names. The below program shows  CRUD  operation in MySQL using python. C - Create (INSERT) R - Read (SELECT) U - Update (UPDATE) D - Delete (DELETE) Program :  # MySQL DATABASE CONNECTIVITY import mysql.connector # presenting output in tabular view from tabulate import tabulate # connecting the database file to MySQL connection = mysql.connector.connect( host = "localhost" , user = "enter username" , password = "enter password" , database = "enter database file name" ) cursor = connection.cursor() # function to INSERT data def insert_data (name , age , city): # INSERT query query = "INSERT INTO Users (name, age, city) values (%s, %s, %s)" # to execute the query cursor.execute(query , (n...