Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the twentytwenty domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in C:\inetpub\wwwroot\blogs\wp-includes\functions.php on line 6121
K Akhilesh Saiju – Club TechKnowHow!
Categories
Programming Python

Object detection using OpenCV

In one of my previous articles, I elaborated on using OpenCV with python to switch on a user’s webcam, and to display the live feed. As a fun-ish Python project, I also created a GUI to pick out a spot in the feed and display its colour scheme, in RGB values.
Scurrying around in the OpenCV documentation, I realized how little I knew, and how deep the proverbial rabbit hole goes, regarding this library’s scope of implementation. One of the topics that immediately piqued my curiosity was live object detection.

Haar Cascades, an Introduction

The one method that I kept seeing again and again, which is used hand-in-glove with OpenCV for object detection, is the use of Haar Cascades. A bit more primitive than more modern techniques, using Haar Cascades provides nigh-unparalleled speed, although with the caveat of frequent false-positives. Even when creating this project, I noticed that the algorithm had a strange obsession of claiming my neck as a second face.
Despite its shortcomings, it’s still widely used, even while creating AI models. The method consists of an algorithm which can detect a particular type of object in real-time, based on pre-trained parameters. A Haar Classifier is used, which can detect features like edges and lines, and determines whether there is a particular object in the video, and can demarcate in what region it is.
For example, in terms of face detection, the HaarClassifier will be able to differentiate eye and nose regions by comparing the brighter and darker pixels. The Classifier works by using similar patterns and comparisons.

Creating a Face Detection Project in Python

Well, there’s no better way to learn than diving off of the deep end. So, I decided to borrow what I learnt from my last project and add a face detection functionality to the GUI.
First off, installing all the necessary packages, via the terminal:

pip install opencv-python
pip install Pillow
pip install tk

And subsequently, importing all the aforementioned packages:

import cv2
from tkinter import *
from PIL import Image, ImageTk

Using OpenCV’s method to access the devices webcam: 

vc = cv2.VideoCapture(0)

A fact that I failed to mention in my previous article, is that the parameter “0” is passed into the method to access the webcam. The address for any required video, from the file directory can also be passed as a parameter, to load the video

vc = cv2.VideoCapture("Jack Ryan.mp4")

Loading the Haar Cascade Classifier:

face_classifier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

In this step we are using an XML file, which contains the instructions for the Haar Classifier. Here’s a snippet of the file:
The first few lines in the haarcascade_frontalface_default.xml file
From within the file we can modify the parameters as per our requirements.
This particular Classifier facilitates detection of front-facing portraits.


Now, I have to make it absolutely clear, that there is a method built into OpenCV which displays the video feed, which runs indefinitely, until the user presses a specified key.

while True:

    success, vf = vc.read()
    if (success == False):
        break 
    gray = cv2.cvtColor(vf, cv2.COLOR_BGR2GRAY)
    fs = face_classifier.detectMultiScale(gray, 1.1, 5, minSize=(40, 40))
    for (x, y, w, h) in fs:
        cv2.rectangle(vid, (x, y), (x + w, y + h), (0, 255, 0), 4)
    cv2.imshow("Face Detection", vf) 
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

vc.release()
cv2.destroyAllWindows()

It’s a neat method. However, sometimes, a person just has to flex their Tkinter GUI skills. Using the code from my last python project to integrate the feed into a GUI;

window = Tk()
window.title("Video feed")
window.geometry("1200x700")
button = Button(window,text="Click to detect face")
button.grid(row=0, column=0)
label = Label(window, height=720, width=1280, text="Video feed here")
label.grid(row=1, column=1, columnspan=1)

def show_frames():
    success, vf = vc.read() 
    if (success==False):
        return  
    gray = cv2.cvtColor(vf, cv2.COLOR_BGR2GRAY)
    fs = face_classifier.detectMultiScale(gray, 1.1, 5, minSize=(40, 40))
    for (x, y, w, h) in fs:
        cv2.rectangle(vf, (x, y), (x + w, y + h), (0, 255, 0), 4)
    frame = cv2.cvtColor(vf, cv2.COLOR_BGR2RGB)
    img = Image.fromarray(frame)
    imgtk = ImageTk.PhotoImage(image = img)
    label.imgtk = imgtk
    label.configure(image = imgtk)
    label.after(20, show_frames)

button.config(command=show_frames)

window.mainloop()

In both methods, the frames from the feed are being converted to grayscale, and passed into the classifier.

gray = cv2.cvtColor(vf, cv2.COLOR_BGR2GRAY)
    fs = face_classifier.detectMultiScale(gray, 1.1, 5, minSize=(40, 40))

Using another OpenCV method, a rectangle is mapped onto the frame, where the classifier has detected the face.

for (x, y, w, h) in fs:
      cv2.rectangle(vf, (x, y), (x + w, y + h), (0, 255, 0), 4)
 

Using the program to detect a face

I tried loading a clip from Patriot Games (fantastic film, by the way) into the face detection model. The model clearly has no problem detecting dear old Dr. Jack Ryan.
An example of the Haar Cascades face detection algorithm in action, detecting a face from a given video
The model can also demarcate multiple faces, both in a video clip, and live webcam feed.

Categories
php XAMPP

Server-Side scripting with XAMPP

XAMPP is an open-source web server distribution which has become the de facto package used while handling PHP files.
XAMPP stands for (X) Cross-platform Operating System, Apache, MySQL, PHP and Perl.

Installing and setting up XAMPP

The official XAMPP installer, provided by Apache can be found at https://www.apachefriends.org/download.html , for various operating systems.
Installing and setting up the XAMPP control panel, the user can access it as such:

The XAMPP Control Panel
The XAMPP Control Panel provides access the various components of the user’s server.

Creating a Demo webpage

To demonstrate the working of the server, we can create a simple webpage, using HTML and PHP, which can be accessed through the server.

The “htdocs” folder can be found where XAMPP was installed. The files and content to be accessed in the web server need to be saved in this folder.

Navigating towards the "htdocs" folder in the XAMPP installation folder
Using HTML, we can create a webpage which utilizes a form to collect any arbitrary data from the user. In this case, a variety of buttons are created, each having its own value, as per the user’s preference.

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image of an Egg</title>
</head>
<style>
    .content {
      max-width: 500px;
      margin: auto;
    }
    </style>
<body>
    <div class="content">
    <h1>Welcome to Image of an Egg</h1>
    <h2>Here's the aforementioned image</h2>
    <img src="Egg pictures/Og egg.jpg">
    <p>Get a personalized egg prepared for you</p>
    <form action="final_egg.php", method="post">
        What is your name? :- <input type="text" name="name"><br>
        <p>What kind of egg would you like?</p>
        <input type="submit" name="action" value="Fried"/>
        <input type="submit" name="action" value="Hard Boiled" />
        <input type="submit" name="action" value="Poached" />
        <input type="submit" name="action" value="Scrambled" />
        <input type="submit" name="action" value="Soft Boiled" />
        <input type="submit" name="action" value="Omelette" />
        <input type="submit" name="action" value="Set free" />
    </form>
    </div>
</body>
</html>

We can use PHP to create a webpage which accesses information provided by the user in the previous page and uses it to personalize the endpage. The PHP file accesses user information from the server-side, to create a better frontend experience. An anchor tag is also provided so that users can return to the original page.

<!-- egg_preference.php -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
.content {
  max-width: 500px;
  margin: auto;
}
</style>
<body>
<div class="content">
    <h1>Welcome, <?php echo $_POST["name"];?></h1>
    <h2> Here is your <?php echo $_POST["action"]; ?> egg.<h2>
    <?php if($_POST['action']=='Fried') : ?>
        <img src="Egg pictures/egg fried.jpg">
    <?php elseif($_POST['action']=='Hard Boiled') : ?>
        <img src="Egg pictures/egg hard boiled.jpg">
    <?php elseif($_POST['action']=='Poached') : ?>
        <img src="Egg pictures/egg poached.jpg">
    <?php elseif($_POST['action']=='Scrambled') : ?>
        <img src="Egg pictures/egg scrambled.jpg">
    <?php elseif($_POST['action']=='Soft Boiled') : ?>
        <img src="Egg pictures/egg soft boiled.jpg">
    <?php elseif($_POST['action']=='Omelette') : ?>
        <img src="Egg pictures/omelette.jpg">
    <?php elseif($_POST['action']=='Set free') : ?>
        <img src="Egg pictures/free egg.jpg">
    <?php endif; ?>

    <p>I don't like it <br></p>
    <a href="Og egg page.html"><p>Take me back to original egg </p></a>
    </div>
</body>
</html>

Starting the Web server and accessing created webpages

The XAMPP Control Panel is used to start the Apache component. The XAMPP dashboard can accessed by typing http://localhost/dashboard in the address bar of any web browser.

The created webpages can be accessed by typing the following format in the address bar:

http://localhost/<address of file, starting from htdocs>
Created websites, as accessed via the web server:
An instance of the webpage created in HTML, running in Google Chrome browserAn instance of the webpage created in PHP, running in Google Chrome browser

Working in a MySQL database with XAMPP

MySQL is one of the most popular database management systems, which can organize and store data of many types, such as text, numerical information, dates, and also JSON.

A MySQL database can be easily built using the XAMPP Control Panel. The MySQL module has to be started, along with the Apache module.
The XAMPP Control Panel, where the Apache and MySQL modules have been started
Use the Admin button in the MySQL to access the Admin page of the XAMPP server. Then navigate to the phpMyAdmin page.

Create the MySQL database by choosing the Database option from the drop-down menu.
Creating a MySQL database using XAMPP
In the Structure tab, the user can find the option to create a Table, with a specified name, number of columns and so forth.
Creating table in MySQL database
After creating the Table, the user can save the database, for future perusal and use. With a tool like XAMPP, the use of MySQL is further simplified, and accessibility is increased.

Categories
Programming Python

Integrating OpenCV with a Tkinter GUI in Python

OpenCV is a pretty handy tool while working with image processing and computer vision. It’s a large open-source library which can be accessed in a variety of programming languages, including Python. It has also been used for video analysis and real-world applications like CCTV footage analysis. 
OpenCV can be easily installed via the command console, to be used in various capacities while programming in Python.

To use the various packages included in OpenCV, we can install it using pip, via the command,

pip install opencv-python

PIL (Python Imaging Library) is another useful open-source library which supports opening and using various image formats. By installing PIL as well, we can further improve our ability to integrate OpenCV packages in out programs.
We can install PIL using the command:

pip install Pillow

A simple GUI utilizing tkinter is in general, more user-friendly and simpler to use. Hence, we can integrate OpenCV based programs with a tkinter GUI for easier access of end product.
Tkinter can be installed with the command,

pip install tk

To demonstrate, we can create a Python program which utilizes an OpenCV package to open the user’s webcam. The user can then get the RGB codes of various regions in the captured feed via a tkinter GUI.

To begin, we have to import the various packages to be used, from OpenCV, Tkinter and PIL

import cv2
from tkinter import *
from PIL import Image, ImageTk

VideoCapture() is the function in package cv2 which can open a camera for video capturing, whereas the cvtColor() function converts the colourspace of the image provided. Here the first frame from the video feed is provided to be converted to RGB. 

vc = cv2.VideoCapture(0)
cv2image= cv2.cvtColor(vc.read()[1],cv2.COLOR_BGR2RGB)

In the GUI, buttons and labels are created to facilitate turning on the camera with user’s permission, and displaying the pixel data when any region in the video feed is clicked.

window = Tk()
window.title("Video feed")
window.geometry("1200x700")
button = Button(window,text="Click to open camera")
button.grid(row=0, column=0)
label = Label(window, height=500, width=650, text="Video feed here")
label.grid(row=1, column=1, columnspan=1)
label_pix1 = Label(window, height=5, width=30, text="Pixel Location: ")
label_pix1.grid(row=2, column=0)
label_pix2 = Label(window, height=5, width=30, text="Pixel colour scheme (RGB): ")
label_pix2.grid(row=2, column=1)
label_pix3 = Label(window, height=5, width=30, text="Pixel colour scheme (HexCode): ")
label_pix3.grid(row=2, column=3)

Two functions are created to implement these roles.
Show_frames() displays the video feed from the webcam.
At a set interval, a frame from the webcam feed is set as a PhotoImage object (from the PIL package) and updated in the GUI.

def show_frames():
      global cv2image
      cv2image = cv2.cvtColor(vc.read()[1],cv2.COLOR_BGR2RGB)
      img = Image.fromarray(cv2image)

      imgtk = ImageTk.PhotoImage(image = img)
      label.imgtk = imgtk
      label.configure(image=imgtk)
      label.after(20, show_frames)

Pixel_colour() updates the information regarding the clicked pixel, every time a new pixel is clicked in the video feed. Also, the pixel data is printed onto the console.

def pixelcolour(pix):
    print("Pixel location")
    print (pix.x, pix.y)
    label_pix1.config(text=f"Pixel Location: ({pix.x}, {pix.y})")
    print("RGB colour")
    print (cv2image[pix.x, pix.y])
    label_pix2.config(text=f"Pixel colour scheme (RGB): {cv2image[pix.x, pix.y]}")
    print("Hex colour")
    bgr_list = cv2image[pix.x, pix.y].tolist()
    hex_str="#"
    for i in reversed(bgr_list):
         hex_str+=f"{hex(i)[2:]}"
    print(hex_str)
    label_pix3.config(text=f"Pixel colour scheme (RGB): {hex_str}")

Setting the function to the button and the label in the GUI, and setting the mainloop for the window,

button.config(command=show_frames)
label.bind("<Button-1>", pixelcolour)
window.mainloop()

Running the program, a window is opened with a clickable button, which opens up the user’s webcam.
Click anywhere in the video feed et voila! Data about the selected pixel is displayed, which includes its position and colour scheme in RGB.

Working demonstration wherein python program opens webcam. Clicking anywhere will provide the pixels location in colour scheme in Hex code and RGB