Tuesday, 13 February 2024

Role of indexing in Databases

Indexing in databases is like using a book's index to find information quickly. Instead of searching every page, you just look up a word in the index and go straight to the page you need.

 

Similarly, in a database, an index is a special data strcuture that helps to find information faster. It keeps track of the values in certain columns and where they are in the database. So, when you ask the database for specific information, it can use the index to find it quickly without searching through everything.

 

Let's delve deeper into indexing by exploring how data is stored on a disk.

In the computer world, understanding disks, tracks, and sectors is key to grasping how data is physically stored and retrieved.

 

Disk

Disks are like flat, circular plates coated with a magnetic or optical material. These plates spin fast, and data is stored in small magnetized or etched areas on their surface. Traditional hard disk drives (HDDs) use magnetic plates, while solid-state drives (SSDs) use flash memory chips.

 

Tracks

Tracks are akin to the concentric grooves on a record album. They're thin, circular bands on the disk surface where data is stored. More tracks mean more storage capacity.

 

Sector

A sector is the smallest storage unit on a hard disk or similar device. It's usually a fixed-size portion of the disk surface that can be read or written in one I/O operation. Sectors are typically 512 bytes or 4 KB in modern disk drives. They're fundamental for addressing data on a disk.

 


 

Block

Block refers to a group of adjacent sectors on a disk. Operating systems often combine sectors into these larger blocks for efficiency reasons. Reading and writing large data chunks at once is faster than accessing individual sectors. Block sizes can vary depending on the file system and disk format, but they're generally much larger than sectors (e.g., 4KB, 8KB, or more).

 

So, if you hear "block" in a disk context, consider the context to know if it means the same as a sector or a larger group of sectors. It's best to use "sector" for the smallest unit and clarify if you're talking about a group of sectors as a "block."

 

Above diagram depicts how a track, sector and blocks looks like. There are 5 track, where each track has 8 sectors.

 

 

Let's understand the significance of indexing using an example of an employee table.

 

To illustrate, let's assume a block size of 512 bytes.

 

id

name

email

city

country

age

1

krishna

krishna@demo.com

Bangalore

India

34

2

Ram

ram@demo.com

Bangalore

Hyderabad

31

 

 

 

 

 

 

 

 

 

 

 

 

 

Let's compute the size of each row in bytes:

 

1.   id: 4 bytes

2.   name: 40 bytes

3.   email: 40 bytes

4.   city: 20 bytes

5.   country: 20 bytes

6.   age: 4 bytes

 

Total row size = 128 bytes.

 

Given a block size of 512 bytes, we can accommodate 512/128 = 4 rows in a block.

 

Now, let's determine the time required to read an employee with a specific ID.

 

Considering we have 400 employee records, and each block can hold 4 employee records, all 400 employee records are distributed across 400/4 blocks = 100 blocks.

 

In the worst-case scenario, locating an employee with a given ID may necessitate scanning through all 100 blocks.

 

With indexing

Let's develop an index data structure to quickly find an employee using their ID. We'll create an index that includes two columns:

a.   id and

b.   a pointer to the record's location on the disk.

 

id

pointer_to_a_record_on_the_disk

 

 

 

 

 

 

 

 

 

 

 

For every employee record, we'll create an entry in the index. Since the index is also stored on the disk, let's determine how many blocks are needed for the index.

 

First, let's calculate the size of each index row in bytes:

 

1.   id: 4 bytes

2.   pointer: 8 bytes

So, each entry size is (4 + 8) = 12 bytes.

 

A block with a size of 512 bytes can accommodate (512/12) = 42.6 rows, which rounds down to 42 rows (using the floor value).

 

Thus, each block can contain 42 index rows. To store 400 index rows, we need (400 /42) = 9.52, which rounds up to 10 blocks (using the ceiling value).

 

In the worst-case scenario, to find an employee with a given ID, we may need to scan 10 indexing blocks (where the indexes are stored). Once we obtain the address of the record, we can read the actual data block containing the exact data. Therefore, by scanning a total of 11 blocks (10 indexing blocks + 1 data block), we can retrieve the desired record efficiently. Without indexing, we might need to scan all 100 blocks.

 

We'll delve into more detail about multi-level indexing and B-Trees in subsequent posts.


                                                  System Design Questions

Monday, 12 February 2024

OpenCV: Compute histogram for pixel intensities in a grayscale image

 

Using histogram, we can visualize the distribution on pixel intensities in an image.

 

Using cv2.calcHist method, we can compute histogram from an image or specific portion of the image.

 

Why histogram needed?

Using histogram, we can visualize the distribution on pixel intensities in an image.

 

Signature

cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])

 

Following table summarizes the parameters of calcHist method.

 

Parameter

Description

images

It is a list of source images from which you want to calculate the histogram.

channels

Specifies which color channels of image you want to consider while calculating histogram.

 

For a grayscale image, it is set to [0].

 

For a BGR image, you can specify [0], [1], or [2] for the blue, green, and red channels.

mask

It is used to calculate histogram for specific region in the image. This is set to None, if you want to calculate histogram for entire image.

histSize

Specifies number of bins in the histogram.

ranges

Specify range of pixel values in each channel.

 

For grayscale images, it is usually [0, 256] to cover the full range of pixel values.

 

For color images, you might use [0, 256] for each channel.

hist

This is optional, specifies an output parameter where the calculated histogram is stored

accumulate

This is optional parameter. If set to True, the histogram is not cleared in the beginning but is accumulated. This can be useful when you want to calculate histograms for multiple images and accumulate them.

 

Example

image = cv.imread('sea_animals.jpeg')
grayscale_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
gray_histogram = cv.calcHist([grayscale_image], [0], None, [256], [0, 256])

 

Above snippet calculate the histogram for a grayscale image.

 

Original image 

 


Find the below working application.

 

gray_scale_image_histogram.py

import cv2 as cv
import matplotlib.pyplot as plt

image = cv.imread('sea_animals.jpeg')
grayscale_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

cv.imshow('Image', image)
cv.imshow('grayscale_image', grayscale_image)

# Compute grayscale histogram
gray_histogram = cv.calcHist([grayscale_image], [0], None, [256], [0, 256])

plt.title('Histogram for Grayscaled imaged')
plt.xlabel('bins')
plt.ylabel('Number of Pixels')
plt.xlim([0, 256])
plt.plot(gray_histogram)

plt.show()
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output

 

Gray scale image


 

Histogram

 


 

Let’s create a histogram for specific portion using mask parameter.

 

Create a mask and use it while calculation histogram.

blank_image = np.zeros(image.shape[:2], dtype='uint8')
mask = cv.rectangle(blank_image, (50, 50), (350, 350), color=255, thickness=-1)

# Compute grayscale histogram
gray_histogram = cv.calcHist([grayscale_image], [0], mask, [256], [0, 256])

Find the below working application.

 

gray_scale_specific_region_histogram.py

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np

image = cv.imread('sea_animals.jpeg')
grayscale_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

blank_image = np.zeros(image.shape[:2], dtype='uint8')
mask = cv.rectangle(blank_image, (50, 50), (350, 350), color=255, thickness=-1)

# Compute grayscale histogram
gray_histogram = cv.calcHist([grayscale_image], [0], mask, [256], [0, 256])

cv.imshow('Image', image)
cv.imshow('grayscale_image', grayscale_image)
cv.imshow('mask', mask)

plt.title('Histogram for Grayscaled imaged')
plt.xlabel('bins')
plt.ylabel('Number of Pixels')
plt.xlim([0, 256])
plt.plot(gray_histogram)

plt.show()
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output




 


Previous                                                    Next                                                    Home

Masking images in OpenCV

In this post, I am going to explain how to extract specific portion of the image using masking technique.

 

Following snippet is used to extract the image of intrest using masking technique.

panda_image = cv.imread('panda.png')

blank_image = np.zeros(panda_image.shape[:2], dtype='uint8')
masked_image = cv.circle(blank_image, (400, 500), 400, color=255, thickness=-1)

result_after_masking = cv.bitwise_and(panda_image, panda_image, mask=masked_image)

 

In summary, the code loads an image of a panda, creates a blank image with a filled white circle, and then uses the circle as a mask to extract and display the panda image content only within the circular region.

 

Let's break down the provided lines of code step by step:

panda_image = cv.imread('panda.png')

read an image file named 'panda.png' and load it into the variable `panda_image`.

 

blank_image = np.zeros(panda_image.shape[:2], dtype='uint8')

Above snippet creates a black image with the same dimensions as the panda image.

 

masked_image = cv.circle(blank_image, (400, 500), 400, color=255, thickness=-1)

Above statement draws a filled white circle on the `blank_image`

 

result_after_masking = cv.bitwise_and(panda_image, panda_image, mask=masked_image)

Above statement perform the 'and' operation between the `panda_image` and itself, and using `masked_image` as the mask

 

Find the below working application.

 

mask_image.py

import cv2 as cv
import numpy as np

# Read the image as matrix of pixels
panda_image = cv.imread('panda.png')

blank_image = np.zeros(panda_image.shape[:2], dtype='uint8')
masked_image = cv.circle(blank_image, (400, 500), 400, color=255, thickness=-1)

result_after_masking = cv.bitwise_and(panda_image, panda_image, mask=masked_image)

# Display the image in new window
cv.imshow('panda_image', panda_image)
cv.imshow('masked_image', masked_image)
cv.imshow('result_after_masking', result_after_masking)

# Wait for Infinite amount of time for a keyboard key to be pressed
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output

Original image


 


Circle


 


Masked image

 


 

Previous                                                    Next                                                    Home

How a data catalog ensures data Governance?

 Data governance refers to the system and practices an organization uses to effectively manage its data. It covers everything from establishing rules and standards to ensure only authorized individuals access the data, as well as maintaining its accuracy and reliability. The main aim is to get the most out of the data while reducing any risks of misuse.

 

Main Goals of Data Governance

1.   Data quality: Making sure data is correct, complete, consistent, and dependable.

2.   Data security: Safeguarding data from unauthorized access, use, disclosure, disruption, alteration, or destruction.

3.   Data accessibility: Providing access to data for those who need it while keeping it secure and governed.

4.   Data compliance: Following industry regulations and internal rules.

5.   Data Stewardship: Assigning responsibility for specific data to designated individuals or teams (data stewards) who manage and maintain its quality, integrity, and security.

 

It's important to note that data governance is an ongoing process that requires continual adaptation as the organization and its data environment change.

 

How a Data Catalog Supports Data Governance

Data catalogs don't directly govern data, but they provide essential tools that support in implementing and maintaining effective data governance practices. They empower individuals and teams to manage data efficiently.

 

For instance, a data catalog helps in:

1.   Identifying Issues: By tracking data from its source to its destination, data catalogs can uncover biases, errors, and compliance risks. This accountability ensures that everyone follows data governance policies.

2.   Enforcing Access Controls: Data catalogs integrate with access control systems, and allow administrators to set and enforce access permissions based on data sensitivity and user roles. This ensures that only authorized personnel access and modify data, maintaining security.

3.   Ensuring Compliance: When regulations require specific data fields to be masked for privacy, data catalogs assist in identifying relevant datasets, automating masking processes, and restricting access to sensitive information, ensuring compliance.

4.   Tracking Changes: Data catalogs keep a record of changes made to data assets, helping maintain data integrity and troubleshoot potential issues.

5.   Centralizing Data Management: By serving as a centralized repository for all data assets, data catalogs document each dataset with detailed metadata, including its source, owner, quality metrics, and usage guidelines. This helps clarify ownership and usage protocols, reducing confusion.

For example, in a retail company with vast data spread across departments, a data catalog provides clarity on ownership and usage guidelines. Similarly, a financial services company uses metadata tags in the data catalog to establish access controls and usage policies for sensitive data elements, ensuring regulatory compliance.

 

Overall, data catalogs facilitate collaboration, transparency, and adherence to data governance principles, making data management more efficient and reliable for organizations.

Previous                                                 Next                                                 Home