0% found this document useful (0 votes)
10 views

IPMV Codes

The document provides a series of Python functions using OpenCV and NumPy for various image processing techniques, including transformations, filtering, and morphological operations. Each function is accompanied by example usage and visualizations of the original and processed images. Key techniques covered include power law transformations, histogram equalization, edge detection, and frequency domain filtering.

Uploaded by

Vikram Mali
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)
10 views

IPMV Codes

The document provides a series of Python functions using OpenCV and NumPy for various image processing techniques, including transformations, filtering, and morphological operations. Each function is accompanied by example usage and visualizations of the original and processed images. Key techniques covered include power law transformations, histogram equalization, edge detection, and frequency domain filtering.

Uploaded by

Vikram Mali
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/ 17

Image Negative Power Law Transform​


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

def display_results(link, gamma=0.5):


img = cv2.imread(link)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)​
gray = cv2.imread(link,0) [ALTERNATE LINE FOR FINDING GRAYSCALE IMAGE]
f = lambda x: np.uint8(np.clip((x / 255) ** gamma * 255, 0, 255))

results = [img, 255-img, f(img), gray, 255-gray, f(gray)]


titles = ['Original Color', 'Negative Color', 'Power Color', 'Original Gray', 'Negative Gray', 'Power
Gray']

for i, (result, title) in enumerate(zip(results, titles)):


plt.subplot(2, 3, i+1)
plt.imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB) if i < 3 else result, cmap='gray' if i >=
3 else None)
plt.title(title); plt.axis('off')
plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Insert your image path here
display_results(link)
Gray Level Slicing Without Background and Log Transform

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

def gray_slice_log_transform(link):
img = cv2.imread(link, 0)

# Gray Level Slicing Without Background (range: 100–150)


sliced = np.uint8(np.where((img >= 100) & (img <= 150), 255, 0))

# Log Transform
log_img = np.uint8(45 * np.log1p(img))

results = [img, sliced, log_img]


titles = ['Original', 'Sliced (No Background)', 'Log Transformed']

for i, (result, title) in enumerate(zip(results, titles)):


plt.subplot(1, 3, i + 1)
plt.imshow(result, cmap='gray')
plt.title(title)
plt.axis('off')
plt.tight_layout()
plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
gray_slice_log_transform(link)
Contrast Stretching and Obtain the Histogram of the
Original Contrast Stretched Image
import cv2, numpy as np, matplotlib.pyplot as plt

def contrast_stretching_hist(link):
img = cv2.imread(link, 0)
p2, p98 = np.percentile(img, (2, 98))
stretched = lambda x: np.uint8(np.clip((x - p2) / (p98 - p2) * 255, 0, 255))

results = [img, stretched(img), stretched(img)]


titles = ['Original', 'Contrast Stretched', 'Contrast Stretched Histogram']

for i, (result, title) in enumerate(zip(results, titles)):


plt.subplot(1, 3, i + 1)
if i == 2:
plt.hist(result.flatten(), 256, [0, 256]) # Histogram for the last subplot
else:
plt.imshow(result, cmap='gray') # For image display
plt.title(title)
plt.axis('off')
plt.tight_layout()
plt.show()

# Example usage:
link = '/content/download.jpg' # Replace with your image path
contrast_stretching_hist(link)
Histogram Equalization for a Grayscale Image

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

def histogram_equalization(link):
img = cv2.imread(link, 0)

# Compute histogram
hist = np.bincount(img.flatten(), minlength=256)
# Normalize histogram to get PDF
pdf = hist / hist.sum()
# Compute cumulative distribution function (CDF)
cdf = np.cumsum(pdf)
# Map old values to new using the CDF
equalized = np.uint8(np.floor(255 * cdf[img]))

results = [img, equalized, equalized]


titles = ['Original', 'Equalized Image', 'Equalized Histogram']

for i, (result, title) in enumerate(zip(results, titles)):


plt.subplot(1, 3, i + 1)
if i == 2:
plt.hist(result.flatten(), 256, [0, 256]) # Histogram for the last subplot
else:
plt.imshow(result, cmap='gray') # For image display
plt.axis('off')
plt.title(title)
plt.tight_layout()
plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
histogram_equalization(link)
Histogram Specification
import cv2, numpy as np, matplotlib.pyplot as plt

def histogram_specification(link, target_link):


img, target = cv2.imread(link, 0), cv2.imread(target_link, 0)

# CDFs of the source and target images


cdf_img = np.cumsum(cv2.calcHist([img], [0], None, [256], [0, 256])) / img.size
cdf_target = np.cumsum(cv2.calcHist([target], [0], None, [256], [0, 256])) / target.size

# Histogram mapping
mapping = np.interp(cdf_img, cdf_target, np.arange(256))

# Apply transformation
spec_img = np.uint8(np.interp(img.flatten(), np.arange(256), mapping).reshape(img.shape))

# Plotting
plt.subplot(1, 2, 1); plt.imshow(img, cmap='gray'); plt.title('Original'); plt.axis('off')
plt.subplot(1, 2, 2); plt.imshow(spec_img, cmap='gray'); plt.title('Specified'); plt.axis('off')
plt.tight_layout(); plt.show()def histogram_specification(link, target_link):
img, target = cv2.imread(link, 0), cv2.imread(target_link, 0)
hist = lambda x:np.bincount(x.flatten(), minlength=256)

# CDFs of the source and target images


cdf_img = np.cumsum(hist(img)) / img.size
cdf_target = np.cumsum(hist(target)) / target.size

# Histogram mapping
mapping = np.interp(cdf_img, cdf_target, np.arange(256))

# Apply transformation
spec_img = np.uint8(np.interp(img.flatten(), np.arange(256), mapping).reshape(img.shape))

results = [img, target, spec_img, hist(img), hist(target), hist(spec_img)]


titles = ['Original Image', 'Target Image', 'Specified Image', 'Original Histogram', 'Target
Histogram', 'Specified Histogram']

# Plotting
for i, (result, title) in enumerate(zip(results, titles)):
plt.subplot(2, 3, i + 1)
if i > 2:
plt.hist(result.flatten(), 256, [0, 256]) # Histogram for the last subplot
else:
plt.imshow(result, cmap='gray') # For image display
plt.axis('off')
plt.title(title)
plt.tight_layout()
plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
target_link = 'path_to_target_image.jpg' # Replace with your target image path
histogram_specification(link, target_link)
Averaging Filter

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

def averaging_filter(link):
img = cv2.imread(link, 0)
kernel = np.ones((5, 5), np.float32) / 25
filtered = cv2.filter2D(img, -1, kernel)

results = [img, filtered]


titles = ['Original Image', 'Averaging Filtered Image']

for i, (result, title) in enumerate(zip(results, titles)):


plt.subplot(1, 2, i+1)
plt.imshow(result, cmap='gray')
plt.title(title)
plt.axis('off')
plt.tight_layout()
plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
averaging_filter(link)

Sobel and Prewitt

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

def manual_convolve(img, kernel):


h, w = img.shape
kh, kw = kernel.shape
pad = kh // 2
padded = np.pad(img, pad, mode='constant', constant_values=0)
result = np.zeros_like(img, dtype=np.float32)

for i in range(h):
for j in range(w):
roi = padded[i:i+kh, j:j+kw]
result[i, j] = np.sum(roi * kernel)
return result

def sobel_prewitt_manual(link):
img = cv2.imread(link, 0).astype(np.float32)

# Sobel Kernels
sobel_x_kernel = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
sobel_y_kernel = np.array([[-1, -2, -1],
[ 0, 0, 0],
[ 1, 2, 1]])

# Prewitt Kernels
prewitt_x_kernel = np.array([[1, 0, -1],
[1, 0, -1],
[1, 0, -1]])
prewitt_y_kernel = np.array([[ 1, 1, 1],
[ 0, 0, 0],
[-1, -1, -1]])

# Apply manual convolution


sobel_x = manual_convolve(img, sobel_x_kernel)
sobel_y = manual_convolve(img, sobel_y_kernel)
sobel = np.hypot(sobel_x, sobel_y)

prewitt_x = manual_convolve(img, prewitt_x_kernel)


prewitt_y = manual_convolve(img, prewitt_y_kernel)
prewitt = np.hypot(prewitt_x, prewitt_y)

plt.subplot(2, 2, 1)
plt.imshow(sobel, cmap='gray')
plt.title('Sobel Edge Detection'); plt.axis('off')
plt.subplot(2, 2, 2)
plt.hist(sobel.flatten(), 256, [0,256])

plt.subplot(2, 2, 3)
plt.imshow(prewitt, cmap='gray')
plt.title('Prewitt Edge Detection'); plt.axis('off')
plt.subplot(2, 2, 4)
plt.hist(prewitt.flatten(), 256, [0,256])

plt.tight_layout(); plt.show()

# Example usage:
link = '/content/download.jpg' # Replace with your image path
sobel_prewitt_manual(link)
Detection of Horizontal and Vertical Lines
import cv2, numpy as np, matplotlib.pyplot as plt

def line_detection(link):
img = cv2.imread(link, 0)
edges = cv2.Canny(img, 50, 150)

# Horizontal lines detection


kernel_h = np.array([[-1, -1, -1], [2, 2, 2], [-1, -1, -1]], dtype=np.float32)
horizontal = cv2.filter2D(edges, -1, kernel_h)

# Vertical lines detection


kernel_v = np.array([[-1, 2, -1], [-1, 2, -1], [-1, 2, -1]], dtype=np.float32)
vertical = cv2.filter2D(edges, -1, kernel_v)

plt.subplot(1, 3, 1)
plt.imshow(edges, cmap='gray')
plt.title('Edge Detection'); plt.axis('off')

plt.subplot(1, 3, 2)
plt.imshow(horizontal, cmap='gray')
plt.title('Horizontal Lines'); plt.axis('off')

plt.subplot(1, 3, 3)
plt.imshow(vertical, cmap='gray')
plt.title('Vertical Lines'); plt.axis('off')

plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
line_detection(link)
Low Pass Filter in Frequency Domain
import cv2, numpy as np, matplotlib.pyplot as plt

def low_pass_filter_frequency(link):
img = cv2.imread(link, 0)
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
rows, cols = img.shape
crow, ccol = rows // 2, cols // 2

# Create mask
mask = np.zeros((rows, cols), np.uint8)
r = 30 # Radius of low-pass filter
center = [crow, ccol]
y, x = np.ogrid[:rows, :cols]
mask_area = (x - center[1])**2 + (y - center[0])**2 <= r**2
mask[mask_area] = 1

# Apply mask
fshift = fshift * mask
f_ishift = np.fft.ifftshift(fshift)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)

plt.subplot(1, 2, 1)
plt.imshow(np.log(1 + np.abs(fshift)), cmap='gray')
plt.title('Frequency Domain'); plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(img_back, cmap='gray')
plt.title('Low-pass Filtered Image'); plt.axis('off')

plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
low_pass_filter_frequency(link)
2D DFT
import cv2, numpy as np, matplotlib.pyplot as plt

def dft_2d(link):
img = cv2.imread(link, 0)
dft = np.fft.fft2(img)
dft_shifted = np.fft.fftshift(dft)
magnitude = np.abs(dft_shifted)

plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image'); plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(np.log(1 + magnitude), cmap='gray')
plt.title('2D DFT'); plt.axis('off')

plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
dft_2d(link)
Erosion and Dilation for Binary and Grayscale Images
import cv2, numpy as np, matplotlib.pyplot as plt

def erosion_dilation(link):
img = cv2.imread(link, 0)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)


eroded = cv2.erode(binary, kernel)
dilated = cv2.dilate(binary, kernel)

plt.subplot(1, 3, 1)
plt.imshow(binary, cmap='gray')
plt.title('Binary Image'); plt.axis('off')

plt.subplot(1, 3, 2)
plt.imshow(eroded, cmap='gray')
plt.title('Eroded Image'); plt.axis('off')

plt.subplot(1, 3, 3)
plt.imshow(dilated, cmap='gray')
plt.title('Dilated Image'); plt.axis('off')

plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
erosion_dilation(link)
Morphological Boundary Extraction
import cv2, numpy as np, matplotlib.pyplot as plt

def boundary_extraction(link):
img = cv2.imread(link, 0)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)


dilated = cv2.dilate(binary, kernel)
boundary = dilated - binary

plt.subplot(1, 2, 1)
plt.imshow(binary, cmap='gray')
plt.title('Binary Image'); plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(boundary, cmap='gray')
plt.title('Boundary Extraction'); plt.axis('off')

plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
boundary_extraction(link)
Morphological Smoothing on Color, Grayscale, and Binary
Images
import cv2, numpy as np, matplotlib.pyplot as plt

def morphological_smoothing(link):
img = cv2.imread(link)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)


smoothed_gray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel)
smoothed_binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)

plt.subplot(1, 3, 1)
plt.imshow(img)
plt.title('Original Color Image'); plt.axis('off')

plt.subplot(1, 3, 2)
plt.imshow(smoothed_gray, cmap='gray')
plt.title('Grayscale Smoothed'); plt.axis('off')

plt.subplot(1, 3, 3)
plt.imshow(smoothed_binary, cmap='gray')
plt.title('Binary Smoothed'); plt.axis('off')

plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
morphological_smoothing(link)
Global Thresholding for Color and Grayscale Image
import cv2, numpy as np, matplotlib.pyplot as plt

def global_thresholding(link, threshold=127):


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

# Global thresholding for grayscale image


_, gray_thresh = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)

# Global thresholding for color image


_, color_thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), threshold, 255,
cv2.THRESH_BINARY)

# Plotting
plt.subplot(1, 3, 1); plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); plt.title('Original');
plt.axis('off')
plt.subplot(1, 3, 2); plt.imshow(gray_thresh, cmap='gray'); plt.title('Grayscale Thresholding');
plt.axis('off')
plt.subplot(1, 3, 3); plt.imshow(color_thresh, cmap='gray'); plt.title('Color Thresholding');
plt.axis('off')
plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
global_thresholding(link)
Adaptive Thresholding
import cv2, numpy as np, matplotlib.pyplot as plt

def adaptive_thresholding(link):
img = cv2.imread(link, 0)

# Adaptive thresholding
adaptive_thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)

# Plotting the original and thresholded images


plt.subplot(1, 2, 1); plt.imshow(img, cmap='gray'); plt.title('Original'); plt.axis('off')
plt.subplot(1, 2, 2); plt.imshow(adaptive_thresh, cmap='gray'); plt.title('Adaptive Thresholding');
plt.axis('off')
plt.tight_layout(); plt.show()

# Example usage:
link = 'path_to_your_image.jpg' # Replace with your image path
adaptive_thresholding(link)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy