You are on page 1of 11

Name:

Awais Amjad

Project :
Open cv

Perform Thresholding on an image:


Code:

import cv2

img = cv2.imread("pic.jpg")

cv2.imshow("BC",img)

ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

cv2.imshow('Binary Threshold', thresh1)

Output:
Detect Edges of objects in an image:
Code:

t_lower = 50 # Lower Threshold

t_upper = 150

edge = cv2.Canny(img, t_lower, t_upper)

cv2.imshow('edge', edge)

Code:
Detect Contours in an image:
Code:

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

edged = cv2.Canny(gray, 30, 200)

contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

cv2.imshow('Contours', img)

Output:
Blending Images:
Code:

mountain = cv2.imread('mountain1.jpg')

# Read image2

dog = cv2.imread("mountain5.jpg")

# Blending the images with 0.3 and 0.7

img = cv2.addWeighted(mountain, 0.3, dog, 0.7, 0)

cv2.imshow("BLend",img)

img = cv2.imread("mountain1.jpg")
Output:

Splitting and merging images:


Code:

img = cv2.imread("mountain1.jpg")

# Using cv2.split() to split channels of coloured image

b, g, r = cv2.split(img)

# Displaying Blue channel image


# Blue colour is highlighted the most

cv2.imshow("Model Blue Image", b)

# Displaying Green channel image

# Green colour is highlighted the most

cv2.imshow("Model Green Image", g)

# Displaying Red channel image

# Red colour is highlighted the most

cv2.imshow("Model Red Image", r)

Output:
Draw Histogram of an image:
Code:

import matplotlib.pyplot as plt

# find frequency of pixels in range 0-255

histr = cv2.calcHist([img], [0], None, [256], [0, 256])

# show the plotting graph of an image

plt.plot(histr)

plt.show()
Output:

Apply Log Transformation on an image:


Code:

import numpy as np

# Trying 4 gamma values.

for gamma in [0.1, 0.5, 1.2, 2.2]:

# Apply gamma correction.

gamma_corrected = np.array(255 * (img / 255) ** gamma, dtype='uint8')


# Save edited images.

cv2.imshow('gamma_transformed' + str(gamma) + '.jpg', gamma_corrected)

Output:

Apply Power Law Transformation on an


image:
Code:

import numpy as np

# Trying 4 gamma values.


for gamma in [0.1, 0.5, 1.2, 2.2]:

# Apply gamma correction.

gamma_corrected = np.array(255 * (img / 255) ** gamma, dtype='uint8')

# Save edited images.

cv2.imshow('gamma_transformed' + str(gamma) + '.jpg', gamma_corrected)

# Wait for a key

cv2.waitKey(0)

# Distroy all the window open

cv2.distroyAllWindows()

Output:

You might also like