The Wayback Machine - https://web.archive.org/web/20240816113816/https://www.geeksforgeeks.org/pollution-control-by-identifying-potential-land-for-afforestation-python-project/
Open In App

Pollution Control by Identifying Potential Land for Afforestation – Python Project

Last Updated : 02 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The program aims at controlling the pollution in a given area by suggesting the number of trees and the areas where they should be planted. The heart of the program is Computer Vision. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Python language. 

Tools and Technology used

In this project, we are using numpy and maths for calculation of our surrounding areas, PIL(Python Imaging Library) for manipulating. Before jumping to the project let’s understand these terms.

  • NumPy (Numerical Python): NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
  • Maths: The Python math module offers you the ability to perform common and useful mathematical calculations within your application. Here are a few practical uses for the math module: Calculating combinations and permutations using factorials. Calculating the height of a pole using trigonometric functions.
  • PIL(Python Imaging Library): Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats.
  • OpenCV: OpenCV is a cross-platform library using which we can develop real-time computer vision applications. It mainly focuses on image processing, video capture and analysis including features like face detection and object detection.

Step by Step Implementation

Step 1: Create a New Project

Create a new project in PyCharm IDE or V.S. Code

Step 2: Before going to the coding section first you have to do some pre-task

In this project, we need an API key provided by Google Maps.

Step 3: Let’s code Map segmentation 

The satellite image generated by the 1st step undergoes Image segmentation, which separates all the objects in the image by focussing on edges and boundaries. The image is divided into objects such as buildings, trees, water bodies, roads, barren land, etc. Our first algorithm of choice is Mean Shift Algorithm for segmentation.

Python
import numpy as np
import cv2
from PIL import Image
import urllib.parse
import urllib.request
import io
from math import log, exp, tan, atan, pi, ceil
from place_lookup import find_coordinates
from calc_area import afforestation_area

EARTH_RADIUS = 6378137
EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS
INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0
ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0

def latlontopixels(lat, lon, zoom):
    mx = (lon * ORIGIN_SHIFT) / 180.0
    my = log(tan((90 + lat) * pi / 360.0)) / (pi / 180.0)
    my = (my * ORIGIN_SHIFT) / 180.0
    res = INITIAL_RESOLUTION / (2 ** zoom)
    px = (mx + ORIGIN_SHIFT) / res
    py = (my + ORIGIN_SHIFT) / res
    return px, py

def pixelstolatlon(px, py, zoom):
    res = INITIAL_RESOLUTION / (2 ** zoom)
    mx = px * res - ORIGIN_SHIFT
    my = py * res - ORIGIN_SHIFT
    lat = (my / ORIGIN_SHIFT) * 180.0
    lat = 180 / pi * (2 * atan(exp(lat * pi / 180.0)) - pi / 2.0)
    lon = (mx / ORIGIN_SHIFT) * 180.0
    return lat, lon

query = input('What kinda places you want me look up? ')
results = find_coordinates(query)

zoom = 18

ullat, ullon = results['upper_left']
lrlat, lrlon = results['lower_right']

scale = 1
maxsize = 640

ulx, uly = latlontopixels(ullat, ullon, zoom)
lrx, lry = latlontopixels(lrlat, lrlon, zoom)

dx, dy = lrx - ulx, uly - lry

cols, rows = int(ceil(dx / maxsize)), int(ceil(dy / maxsize))

bottom = 120
largura = int(ceil(dx / cols))
altura = int(ceil(dy / rows))
alturaplus = altura + bottom

final = Image.new("RGB", (int(dx), int(dy)))
for x in range(cols):
  
    for y in range(rows):
        dxn = largura * (0.5 + x)
        dyn = altura * (0.5 + y)
        latn, lonn = pixelstolatlon(ulx + dxn, uly - dyn - bottom / 2, zoom)
        position = ','.join((str(latn), str(lonn)))
        print(x, y, position)
        urlparams = urllib.parse.urlencode({'center': position,
                                            'zoom': str(zoom),
                                            'size': '%dx%d' % (largura, alturaplus),
                                            'maptype': 'satellite',
                                            'sensor': 'false',
                                            'scale': scale,
                                            'key': 'AIzaSyA_d4uV3HqPPWbCb77VhXNYn5UcXRLAiVc'})
        urlparamsmaps = urllib.parse.urlencode({'center': position,
                                                'zoom': str(zoom),
                                                'size': '%dx%d' % (largura, alturaplus),
                                                'maptype': 'roadmap',
                                                'sensor': 'false',
                                                'scale': scale,
                                                'key': 'AIzaSyA_d4uV3HqPPWbCb77VhXNYn5UcXRLAiVc'})
        url = 'http://maps.google.com/maps/api/staticmap?' + urlparams
        url1 = 'http://maps.google.com/maps/api/staticmap?' + urlparamsmaps
        f = urllib.request.urlopen(url)
        h = urllib.request.urlopen(url1)
        image = io.BytesIO(f.read())
        imagemaps = io.BytesIO(h.read())
        im = Image.open(image)
        immaps = Image.open(imagemaps)
        im.save("map.png")
        immaps.save("map_normal.png")

        img = cv2.imread('map.png')
        img_maps = cv2.imread('map_normal.png')
        shifted = cv2.pyrMeanShiftFiltering(img, 7, 30)
        shifted_normal = cv2.pyrMeanShiftFiltering(img_maps, 7, 30)
        gray = cv2.cvtColor(shifted, cv2.COLOR_BGR2GRAY)
        ret, thresh = cv2.threshold(
            gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
        hsv = cv2.cvtColor(shifted, cv2.COLOR_BGR2HSV)
        hsv_normal = cv2.cvtColor(shifted_normal, cv2.COLOR_BGR2HSV)

        lower_trees = np.array([10, 0, 30])
        higher_trees = np.array([180, 100, 95])

        lower_houses = np.array([90, 10, 100])
        higher_houses = np.array([255, 255, 255])

        lower_roads = np.array([0, 0, 250])
        higher_roads = np.array([20, 20, 255])

        lower_feilds = np.array([0, 50, 100])
        higher_feilds = np.array([50, 255, 130])

        lower_feilds_blue = np.array([0, 80, 100])
        higher_feilds_blue = np.array([255, 250, 255])

        masktree = cv2.inRange(hsv, lower_trees, higher_trees)
        maskhouses = cv2.inRange(hsv, lower_houses, higher_houses)
        maskroads = cv2.inRange(hsv_normal, lower_roads, higher_roads)
        maskfeilds = cv2.inRange(hsv, lower_feilds, higher_feilds)
        gausssion_blur_maskfields = cv2.GaussianBlur(maskfeilds, (15, 15), 0)
        gausssion_blur_masktree = cv2.GaussianBlur(masktree, (15, 15), 0)
        blue_limiter = cv2.inRange(hsv, lower_feilds_blue, higher_feilds_blue)
        res_roads = cv2.bitwise_and(img_maps, img, mask=maskroads)
        # res_houses = cv2.bitwise_and(img,img,mask=maskhouses)
        res_feilds = cv2.bitwise_and(img, img, mask=gausssion_blur_maskfields)
        res_trees = cv2.bitwise_and(img, img, mask=masktree)

        # show the output image
        cv2.imshow('res', res_trees)
        cv2.imshow('res_fields', res_feilds)
        cv2.imshow('res_roads', res_roads)
        
        # cv2.imshow('res_houses',res_houses)
        # cv2.imshow('mask',maskfeilds)
        cv2.imshow('img', img)
        
        # cv2.imshow("hsv", hsv)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

tot_land_area_acres, number_of_trees = afforestation_area()

Step 4: Let’s code for place lookup

The user is required to input the name of the area, on which the program has to be executed. The satellite images of that area will be scraped and are zoomed such as to generate a clear image of the map on which image segmentation can be done.

Python
import urllib.parse
import requests

def find_coordinates(query):

    main_api = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
    url = main_api + \
        urllib.parse.urlencode({'query': query}) + '&key=Your API Key'

    json_data = requests.get(url).json()
    json_status = json_data['status']
    print('\nAPI Status :' + json_status)

    if json_status == 'OK':

        location_details = {
            'name_of_place': json_data['results'][0]['name'],
            'formatted_address': json_data['results'][0]['formatted_address'],
            'location': json_data['results'][0]['geometry']['location'],
            'upper_left': (json_data['results'][0]['geometry']['viewport']['northeast']['lat'],
                           json_data['results'][0]['geometry']['viewport']['southwest']['lng']),
            'lower_right': (json_data['results'][0]['geometry']['viewport']['southwest']['lat'], 
                            json_data['results'][0]['geometry']['viewport']['northeast']['lng']),
        }

        return location_details

Step 5: Let’s code calculate area

We will be finding the pollution level of the given area. According to that level, we will find the number of trees required to bring that particular level to normal. In this process, we need to train a Classifier that can identify the buildings, the trees, and most importantly, the free land. The Zernike moments used by the above method will be used as features for these segments. The classifier is trained with labels as ‘buildings’, ‘trees’, ‘water’, ‘free land’, and ‘roads’. After the training, we only need to find the part coming under the ‘Free Land’ label.

Python
import cv2
import numpy as np

def afforestation_area():

    img = cv2.imread('map.png')
    shifted = cv2.pyrMeanShiftFiltering(img, 7, 30)
    gray = cv2.cvtColor(shifted, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(
        gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    hsv = cv2.cvtColor(shifted, cv2.COLOR_BGR2HSV)

    lower_trees = np.array([10, 0, 10])
    higher_trees = np.array([180, 180, 75])

    lower_houses = np.array([90, 10, 100])
    higher_houses = np.array([255, 255, 255])

    lower_roads = np.array([90, 10, 100])
    higher_roads = np.array([100, 100, 100])

    lower_feilds = np.array([0, 20, 100])
    higher_feilds = np.array([50, 255, 255])

    lower_feilds_blue = np.array([0, 80, 100])
    higher_feilds_blue = np.array([255, 250, 255])

    masktree = cv2.inRange(hsv, lower_trees, higher_trees)
    maskhouses = cv2.inRange(hsv, lower_houses, higher_houses)
    maskroads = cv2.inRange(hsv, lower_roads, higher_roads)
    maskfeilds_houses = cv2.inRange(hsv, lower_feilds, higher_feilds)
    blue_limiter = cv2.inRange(hsv, lower_feilds_blue, higher_feilds_blue)
    maskfeilds = maskfeilds_houses
    res = cv2.bitwise_and(img, img, mask=maskfeilds)

    print(res.shape)  # (640, 622, 3)
    print(np.count_nonzero(res))  # 679089

    print("number of pixels", res.size//3)
    tot_pixels = res.size//3
    # print("number of pixels: row x col", res.)

    no_of_non_zero_pixels_rgb = np.count_nonzero(res)
    row, col, channels = res.shape  # 152886
    print("percentage of free land : ", (no_of_non_zero_pixels_rgb /
                                         (row*col*channels)))  # 0.5686369573954984
    percentage_of_land = no_of_non_zero_pixels_rgb/(row*col*channels)

    # https://www.unitconverters.net/typography/centimeter-to-pixel-x.htm
    # says 1 cm = 37.795275591 pixels
    cm_2_pixel = 37.795275591
    print("row in cm ", row/cm_2_pixel)
    print("col in cm ", col/cm_2_pixel)

    row_cm = row/cm_2_pixel
    col_cm = col/cm_2_pixel
    tot_area_cm = tot_pixels/(row_cm*col_cm)
    tot_area_cm_land = tot_area_cm*percentage_of_land

    print("Total area in cm^2 : ", tot_area_cm_land)

    # in google maps 2.2cm = 50m => 1cm = 22.727272727272727m
    # in real life at zoom 18 1cm^2 = (22.727272727272727m)^2
    # = 516.5289256198347 m^2
    print("Total area in m^2 : ", tot_area_cm_land*(516.5289256198347))
    tot_area_m_actual_land = tot_area_cm_land*(516.5289256198347)

    # 1 m^2 = 0.000247105 acres :: source Google
    tot_area_acre_land = tot_area_m_actual_land*0.000247105
    print("Total area in acres : ", tot_area_acre_land)

    # https://www.treeplantation.com/tree-spacing-calculator.html
    # says if you have 2 ft between rows, and 2ft between 
    # trees will can take 10890 trees per acre.
    number_of_trees = tot_area_acre_land*10890
    print(f"{round(number_of_trees)} number of trees can be planted in\
    {tot_area_acre_land} acres.")

    return tot_area_acre_land, round(number_of_trees)

    # show the output image
    # cv2.imshow('res',res)

    # cv2.imshow('mask',maskfeilds)
    # cv2.imshow('img', img)

    #cv2.imshow("hsv", hsv)
    # cv2.waitKey(delay=0)
    # cv2.destroyAllWindows()

# afforestation_area()

Step 6: Let’s code main file

Python
import numpy as np
import cv2
from PIL import Image
import urllib.parse
import urllib.request
import io
from math import log, exp, tan, atan, pi, ceil
from place_lookup import find_coordinates

EARTH_RADIUS = 6378137
EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS
INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0
ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0

def latlontopixels(lat, lon, zoom):
    mx = (lon * ORIGIN_SHIFT) / 180.0
    my = log(tan((90 + lat) * pi / 360.0)) / (pi / 180.0)
    my = (my * ORIGIN_SHIFT) / 180.0
    res = INITIAL_RESOLUTION / (2 ** zoom)
    px = (mx + ORIGIN_SHIFT) / res
    py = (my + ORIGIN_SHIFT) / res
    return px, py

def pixelstolatlon(px, py, zoom):
    res = INITIAL_RESOLUTION / (2 ** zoom)
    mx = px * res - ORIGIN_SHIFT
    my = py * res - ORIGIN_SHIFT
    lat = (my / ORIGIN_SHIFT) * 180.0
    lat = 180 / pi * (2 * atan(exp(lat * pi / 180.0)) - pi / 2.0)
    lon = (mx / ORIGIN_SHIFT) * 180.0
    return lat, lon

def calculate_area(res):
    """
    Args:
        Takes the transformed image as input
    Returns:
        :tot_area_acre_land: empty area in acres.
        :trees: rounded number of trees in the possible area.
    """
    # print(res.shape) # (640, 622, 3)
    # print(np.count_nonzero(res)) # 679089

    # print("number of pixels", res.size//3)
    tot_pixels = res.size//3
    # print("number of pixels: row x col", res.)

    no_of_non_zero_pixels_rgb = np.count_nonzero(res)
    row, col, channels = res.shape  # 152886
    
    percentage_of_land = no_of_non_zero_pixels_rgb/(row*col*channels)

    # https://www.unitconverters.net/typography/centimeter-to-pixel-x.htm
    # says 1 cm = 37.795275591 pixels
    cm_2_pixel = 37.795275591
    # print("row in cm ", row/cm_2_pixel)
    # print("col in cm ", col/cm_2_pixel)

    row_cm = row/cm_2_pixel
    col_cm = col/cm_2_pixel
    tot_area_cm = tot_pixels/(row_cm*col_cm)
    tot_area_cm_land = tot_area_cm*percentage_of_land

    # print("Total area in cm^2 : ", tot_area_cm_land)

    # in google maps 2.2cm = 50m => 1cm = 22.727272727272727 m 
    # in real life at zoom 18 1cm^2 = (22.727272727272727m)^2 
    # = 516.5289256198347 m^2
    tot_area_m_actual_land = tot_area_cm_land*(516.5289256198347)

    # 1 m^2 = 0.000247105 acres :: source Google
    tot_area_acre_land = tot_area_m_actual_land*0.000247105
    # print("Total area in acres : ", tot_area_acre_land)

    # https://www.treeplantation.com/tree-spacing-calculator.html
    # says if you have 2 ft between rows, and 2ft between trees 
    # will can take 10890 trees per acre.

    number_of_trees = tot_area_acre_land*10890
    # print(f"{round(number_of_trees)} number of trees can be planted
    # in {tot_area_acre_land} acres.")

    return tot_area_acre_land, round(number_of_trees)

def air_pollution_core(ullat, ullon, lrlat, lrlon, results):

    zoom = 18
    scale = 1
    maxsize = 640

    ulx, uly = latlontopixels(ullat, ullon, zoom)
    lrx, lry = latlontopixels(lrlat, lrlon, zoom)

    dx, dy = lrx - ulx, uly - lry

    cols, rows = int(ceil(dx / maxsize)), int(ceil(dy / maxsize))

    bottom = 120
    largura = int(ceil(dx / cols))
    altura = int(ceil(dy / rows))
    alturaplus = altura + bottom

    final = Image.new("RGB", (int(dx), int(dy)))
    total_acres_place, total_trees = 0., 0.
    total_tile_results = dict()
    for x in range(cols):
        for y in range(rows):
            dxn = largura * (0.5 + x)
            dyn = altura * (0.5 + y)
            latn, lonn = pixelstolatlon(
                ulx + dxn, uly - dyn - bottom / 2, zoom)
            position = ','.join((str(latn), str(lonn)))
            # print(x, y, position)
            urlparams = urllib.parse.urlencode({'center': position,
                                                'zoom': str(zoom),
                                                'size': '%dx%d' % (largura, alturaplus),
                                                'maptype': 'satellite',
                                                'sensor': 'false',
                                                'scale': scale,
                                                'key': 'YOUR_API_HERE'})
            url = 'http://maps.google.com/maps/api/staticmap?' + urlparams
            f = urllib.request.urlopen(url)
            image = io.BytesIO(f.read())
            im = Image.open(image)
            im.save("map_{}_{}_{}.png".format(x, y, position))

            img = cv2.imread("map_{}_{}_{}.png".format(x, y, position))
            shifted = cv2.pyrMeanShiftFiltering(img, 7, 30)
            gray = cv2.cvtColor(shifted, cv2.COLOR_BGR2GRAY)
            ret, thresh = cv2.threshold(
                gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
            hsv = cv2.cvtColor(shifted, cv2.COLOR_BGR2HSV)

            lower_trees = np.array([10, 0, 10])
            higher_trees = np.array([180, 180, 75])

            lower_houses = np.array([90, 10, 100])
            higher_houses = np.array([255, 255, 255])

            lower_roads = np.array([90, 10, 100])
            higher_roads = np.array([100, 100, 100])

            lower_feilds = np.array([0, 20, 100])
            higher_feilds = np.array([50, 255, 255])

            lower_feilds_blue = np.array([0, 80, 100])
            higher_feilds_blue = np.array([255, 250, 255])

            masktree = cv2.inRange(hsv, lower_trees, higher_trees)
            maskhouses = cv2.inRange(hsv, lower_houses, higher_houses)
            maskroads = cv2.inRange(hsv, lower_roads, higher_roads)
            maskfeilds_houses = cv2.inRange(hsv, lower_feilds, higher_feilds)
            blue_limiter = cv2.inRange(
                hsv, lower_feilds_blue, higher_feilds_blue)
            maskfeilds = maskfeilds_houses
            res = cv2.bitwise_and(img, img, mask=maskfeilds)

            area_in_acres, number_of_trees = calculate_area(res)
            total_acres_place += area_in_acres
            total_trees += number_of_trees
            # print(f"area: {area_in_acres}, no of trees: {number_of_trees}")

            tile_results = {
                "name_of_tile_image": "map_{}_{}_{}.png".format(x, y, position),
                "area_acres": area_in_acres,
                "number_of_trees": number_of_trees
            }
            # print(tile_results)
            total_tile_results["{}_{}_{}".format(
                x, y, position)] = tile_results
            
            # uncomment below for viewing the output images
            # cv2.imshow('res',res)
            # cv2.imshow('img', img)
            # cv2.waitKey(delay=2000)
            # cv2.destroyAllWindows()
            
    # print(total_tile_results)
    results["total_tile_results"] = total_tile_results
    results["total_acres_of_land"] = total_acres_place
    results["total_number_of_trees"] = total_trees
    return results


def location_based_estimation(place):
    """
    :place: is a string that expects a name of a place
    """
    results = find_coordinates(place)

    ullat, ullon = results['upper_left']
    lrlat, lrlon = results['lower_right']

    returning_json = air_pollution_core(ullat, ullon, lrlat, lrlon, results)
    return returning_json


def coordinates_based_estimation(ullat, ullon, lrlat, lrlon):
    """
    :upperleft: a string expecting upperleft coordinates of 
    the tile you are expecting. ex : '12.92,79.11'
    :lowerright: a string expecting lowerright coordinates of
    the tile you are expecting. ex :'12.91,79.13'
    """
    # print(f"{upperleft.replace('\"','')}")
    # ullat, ullon = map(float, upperleft.split(','))
    # lrlat, lrlon = map(float, lowerright.split(','))
    results = dict()

    returning_json = air_pollution_core(ullat, ullon, lrlat, lrlon, results)
    return returning_json

Output:

68747470733a2f2f7332322e706f7374696d672e63632f36613637616d7968642f494d475f32303138303332365f3030333930335f302e6a7067min1-copy


This is how the complete project structure looks like.

GitHub Link: https://github.com/abhishektyagi2912/airpollution-analyses 



Previous Article
Next Article

Similar Reads

Project Idea | (Optimization of Object-Based Image Analysis  with Super-Pixel for Land Cover Mapping)
ABSTRACT: A prerequisite for object-based image analysis is the generation of adequate segments. However, the parameters for the image segmentation algorithms are often manually defined. Therefore, the generation of an ideal segmentation level is usually costly and user-depended. A strategy for a semi-automatic optimization of object-based classifi
3 min read
Identifying patterns in DataFrames using Data-Pattern Module
Prerequisites: Pandas Module, Pandas Data frame Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas are fast and it has high-performa
3 min read
Identifying Test files and Functions using Pytest
The Python framework used for API testing is called Pytest. For executing and running the tests, it is crucial to identify the test files and functions. Pytest, by default, executes all the test files under a certain package which are of the format test_*.py or *_test.py, in case there is no test file mentioned. Similarly, for functions, all the fu
2 min read
Have A Happy Diwali With Artificial Intelligence - How AI Can Help In Managing The Pollution This Festival?
Diwali is the festival of lights. It is the festival of joy when we welcome Goddess Lakshmi in the form of wealth and prosperity into our homes. It is the time for giving and receiving gifts and also eating lots of sweets! But in recent times, Diwali has also become the festival of beautiful multicolored fireworks that explode against the night sky
5 min read
Learn with GeeksforGeeks Course - Best Courses To Land Job In Your Dream Company
Please refer GeeksforGeeks - FREE & Paid Courses for the latest list of courses. Do you want to learn more about Data Structures and Algorithms to help in your placement process? Or maybe you want to focus on your basics and learn C++, Python, or Java? Be it learning complex topics like Machine Learning and Data Science or learning HTML, Geeksf
11 min read
Project Idea | Traffic Signal Control (Automatic)
Project Title : Traffic Signal Control (Automatic) Using Machine Learning and IoT Introduction: In India Traffic has become a huge problem, in order to control traffic in India we use manually operated traffic lights i.e. how much time the vehicle needs to stop at the signal is decided by the traffic police at that location. Based on his experience
1 min read
Project Idea | (Project Approval System)
Academic Project management is a major issue which is faced by many educational institutes, the main reason for this is there is no automated system followed in any institute. College management/staff gathers all the project reports and project sources from students and store them physically in some locations probably libraries. To overcome this pr
2 min read
Loops and Control Statements (continue, break and pass) in Python
Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
4 min read
Draw Control Flow Graph using pycfg | Python
Prerequisites: Control Flow Graph, Cyclomatic Complexity Usually, we draw manual Control Flow Graph using pen and paper by analyzing the control flow of the program. CFG helps us finding independent paths (Cyclomatic Complexity), which leads to the number of test cases required to test the program. We can automate the CFG task using a Python librar
2 min read
How to Control Laptop Screen Brightness using Python?
To control the brightness of the screen we are using the screen-brightness-control library. The screen-brightness-control library has only one class and few functions. The most useful functions are mentioned below: get_brightness()set_brightness()fade_brightness()list_monitors() Installation: We can install the package by running the following pip
4 min read
How to control PC from anywhere using Python?
Prerequisite - Socket programming in Python In this solution, we use the concept of Socket Programming for establishing communication between two computers. Socket Programming in Python Socket Programming is a way of connecting two systems on a network to communicate with each other. Sockets are the endpoints built for sending and receiving data an
2 min read
Brightness Control With Hand Detection using OpenCV in Python
In this article, we are going to make a Python project that uses OpenCV and Mediapipe to see hand gesture and accordingly set the brightness of the system from a range of 0-100. We have used a HandTracking module that tracks all points on the hand and detects hand landmarks, calculate the distance between thumb tip and index fingertip and maps the
6 min read
Control Arduino with Python and pyFirmata
In this article, we will learn how to link an Arduino to a Python script in order to operate the Arduino. This example of constructing a 4-bit binary up-counter using Python script to control Arduino helps us understand this better. Components Required:An Arduino Board (We will be using Arduino UNO, but other similar boards like Arduino Mini, MEGA,
4 min read
Integrating Poetry in Python with version control systems
Version control systems, like Git, are crucial components in today’s software application development processes. They assist in controlling modification to the project's source code, working with other developers, and, reviewing the history of the project. In this tutorial, crucial steps of Poetry’s integration with the project’s version control ar
7 min read
wxPython | create control tool using CreateTool() function
In this function, we are going to learn how can we create a control tool using CreateTool() function. It is another version of CreateTool() function which only takes two parameters that is control and label. Let's see the parameters in detail. Parameters : ParameterInput TypeDescriptioncontrolwx.ControlThe control is to be added.labelstringText to
1 min read
PyQt5 QScrollBar – Setting Inverted Control Property
In this article we will see how we can set inverted control property of QScrollBar. QScrollBar is a control that enables the user to access parts of a document that is larger than the widget used to display it. Slider is the scroll-able object inside the bar. This property holds whether or not the slider inverts its wheel and key events. If this pr
2 min read
PyQt5 QScrollBar – Getting Inverted Control Property
In this article we will see how we can get inverted control property of QScrollBar. QScrollBar is a control that enables the user to access parts of a document that is larger than the widget used to display it. Slider is the scroll-able object inside the bar. This property holds whether or not the slider inverts its wheel and key events. If this pr
2 min read
Window Resizer Control Panel - Tkinter
Prerequisite: Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we wi
4 min read
Pygame - Control Sprites
In this article, we will discuss how to control the sprite, like moving forward, backward, slow, or accelerate, and some of the properties that sprite should have. We will be adding event handlers to our program to respond to keystroke events, when the player uses the arrow keys on the keyboard we will call our pure methods to move the object on th
4 min read
Pycharm - Integration of Version Control
PyCharm is an integrated development environment (IDE) specifically designed for Python programming. It was developed by JetBrains and is one of the most popular and widely used IDEs among Python developers. In this article, we will see the integration of Version Control in PyCharm. Version Control Integration in PyCharmBelow are the steps by which
3 min read
Flask - Role Based Access Control
Flask is a  micro-framework written in Python. It is used to create web applications using Python. Role-based access control means certain users can access only certain pages. For instance, a normal visitor should not be able to access the privileges of an administrator. In this article, we will see how to implement this type of access with the hel
14 min read
Project Idea | Breakout game in Python
Project Title: Breakout game in Python Introduction: The project 'Breakout game in Python' is proposed to recreate a classical game of Breakout by using the Python language. It is meant to be a fully functional game with scores, lives, game over, and high score management. The high scores can also be uploaded to a website. The game is playable with
2 min read
Selenium Base Mini Project Using Python
Project Description:-Here, we're going to study a simple SMS bomber trick (for amusing and educational purpose). Selenium is a free tool for automated trying out across exceptional browsers. In this tutorial, we will learn how to ship mechanically range of unsolicited mail SMS for given variety of frequency and interval. Requirement: You need to in
2 min read
Rock, Paper, Scissor game - Python Project
In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of the three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”. Game Winner Conditions Let there be a Player w
15+ min read
Invisible Cloak using OpenCV | Python Project
Have you ever seen Harry Potter's Invisible Cloak; Was it wonderful? Have you ever wanted to wear that cloak? If Yes!! then in this post, we will build the same cloak which Harry Potter uses to become invisible. Yes, we are not building it in a real way but it is all about graphics trickery. In this post, we will learn how to create our own ‘Invisi
4 min read
Python - Eye blink detection project
In this tutorial you will learn about detecting a blink of human eye with the feature mappers knows as haar cascades. Here in the project, we will use the python language along with the OpenCV library for the algorithm execution and image processing respectively. The haar cascades we are going to use in the project are pretrained and stored along w
4 min read
Email Id Extractor Project from sites in Scrapy Python
Scrapy is open-source web-crawling framework written in Python used for web scraping, it can also be used to extract data for general-purpose. First all sub pages links are taken from the main page and then email id are scraped from these sub pages using regular expression. This article shows the email id extraction from geeksforgeeks site as a ref
8 min read
Face Mask detection and Thermal scanner for Covid care - Python Project
IntroductionThe coronavirus COVID-19 pandemic is triggering a worldwide health catastrophe, hence the World Health Organization recommends wearing a face mask in designated areas. Face Mask Detection and Hand Sanitization have been a well-known subject in recent times, as well as in image preparation and computer vision. Many new computations are b
5 min read
Online Schooling System - Python Project
In this article, we are going to build an Online schooling system United School for all students where they can study online and get an equivalent degree affiliated with a well-known organization. Many of the schools were shut and many are facing problems in teaching online through any platform. Here in this project, a well-organized Online learnin
4 min read
HAUS Connect - Python Project
One of the most common problems faced by college students is that we have very erratic timetables and it is a cumbersome task to keep up with them, these issues have been amplified enormously during these pandemic times where everyone is on their own. The purpose of this application is to help students keep track of their classes, tests, and assign
15+ min read
Practice Tags :
three90RightbarBannerImg