0% found this document useful (0 votes)
19 views25 pages

Ivalab

The document contains various image processing programs using OpenCV and NumPy, including T-Pyramid computation, Quad Tree representation, geometric transformations (rotation, scaling, skewing, affine, bilinear), and object detection. Each section includes code snippets that demonstrate how to manipulate images, such as resizing, transforming, and displaying images, along with explanations of the processes involved. The programs also handle image loading, error checking, and visualization of results using OpenCV and Matplotlib.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views25 pages

Ivalab

The document contains various image processing programs using OpenCV and NumPy, including T-Pyramid computation, Quad Tree representation, geometric transformations (rotation, scaling, skewing, affine, bilinear), and object detection. Each section includes code snippets that demonstrate how to manipulate images, such as resizing, transforming, and displaying images, along with explanations of the processes involved. The programs also handle image loading, error checking, and visualization of results using OpenCV and Matplotlib.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

1.

COMPUTATION OF T-PYRAMID OF AN IMAGE

Program:

import cv2

import numpy as np

def T_pyramid(image, levels):

pyramid = [image]

for i in range(levels):

image = cv2.pyrDown(image)

pyramid.append(image)

return pyramid

image = cv2.imread(r'D:\meenu_rs\img1.jpg')

if image is None:

print("Error: Image not found.")

exit()

levels = 4

pyramid = T_pyramid(image, levels)

for i in range(len(pyramid)):

cv2.imshow(f'Level {i} T Pyramid', pyramid[i])

cv2.waitKey(0)

cv2.destroyAllWindows()

Meaning: cv2 and numpy modules import pannirukom. Ivanga


image processing-ku mukkiyam.
T_pyramid nu oru function define pannirukanga. Ithu oru image
ah eduthu, levels nu kudukkura count-ku ethaavadhu pyramid levels
generate pannum.

pyrDown() function use pannitu, image size ah sila thadava


reduce (downsample) pannum. Ivlo thadava panninalo, ella versions-
um oru list-la store pannitu return pannum.

Image path E:\nature.jpg la irukura oru image load


pannirukanga. Image correct-a load aagala na, error message print
aagum, program stop aagum.

levels = 4 nu kuduthurukanga, so 4 pyramid levels generate


pannum.

Function call pannitu pyramid list-a generate pannirukanga.

Pyramid la irukkura ella images-um one by one screen la


kaamikka cv2.imshow() use pannirukanga.

User key press pannum varaikkum window close aagaadhu


(waitKey(0)), apram ella windows um close panniranga
(destroyAllWindows()).

2.QUAD TREE REPRESENTATION OF AN IMAGE USING


HOMOGENEITY CRITERION OF EQUAL INTENSITY

Program:
import cv2

import numpy as np

import matplotlib.pyplot as plt

img = cv2.imread(r'D:\iva\tree.webp')

def split4(image):
top_bottom = np.array_split(image, 2)

return [np.array_split(part, 2, axis=1) for part in top_bottom]

def flatten_split(parts):

return [part for row in parts for part in row]

def combine4(nw, ne, sw, se):

top = np.hstack((nw, ne))

bottom = np.hstack((sw, se))

return np.vstack((top, bottom))

def mean_color(image):

return np.mean(image, axis=(0, 1)).astype(int)

def is_uniform(image):

return (image == image[0, 0]).all()

class QuadTree:

def insert(self, image, level=0):

self.level = level

self.mean = mean_color(image)

self.size = image.shape[:2]

self.leaf = is_uniform(image)

if not self.leaf:

parts = flatten_split(split4(image))

self.nw = QuadTree().insert(parts[0], level + 1)

self.ne = QuadTree().insert(parts[1], level + 1)

self.sw = QuadTree().insert(parts[2], level + 1)

self.se = QuadTree().insert(parts[3], level + 1)

return self
def get_image(self, target_level):

if self.leaf or self.level == target_level:

return np.tile(self.mean, (*self.size, 1))

return combine4(

self.nw.get_image(target_level),

self.ne.get_image(target_level),

self.sw.get_image(target_level),

self.se.get_image(target_level)

parts = flatten_split(split4(img))

fig, axs = plt.subplots(2, 2)

for i, ax in enumerate(axs.flat):

ax.imshow(parts[i])

plt.show()

combined = combine4(*parts)

plt.imshow(combined)

plt.show()

means = np.array([mean_color(p) for p in parts]).reshape(2, 2, 3).astype(np.uint8)

print(means)

plt.imshow(means)

plt.show()

qt = QuadTree().insert(img)

for level in [1, 3, 7, 10]:

plt.imshow(qt.get_image(level))

plt.show()
Meaning:
1. Image Load Panradhu:
Computer-la irukra oru image file-ai eduthu appadiye use panna ready-aakkiradhu.

2. Image-a 4 Parts-a Split Panradhu:


Image-a rendu horizontal halves-aaga split pannuvom. Aparam, a halves-ai rendu
vertical halves-aaga split pannuvom. So, total 4 parts-aagum — top-left, top-right,
bottom-left, bottom-right.

3. 4 Parts-a Oru List-a Convert Panradhu:


Split pannina 2D list (2 rows with 2 parts each) single flat list-a convert pannuvom,
4 separate parts oda.

4. 4 Parts-ai Serthu Oru Image-a Create Panradhu:


4 image parts-a horizontal and vertical-a serthu, original image mathiri oru image
create pannuvom.

5. Oru Part-oda Average Color Calculate Panradhu:


Oru part-la irukra ellaa pixels-um eduthu, avangaloda average (mean) color-a
calculate pannuvom.

6. Part Ellaa Pixelsum Same Color-aa Irukka Check Panradhu:


Part-la ellaa pixels-um same color-a irukka check pannuvom. Adhu true-na, andha
part leaf node-nu artham.

7. QuadTree Structure Create Panradhu:


Image-a recursively 4 parts-a split pannitu, each part leaf node-aa irukka check
pannuvom. Leaf node illa na, appadiye split pannitu tree structure-a build
pannuvom.

8. QuadTree-la Naan Decide Panna Level-ku Image Generate Panradhu:


Tree-la irukra nodes-la irundhu, oru target level-ku varai average colors use pannitu
image generate pannuvom. Level perundra bodhu, detail perugum.

9. 4 Parts-a Oru 2x2 Grid-la Display Panradhu:


Split pannina 4 parts-ai 2 rows and 2 columns-la display pannuvom.

10. 4 Parts-ai Serthu Original Image Display Panradhu:


Split pannina parts-ai serthu, original image mathiri display pannuvom.
11. 4 Parts-oda Average Colors-a 2x2 Grid-la Display Panradhu:
Parts-oda average colors-ai 2x2 color blocks mathiri display pannuvom. RGB values
print pannitu paakalam.

12. QuadTree-a Use Panni Different Levels-ku Image Generate Panni Display Panradhu:
QuadTree structure-a use panni, levels 1, 3, 7, 10-ku average color patches use
pannitu images generate pannuvom, adha display pannuvom. Level koranda podhu
image blurry, level perunda detail clear.

3a.GEOMETRIC TRANSFORMATION OF AN IMAGE –


ROTATION
Program
import cv2
img = cv2.imread(r'D:\meenu_rs\img1.jpg')
if img is None:
print("Error: Image not found")
exit()
rows, cols = img.shape[:2]
matrix_rotated = cv2.getRotationMatrix2D((cols / 2, rows / 2), 90,
0.6)
rotated_img = cv2.warpAffine(img, matrix_rotated, (cols, rows))
resized_img = cv2.resize(img, (800, 600))
resized_rotated_img = cv2.resize(rotated_img, (800, 600))
cv2.imshow("Original", resized_img)
cv2.imshow("Rotated", resized_rotated_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Meaning:

Image Read Pannuthu:


The code first tries to load an image from a specified path. If the image is not
found, it shows an error and stops further execution.

Image Rotation:
The image is rotated by 90 degrees. It calculates the center of the image and
rotates it around that center. The rotation is done with a specific scale (in this
case, 0.6), which reduces the image size while rotating.

Resize Pannuthu:
Both the original image and the rotated image are resized to a fixed size of
800x600 pixels to ensure that they are displayed clearly and consistently.

Image Display Pannuthu:


The original image and the rotated image are shown in separate windows. The
windows will remain open until a key is pressed.

Wait and Close Windows:


The program waits for the user to press any key. Once the key is pressed, all
the image display windows are closed.

3b. GEOMETRIC TRANSFORMATION OF AN IMAGE –


CHANGE OF SCALE
Program
import cv2
import numpy as np
img = cv2.imread(r'D:\meenu_rs\tree.jpg')
scaled_img = cv2.resize(img, None, fx=2.0, fy=3.0)
cv2.imshow("Original image",img)
cv2.imshow("Scaled image",scaled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Meaning:

Image Read: First, the image located at the path D:\meenu_rs\img1.jpg is


read using the cv2.imread function. This function loads the image into a
variable called img.

Scaling the Image: The image is then scaled (resized) to 50% of its original
size in both the x (horizontal) and y (vertical) directions using the cv2.resize
function. The fx parameter controls the scaling factor for the x-axis (width),
and fy controls the scaling factor for the y-axis (height). Here, both are set to
0.5, meaning the image will be resized to half its original width and height.

Displaying Images: After scaling, both the original and scaled images are
shown using cv2.imshow. The first window will display the original image,
and the second window will display the scaled image.

Waiting and Closing: The cv2.waitKey(0) function waits for any key to be
pressed, and once a key is pressed, the cv2.destroyAllWindows() function will
close the windows displaying the images.

3c. GEOMETRIC TRANSFORMATION OF AN IMAGE –


SKEWING

Program:
import cv2

import numpy as np
img = cv2.imread(r'D:\meenu_rs\img1.jpg')

rows, cols, _ = img.shape

pts1 = np.float32([[cols * 0.45, rows * 0.95], [cols * 0.90, rows * 0.95], [cols *
0.10, 0], [cols, 0]])

pts2 = np.float32([[cols * 0.1, rows], [cols, rows], [0, 0], [cols, 0]])

M = cv2.getPerspectiveTransform(pts1, pts2)

dst = cv2.warpPerspective(img, M, (cols, rows))

small_img = cv2.resize(img, (600, 400))

small_dst = cv2.resize(dst, (600, 400))

cv2.imshow('Original', small_img)

cv2.imshow('Transformed', small_dst)

cv2.imwrite('E:\My Zen Garden.jpg', dst)

cv2.waitKey(0)

cv2.destroyAllWindows()

Meaning:
First, oru image-ah read pannirukaanga system-la irundhu.

Appuram, andha image-oda height, width, channels nu eduthirukaanga.

Skew effect apply panna, rendu point sets define pannirukaanga:

• One set is the original points (source).


• Another set is the modified or target points (destination).
Ithu perspective transformation (skewing) matrix generate pannum.

Aparam, andha matrix use panni image-ah transform pannirukaanga, so it


looks tilted or skewed.

Display screen-la periya image varama irukka, rendu image-um (original +


skewed) resize pannirukaanga (600x400 pixels).

Ithu rendu image-ai oru window-la kaattum, and then user-oda key press-a
wait pannum.

Final-ah, transformed (skewed) image-ah save pannirukaanga specified


path-la.

3d. AFFINE TRANSFORMATION OF AN IMAGE FROM


THREE PAIRS OF CORRESPONDING POINTS
Program:
import cv2

import numpy as np

from matplotlib import pyplot as plt

img = cv2.imread(r'D:\meenu_rs\img1.jpg')

rows, cols, ch = img.shape

pts1 = np.float32([[50, 50], [200, 50], [50, 200]])

pts2 = np.float32([[10, 100], [200, 50], [100, 250]])

M = cv2.getAffineTransform(pts1, pts2)

dst = cv2.warpAffine(img, M, (cols, rows))

plt.subplot(121)

plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('Input')

plt.subplot(122)

plt.imshow(cv2.cvtColor(dst, cv2.COLOR_BGR2RGB))

plt.title('Output')

plt.show()

cv2.destroyAllWindows()

Meaning:

First, namma oru image-a read panrom.

Apparam, andha image-oda height (rows), width (columns), and color


channels extract panrom.

Next, moonu point pairs define panrom — original image-la irundhu three
points (source) and athukku correspond aagura three points (destination).

Ithu base pannindu, affine transformation matrix generate panrom.

Andha matrix use pannindu, transformation apply pannrom — ithu image-


a slightly move, skew, rotate panna use aagum.

Finally, original image-um transformed image-um side-by-side display


panrom using matplotlib.

Last-la, close panra actions irukku for clean up.

3e. BILINEAR TRANSFORMATION OF AN IMAGE FROM


FOUR PAIRS OF CORRESPONDING POINTS
Program:
import cv2

import numpy as np
img = cv2.imread(r'D:\meenu_rs\tree.jpg')

if img is None:

print("Image not found")

exit()

def bilinear_interp(img, x, y):

x1, y1 = int(x), int(y)

x2, y2 = x1 + 1, y1 + 1

if x2 >= img.shape[1] or y2 >= img.shape[0]:

return img[y1, x1]

dx, dy = x - x1, y - y1

tl = img[y1, x1].astype(np.float32)

tr = img[y1, x2].astype(np.float32)

bl = img[y2, x1].astype(np.float32)

br = img[y2, x2].astype(np.float32)

return ((1 - dx) * (1 - dy) * tl + dx * (1 - dy) * tr + (1 - dx) * dy * bl + dx * dy


* br).astype(np.uint8)

points = [(70, 90), (50, 60), (60, 70), (50, 20)]

for x, y in points:

val = bilinear_interp(img, x, y)

print(f"Value at ({x},{y}): {val}")

cv2.circle(img, (int(x), int(y)), 5, (0, 0, 255), -1)

cv2.imshow("Bilinear Interpolated Points", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

Meaning:

First, the image is loaded.

If the image isn't loaded correctly, it shows an error message.

Four points are defined on the image where we want to calculate the pixel
value.

For each of these points, it checks the neighboring pixels and calculates the
pixel value at that point using bilinear interpolation (based on four
surrounding pixels).

It then prints the interpolated pixel value for each point.

A red circle is drawn at each of the four points to mark them on the image.

Finally, the image with the points marked is shown on the screen.

4.OBJECT DETECTION AND RECOGNITION


Program:
import cv2

from matplotlib import pyplot as plt

img = cv2.imread(r"D:\iva\cat.webp")

if img is None:

print("Image not found.")

exit()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)


cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalcatface.xml")

if cascade.empty():

print("Cascade load failed.")

exit()

found = cascade.detectMultiScale(gray, 1.1, 3, minSize=(50, 50))

for (x, y, w, h) in found:

cv2.rectangle(rgb, (x, y), (x + w, y + h), (255, 0, 0), 3)

plt.imshow(rgb)

plt.axis('off')

plt.title("Object Detection - Cat Face")

plt.show()

print("Cat face(s) detected" if len(found) else "No cat face detected")

Meaning:
1. import cv2 and from matplotlib import pyplot as plt — Ithu OpenCV mathiri image
processing library-um, matplotlib-la image display panna use panra tool-um load
panrathu.

2. img = cv2.imread(r"D:\iva\cat.jpg") — Ithu "cat.jpg" file-ai load pannuthu, image


data-a img variable-la store pannudhu.

3. if img is None: ... — Image file correct-a load aagala na error message solli program-
a stop pannudhu.

4. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) — Original color image


(BGR) ah grayscale (black & white) image-a convert pannudhu. Grayscale image
easier-a analyze panna use aagum.

5. rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) — OpenCV images BGR format-


la irukkum, matplotlib RGB format-la expect panrathu, so color correct-a display
panna convert pannudhu.
6. cascade = cv2.CascadeClassifier(...) — Haar cascade file load pannudhu; ithu cat
face detect panna use aagum machine learning model.

7. if cascade.empty(): ... — Haar cascade file load aagala error solli program-a stop
pannudhu.

8. found = cascade.detectMultiScale(gray, 1.1, 3, minSize=(50, 50)) — Grayscale


image-la cat faces detect pannudhu. found-la detect panna rectangles coordinates
varum.

9. for (x, y, w, h) in found: — Detect panna cat face ellam rectangle draw pannudhu.

10. plt.imshow(rgb) and plt.show() — Rectangle oda image-a display pannudhu.

11. print(...) — Cat face detect aana message illa na detect aagala message print
pannudhu.

5.MOTION ANALYSIS USING MOVING EDGES


program:
import cv2, os

def motion_analysis(path):

if not os.path.isfile(path) or not cv2.VideoCapture(path).isOpened(): print(f"File error:


{path}"); return

cap = cv2.VideoCapture(path)

ret, prev = cap.read()

if not ret: return print("Error: Cannot read video.")

prev = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)

while True:
ret, frame = cap.read()

if not ret: break

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

diff = cv2.absdiff(gray, prev)

_, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)

cnts, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL,


cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(frame, cnts, -1, (0, 255, 0), 2)

cv2.imshow("Motion", frame)

if cv2.waitKey(25) & 0xFF == ord('q'): break

prev = gray

cap.release(), cv2.destroyAllWindows()

if __name__ == "__main__":

path = r"D:\iva\car1.mp4"; print(os.path.isfile(path)); motion_analysis(path)

Meanings:

1. First, program OpenCV and file-checking tools ah import pannudhu.

2. Next, neenga kudukkura video file path correct ah irukka check


pannum. File illa, illa open panna mudiyala na, error message kaatti stop
aagum.

3. Apparam, video open pannitu first frame ah read pannum. Adha gray
(black & white) color la maathidum. Ithu motion detect panna easy
aagum.

4. Ippo video la oru oru frame read pannum. Frame illa na video
mudinchu nu artham, so loop stop aagum.
5. Every new frame-um black & white la maathidum. Appo previous frame
kooda compare pannum to see edhavadhu maari irukka (like car move
aagiruchaa nu paakardhukku).

6. Difference irundha adha highlight pannum — like moving objects. Small


changes ah ignore pannum by threshold (minimum limit).

7. Motion detect aana area la green outline varum (contours draw


pannum).

8. Frame ah screen la kaattum with motion area highlight pannitu


irukkum. Neenga 'q' key press panna dhan video close aagum.

9. Video stop aana udane, program clean ah video file close pannidum,
screen um close aagum.

6.FACIAL DETECTION AND RECOGNITION

Program:
import cv2, numpy as np

f=cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')

kf=cv2.imread(r"D:\iva\face.jpg",0)

x,y,w,h=f.detectMultiScale(kf,1.1,5)[0]

kr=kf[y:y+h,x:x+w]

cap=cv2.VideoCapture(0)

if not cap.isOpened(): exit("No camera")

while 1:
ret,frame=cap.read()

if not ret: break

g=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

for (x,y,w,h) in f.detectMultiScale(g,1.1,5):

roi=cv2.resize(g[y:y+h,x:x+w],(w,h))

known_resized = cv2.resize(kr,(w,h)) # resize kr here

mse=np.mean(cv2.absdiff(roi,known_resized))

c,t=((0,255,0),'Yes') if mse<40 else ((0,0,255),'No')

cv2.rectangle(frame,(x,y),(x+w,y+h),c,2)

cv2.putText(frame,t,(x,y-10),0,0.7,c,2)

cv2.imshow('Face',frame)

if cv2.waitKey(1)&0xFF==ord('q'): break

cap.release()

cv2.destroyAllWindows()

Meaning:

Sure! Here’s a step-by-step explanation of your face recognition code:

1. Import Libraries

• cv2 for image and video processing

• numpy for numerical operations

2. Load Face Detector

• Load OpenCV’s pre-trained face detector using Haar Cascade XML file.
• This detector helps find faces in images or video frames.

3. Load Known Face Image

• Read an image file from disk (known_face.jpg).

• Check if the image was loaded successfully, else stop the program.

4. Detect Face in Known Image

• Convert the known face image to grayscale (because face detection


works better in grayscale).

• Use the face detector to find faces in the known image.

• If no face found in the known image, stop the program.

• Extract the coordinates (x, y, w, h) of the first detected face.

• Crop the face region from the known image to use as a reference.

5. Define Face Recognition Function

• For every video frame passed to this function:

o Convert frame to grayscale.

o Detect all faces in the frame.

o For each detected face in the frame:

▪ Extract the face region from the frame.

▪ Resize the known face crop to the same size as the detected
face region.

▪ Calculate the difference between the detected face and the


known face using pixel-wise subtraction (absdiff).
▪ Calculate the mean value of this difference (mse), a measure
of similarity.

▪ If the difference is below a threshold (meaning faces are


similar), draw a green rectangle and write "Recognized".

▪ Otherwise, draw a red rectangle and write "Unknown".

o Return the frame with the drawings and labels.

6. Open Camera

• Start capturing video from the default camera (0).

• If camera can’t open, print error and stop the program.

7. Process Video Frames

• Loop continuously:

o Read a frame from the camera.

o If frame reading fails, break the loop.

o Call face recognition function to process the frame.

o Show the processed frame in a window.

o If user presses ‘q’, stop the loop.

8. Cleanup

• Release the camera resource.

• Close all OpenCV windows.


7.EVENT DETECTION IN VIDEO SURVEILLANCE SYSTEM
Program:
import cv2

video = cv2.VideoCapture('D:\\meenu_rs\\event.mp4')

bg = cv2.createBackgroundSubtractorMOG2()

while True:

ret, frame = video.read()

if not ret:

break

mask = bg.apply(frame)

mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, (5, 5))

contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,


cv2.CHAIN_APPROX_SIMPLE)

for c in contours:

if cv2.contourArea(c) > 500:

x, y, w, h = cv2.boundingRect(c)

cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

cv2.imshow("Video", frame)

cv2.imshow("Motion", mask)

if cv2.waitKey(30) & 0xFF == ord('q'):

break

video.release()

cv2.destroyAllWindows()
Meaning:

1. Open the video file


The program starts by opening the video file you want to analyze.
2. Prepare the background subtractor
It sets up a method to separate moving objects from the background in each
video frame.
3. Start processing each frame in a loop
The program looks at the video one frame at a time, from start to end.
4. Read the current frame
It gets the current image frame from the video.
5. Check if the frame was read successfully
If there are no more frames (end of video), the program stops.
6. Detect moving parts
It uses the background subtractor to find areas in the frame that are changing
— meaning objects that are moving.
7. Clean up the detected moving areas
Small noises or random spots that aren’t really moving objects are removed
to make the detection clearer.
8. Find outlines of moving objects
The program finds the edges or shapes of the moving objects in the cleaned-
up image.
9. Ignore very small movements
Very tiny movements or noise are ignored; only big enough movements are
kept.
10.Draw boxes around moving objects
For each detected moving object, it draws a green rectangle around it on the
original video frame.
11.Show the video frames
The original video with green boxes, and the image showing detected
movement areas, are displayed on the screen.
12.Check if the user wants to quit
The program waits for a short moment to see if you press the letter ‘q’ on the
keyboard. If yes, it stops.
13.Clean up
After finishing, it closes the video file and all display windows properly.
8.MINI PROJECT GAMMA CORRECTION

Program:

import cv2

import numpy as np

img = cv2.imread(r"D:\meenu_rs\gamma.webp")

if img is None: raise FileNotFoundError("Image not found")

gamma = 0.6

inv = 1.0 / gamma

table = np.array([((i/255)**inv)*255 for i in range(256)],


dtype=np.uint8)

corrected = cv2.LUT(img, table)

scale = 0.5

small = lambda im: cv2.resize(im, (0,0), fx=scale, fy=scale,


interpolation=cv2.INTER_AREA)

cv2.imshow("Original", small(img))

cv2.imshow("Gamma Corrected", small(corrected))

cv2.waitKey(0)

cv2.destroyAllWindows()
Meaning:

 img = cv2.imread(r"D:\meenu_rs\gamma.webp")
Ithu image-ai load panrathu from the given path. File path correct illa na img will be None.

 if img is None: raise FileNotFoundError("Image not found")


Ithu check panrathu image load aayiduchuna illa-nu. Illana error message koduthu stop pannum.

 gamma = 0.6
Gamma value set pannirukkom. Ithu brightness and contrast adjust panrathuku use aagum.

 inv = 1.0 / gamma


Gamma correction-ku inverse gamma calculate pannirukkom. Adhu 1.0 / 0.6.

 table = np.array([((i/255)**inv)*255 for i in range(256)],


dtype=np.uint8)
Ithu lookup table create panrathu. Image pixels brightness-ai adjust panna ithu use aagum.
0 to 255 range la pixels-ai new values-ku map pannum based on gamma.

 corrected = cv2.LUT(img, table)


Lookup table use pannitu image pixels brightness-ai adjust pannum (gamma correction).

 scale = 0.5
Ithu scale factor. Image size 50% ku reduce panna use pannuvom.

 small = lambda im: cv2.resize(im, (0,0), fx=scale, fy=scale,


interpolation=cv2.INTER_AREA)
Ithu shortcut function. Edhaavathu image kudutha, adha scale factor (0.5) use panni size-a reduce
pannum.

 cv2.imshow("Original", small(img))
Original image size-a reduce panni display pannum.

 cv2.imshow("Gamma Corrected", small(corrected))


Gamma-corrected image size-a reduce panni display pannum.

 cv2.waitKey(0)
User oru key press pannum varai window open-a irukkum.

 cv2.destroyAllWindows()
Display pannra windows ellam close pannum

You might also like