Saturday, 16 March 2024

OpenCV: Face detection

In this post, I am going to use Haar Cascade Classifiers, to detect the faces in an Image. Haar Cascade Classifiers are machine learning models that have been trained to recognize specific objects,

 

Step 1: Go to below location and download haarcascade_frontalface_default.xml file.

https://github.com/opencv/opencv/tree/master/data/haarcascades

 

'haarcascade_frontalface_default.xml' file is one of the pre-trained models provided by OpenCV for face detection.

 

Step 2: Get an instance of Haar cascade classifier.

 

haar_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')

In the above snippet, 'haarcascade_frontalface_default.xml' is the XML file that contains the pre-trained model for face detection.

 

Step 3: Detect faces.

faces_rectangle = haar_cascade.detectMultiScale(gray_scaled_image, scaleFactor=1.3, minNeighbors=1)

'detectMultiScale' method is used to detect objects (faces, in this case) in an image. Coordinates of the detected faces are stored in the variable ‘faces_rectangle’.

 

Signature

cv2.detectMultiScale(image, scaleFactor=1.1, minNeighbors=3, flags=0, minSize=None, maxSize=None)

 

Following table summarizes the parameters of detectMultiScale method.

 

Parameter

Description

image

Source image on which you want to detect the objects.

scaleFactor

Controls how much the image size is reduced at each image scale. Default value is 1.1, that means image size is redued by 10 percent.

minNeighbors

S ecifies how many neighbors each candidate object should have to retain it. A higher value means that the algorithm will be more selective in accepting detected objects.

A lower value might return more false positives.

flags

This is optional parameter. It gives you additional control over the object detection process.

minSize

This is optional parameter (width, height). Specify the minimum object size that detect should consider.

maxSize

This is optional parameter (width, height). Specify the maximum object size that the detector should consider.

 

Step 4: Draw a rectangle using the coordinates returned by 'detectMultiScale' method.

for (a, b, c, d) in faces_rectangle:
    cv.rectangle(image, (a,b), (a+c, b+d), color=(0, 255, 0), thickness=3)

Let’s work with below image to identify the faces

 

rrr.png



Find the below working application.

 

face_detection.py

 

import cv2 as cv

image = cv.imread('rrr.png')
gray_scaled_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

haar_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
faces_rectangle = haar_cascade.detectMultiScale(gray_scaled_image, scaleFactor=1.3, minNeighbors=1)
print(f'Total faces found {len(faces_rectangle)}')

for (a, b, c, d) in faces_rectangle:
    cv.rectangle(image, (a,b), (a+c, b+d), color=(0, 255, 0), thickness=3)

cv.imshow('image', image)

cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

 

Output

Total faces found 7

Total 7 faces are detected by the algorithm. Two foreground faces and one background face are correct, remaining faces are false positives.

 


 

How to address false positives?

By tweaking the parameters like minSize, minNeighbors etc., we can address false positives.

faces_rectangle = haar_cascade.detectMultiScale(gray_scaled_image, scaleFactor=1.3, minNeighbors=5, minSize=(110, 110))


a.   Set the scaleFactor to 1.3

b.   minNeighbors to 5

c.    minSize to (110, 110)

 

Above statement identifies 2 faces.



 


Previous                                                    Next                                                    Home

Tuesday, 12 March 2024

Column vs row oriented Databases

One of the ways to classify databases is by how the data is stored on disk: row- or column-wise. Tables can be partitioned either horizontally (storing values belonging to the same row together), or vertically (storing values belonging to the same column together).

 

Row-oriented databases

Row-oriented database management systems store data in records or rows. Their layout is quite close to the tabular data, xls sheet representation, where every row has the same set of fields.

 

Data is organized into tables and rows

a. Data is organized into tables, similar to spreadsheets. Each table represents a specific category of information, like "Customers" or "Orders."

 

b. Each row in a table represents a single record or data entry. A row holds all the attributes (columns) associated with that particular record.

 

For instance, a row-oriented database can effectively manage employee records, containing information such as names, cities, ages, birth dates, phone numbers, and more.

| id | name           | city          | age | birth_date | phone_number    |
|----|----------------|---------------|-----|------------|-----------------|
| 1  | John Doe       | New York      | 35  | 1989-05-21 | +1 (555) 123456 |
| 2  | Alice Lee      | Los Angeles   | 28  | 1996-12-10 | +1 (555) 987654 |
| 3  | Emily Smith    | Chicago       | 40  | 1982-08-03 | +1 (555) 246810 |
| 4  | Michael Johnson| Houston       | 45  | 1977-03-15 | +1 (555) 135790 |
| 5  | Sarah Brown    | San Francisco | 32  | 1992-09-28 | +1 (555) 369258 |

How to data is stored in row oriented databases?

Data for a single row is typically stored contiguously on disk. This means all the values belonging to a particular record (from different columns) are placed as close together as possible on the storage medium.

 

When data for one row is stored contiguously on a disk, it means that all the information related to that row, like a person's name, age, or city, is kept close together. This organization helps the computer quickly find and access all the details for a single entry, like a person's record in a database.

 

Benefits of row oriented database

1. Quick Retrieval of Entire Rows: Row-oriented databases make it easy to fetch complete records because all the data for a row is stored together. This is great when you need to find specific information about something, like looking up a employee’s details using their ID.

 

2. Faster Updation of Records: When you need to change something in a record, like updating an employee's name, city and age, row-oriented databases make it straightforward. You just need to make changes to the entire row where the data is stored, which is simple because everything is already together.

 

3. Smooth Transaction Processing: Row-oriented databases are also good for handling transactions, like when you're buying something online and your purchase needs to be recorded. They handle these kinds of tasks efficiently, making sure your transactions are processed quickly and accurately.

 

Drawbacks of Row-Oriented Storage

1. Slow when Aggregating Columns: If you're trying to do something like finding the average age of all the employees, row-oriented databases might not be the best choice. They have to look through every row to find the information you need, which can take longer because the data is spread out.

 

2. Compression Isn't as Good: Row-oriented databases have trouble compressing data efficiently because they store different types of information, like numbers and text (name, age, city, id etc.,), all mixed together. This can make them take up more space compared to databases that store similar types of data together.

 

3. Might Not Handle Big Data Analysis Well: If you're working with really big sets of data and need to do complicated analysis involving lots of different columns, row-oriented databases might not be up to the task. They will struggle with these kinds of complex jobs, leading to slower performance compared to databases designed specifically for this type of work.

 

In summary, Row-oriented databases are proficient at handling complete records, while column-oriented databases may deliver superior performance for tasks requiring extensive aggregation or analysis across specific columns. The optimal choice between these database types hinges on your unique data access patterns and query needs.

 

 

Column Oriented databases

Column-oriented database management systems organize data vertically, meaning by column rather than by row. In this arrangement, values within the same column are stored sequentially on disk, contrasting with the contiguous storage of rows seen in row-oriented databases.

 

Similar to row-oriented databases, data in column-oriented systems is structured into tables, yet the internal storage methodology differs significantly. Instead of each record having its own row, the data for each column is grouped and stored together.

 

For instance, take an employee table with columns for id, name, age, city, birth date, and phone number. In a column-oriented database, all the ids would be stored together, followed by all the names, and so forth. These groupings of individual column data are often referred to as column chunks or segments.

 

For example, let’s take same employee table.

| id | name           | city          | age | birth_date | phone_number    |
|----|----------------|---------------|-----|------------|-----------------|
| 1  | John Doe       | New York      | 35  | 1989-05-21 | +1 (555) 123456 |
| 2  | Alice Lee      | Los Angeles   | 28  | 1996-12-10 | +1 (555) 987654 |
| 3  | Emily Smith    | Chicago       | 40  | 1982-08-03 | +1 (555) 246810 |
| 4  | Michael Johnson| Houston       | 45  | 1977-03-15 | +1 (555) 135790 |
| 5  | Sarah Brown    | San Francisco | 32  | 1992-09-28 | +1 (555) 369258 |

In a column-oriented database, the data from the employee table  would be stored differently compared to a row-oriented database. Each column's data would be stored together in contiguous segments. Here's how it would look:

1: John Doe; 2: Alice Lee; 3: Emily Smith; 4: Michael Johnson; 5: Sarah Brown (Name Column)

1: New York; 2: Los Angeles; 3: Chicago; 4: Houston; 5: San Francisco (City Column)

1: 35; 2: 28; 3: 40; 4: 45; 5: 32 (Age Column)

1: 1989-05-21; 2: 1996-12-10; 3: 1982-08-03; 4: 1977-03-15; 5: 1992-09-28 (Birth Date Column)

1: +1 (555) 123456; 2: +1 (555) 987654; 3: +1 (555) 246810; 4: +1 (555) 135790; 5: +1 (555) 369258 (Phone Number Column)

Each column's data is stored contiguously, allowing for efficient retrieval and processing of columnar data.

 

Let’s calculate average age of all the employees in column oriented database

Since the age data is stored contiguously in its own segment, the database system can efficiently process only the age column to calculate the average age. This process involves iterating through the age values and computing the average directly from the stored data, without needing to access any other columns or unnecessary records. This approach significantly improves the performance of such analytical queries compared to row-oriented databases, where scanning all records may be necessary.

 

Benefits of column oriented databases

1. Quick Aggregation for Columns: Column-oriented databases excel in aggregating data across specific columns because all the information for each column is stored together. Tasks like finding the total, average, or count of values become much faster since the database only needs to look through a single, continuous set of data for that particular column. This is particularly useful for applications that need to analyze large amounts of data, like data warehouses or analytics tools.

 

2. Effective Data Compression: Storing similar data types together in each column chunk makes it easier to compress the data efficiently. Column-oriented databases can use advanced compression techniques tailored to the specific data types within each column, resulting in significant reductions in storage space needed.

 

3. Better Performance for Queries: Column-oriented databases often perform better when handling complex queries and large volumes of data. The way they organize and access data makes queries run faster, improving the overall speed and responsiveness of the database system.

 

Drawbacks of column oriented databases

1. Slower Retrieval of Entire Rows: Getting all the data for a complete record (row) can take longer in column-oriented databases compared to row-oriented ones. This is because the database has to gather data fragments from different parts of the storage to put together a full row.

 

2. Complicated Updates: Changing information in a single record involves updating multiple column chunks. This makes updates more complicated compared to row-oriented databases, where you only need to modify one row.

 

3. Less Effective for OLTP Work: Column-oriented databases might not work as well for tasks like Online Transaction Processing (OLTP), where lots of individual transactions need to be quickly recorded and managed. The way the database is set up for analyzing data can make these kinds of transactions slower compared to databases designed specifically for them.

 

In summary, column-oriented databases excel in data warehousing and analytics, offering superior performance for aggregations and filtering by specific columns. Conversely, for tasks necessitating frequent access to complete records, row-oriented databases may prove more suitable. Ultimately, the optimal choice lies on the nature of your workload and query patterns.



 

 

                                                  System Design Questions

Monday, 11 March 2024

PlantUML: Cusotmize colors, fonts in state diagram using skinparam command

customizeUsingSkinParam.txt

@startuml

skinparam backgroundColor LightBlue

skinparam state {
	StartColor PaleGreen
	EndColor brown
	BackgroundColor gold
	BackgroundColor<<automated>> aqua
	BackgroundColor<<last>> pink
	BorderColor Gray
	FontName Impact
}

left to right direction

state state1 <<automated>>
state state2 
state state3
state state4
state state5 <<last>>

[*] --> state1
state1 --> state2
state2 --> state3
state3 --> state4
state4 --> state5
state5 --> [*]


@enduml

 

Above snippet generate below command.

 


Previous                                                    Next                                                    Home

PlantUML: add inline color to the states in state diagram

Using #color notation, we can apply colors to the state diagram.

inlineColor.txt

@startuml

left to right direction

state state1 #FF9876
state state2 #lightblue
state state3 #palegreen
state state4 #brown
state state5 #magenta

[*] --> state1
state1 --> state2
state2 --> state3
state3 --> state4
state4 --> state5
state5 --> [*]


@enduml

Above snippet generate below diagram.

 


 

You can apply two colors on the state to get color gradient affects.

 

colorGradient.txt

@startuml

left to right direction

state "initialization state" as state1 #red-green
state "running state" as state2 #green|blue

[*] --> state1
state1 --> state2
state2 --> [*]


@enduml

Above snippet generate below diagram.



  

Previous                                                    Next                                                    Home

PlantUML: add note on links in state diagram

Using ‘note on link’ command, we can put notes on the links.

Example 1

state1 --> state2
note on link : This is note 1

 

Example 2 : multi line note

state2 --> state3
note on link
This is multi line
note using note on link
command
end note

noteOnLink.txt

@startuml

left to right direction

[*] --> state1
state1 --> state2
note on link : This is note 1

state2 --> state3
note on link
This is multi line
note using note on link
command
end note

state3 --> [*]

@enduml

Above snippet generate below diagram.




 

Previous                                                    Next                                                    Home

How an in-memory database achieve durability?

 

Durability in ACID and DBMS means that once you finish a transaction, the changes you made to the database persist always even if something goes wrong with the computer. Basically, your data stays safe even if the system crashes or the power goes out.

 

How in-memory systems achieve durability?

In-memory database management systems primarily store data in memory and utilize disk for recovery and logging purposes.

 

Examples

H2 Database: H2 is a Java-based open-source relational database management system. It supports both in-memory databases and persistent disk-based databases. H2 offers features such as ACID transactions, SQL support, and compatibility with other database systems. It finds applications in embedded systems, testing environments, and small to medium-sized applications.

 

Apache Derby: Apache Derby is an open-source relational database management system implemented in Java. It supports both in-memory databases and persistent disk-based databases. Derby is fully transactional and supports SQL queries, stored procedures, and triggers. It is commonly used in embedded systems, desktop applications, and small-scale web applications.

 

Here are some common techniques used by in-memory databases to achieve durability.

 

1. Write Ahead Logging (WAL)

Write-ahead logging (WAL) is a method used in databases to ensure that changes to data stay even if the system crashes, which is important for maintaining durability, a key aspect of database reliability.

 

In WAL, every change made to the database is first recorded in a log file on the disk before it's applied to the actual data in the system's memory(disk). This log file keeps track of all the transactions, serving as a backup that can be used to recover data if there's a crash.

 

WAL is also known as a transaction log, indicating that a transaction is considered complete only when the data is safely written into this log. WAL provides a way to replay transactions, allowing the database to be restored to a consistent state after a failure.

 

Here's how it operates:

WAL Log: The database system maintains a dedicated file known as the Write-Ahead Log (WAL), which records all changes.

 

Log First: Before any changes are made to the actual data, they're first recorded in the WAL. This ensures that the log accurately reflects the intended updates.

 

Durability Assurance: The WAL is stored in stable storage, usually the disk, guaranteeing that the log persists even if there's a crash during the update process.

 

Recovery from Crashes: If the system crashes, the database can use the WAL to recover. It replays the log entries, redoing the intended changes to bring the database back to a consistent state reflecting the last committed transactions.

 

Advantages of WAL

Since data updates aren't immediately written to the main database files, WAL enables quicker write operations. The actual data updates happen periodically based on some dbms configuraitons.

 

Addressing Concerns of Infinite Growth: Managing Transaction Logs in WAL

Continuously writing all transactions to a single WAL file would result in an ever-expanding and eventually unmanageable file size. Here are a few methods used by databases to effectively handle WAL size:

 

Checkpointing: Databases regularly execute checkpoints. During a checkpoint, all pending changes in the WAL are applied to the main data files. This essentially tidies up the WAL by eliminating entries that are no longer necessary for recovery. Checkpoints ensure the WAL doesn't grow excessively large.

 

Segmentation: Some systems utilize segmented WALs. Instead of one large file, the WAL is split into multiple segments. Once a segment reaches a specific size limit, it's either archived or recycled. This prevents the entire WAL from becoming unwieldy.

 

By employing these strategies, databases can maintain a manageable size for the WAL while still ensuring data durability through write-ahead logging.

 

2. Periodic Snapshots to Disk

Another method is to regularly take the snapshots of the data that's stored in the computer's memory and save them on the hard drive. This helps if something goes wrong and the system crashes. You can use these snapshots to get the database back to how it was when the last snapshot was taken.

 

3. Battery-backed RAM (BBRAM)

BB-RAM is like regular memory (RAM) in your computer but with a small battery attached to it. The RAM stores all the information while your computer is on, and if the power suddenly goes out, the battery kicks in to keep that information safe. Some systems use both RAM and battery-backed hardware to make sure your data stays safe. They store the data in fast-access RAM at first, but then regularly save it onto more permanent storage, like a solid-state drive (SSD) or hard disk drive (HDD), using the battery's power.

                                                  System Design Questions