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

Assignment 2

The document contains Python code for image processing using OpenCV and Matplotlib, focusing on adding noise and applying various image transformations. It includes functions for adding Gaussian and salt & pepper noise, applying a vignette effect, and performing different types of thresholding and segmentation. The results are visualized through histograms and side-by-side comparisons of the original and processed images.
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)
4 views

Assignment 2

The document contains Python code for image processing using OpenCV and Matplotlib, focusing on adding noise and applying various image transformations. It includes functions for adding Gaussian and salt & pepper noise, applying a vignette effect, and performing different types of thresholding and segmentation. The results are visualized through histograms and side-by-side comparisons of the original and processed images.
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/ 9

4/16/25, 10:08 PM Untitled12.

ipynb - Colab

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

# Load grayscale image


image = cv2.imread('br.jpg', cv2.IMREAD_GRAYSCALE) # Replace with your image path

# 1. Strong Gaussian Noise


def add_gaussian_noise(img, mean=0, sigma=50):
gaussian = np.random.normal(mean, sigma, img.shape).astype(np.float32)
noisy_img = np.clip(img.astype(np.float32) + gaussian, 0, 255).astype(np.uint8)
return noisy_img

# 2. Strong Salt & Pepper Noise


def add_salt_pepper_noise(img, amount=0.1, salt_vs_pepper=0.5):
noisy_img = img.copy()
num_salt = int(np.ceil(amount * img.size * salt_vs_pepper))
num_pepper = int(np.ceil(amount * img.size * (1.0 - salt_vs_pepper)))

# Salt noise
coords = [np.random.randint(0, i - 1, num_salt) for i in img.shape]
noisy_img[tuple(coords)] = 255

# Pepper noise
coords = [np.random.randint(0, i - 1, num_pepper) for i in img.shape]
noisy_img[tuple(coords)] = 0

return noisy_img

# 3. Uneven Illumination (Vignette Effect)


def apply_vignette(img, strength=100):
rows, cols = img.shape
kernel_x = cv2.getGaussianKernel(cols, strength)
kernel_y = cv2.getGaussianKernel(rows, strength)
kernel = kernel_y @ kernel_x.T
mask = kernel / np.max(kernel) # Normalize to [0,1]
vignette_img = img * mask
vignette_img = np.clip(vignette_img, 0, 255).astype(np.uint8)
return vignette_img

# Apply the transformations


gaussian_noise = add_gaussian_noise(image)
sp_noise = add_salt_pepper_noise(image)
vignette = apply_vignette(image)

# Show results
plt.figure(figsize=(12, 6))
plt.subplot(1, 4, 1), plt.imshow(image, cmap='gray'), plt.title('Original'), plt.axis('off')
plt.subplot(1, 4, 2), plt.imshow(gaussian_noise, cmap='gray'), plt.title('Gaussian Noise'), plt.axis('off')
plt.subplot(1, 4, 3), plt.imshow(sp_noise, cmap='gray'), plt.title('Salt & Pepper'), plt.axis('off')
plt.subplot(1, 4, 4), plt.imshow(vignette, cmap='gray'), plt.title('Uneven Illumination'), plt.axis('off')
plt.tight_layout()
plt.show()

https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 1/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab

 

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

# Load grayscale image


image = cv2.imread('br.jpg', cv2.IMREAD_GRAYSCALE) # Replace with your actual image path

# Functions for noise and vignette


def add_gaussian_noise(img, mean=0, sigma=50):
noise = np.random.normal(mean, sigma, img.shape).astype(np.float32)
return np.clip(img.astype(np.float32) + noise, 0, 255).astype(np.uint8)

def add_salt_pepper_noise(img, amount=0.1, salt_vs_pepper=0.5):


noisy_img = img.copy()
num_salt = int(amount * img.size * salt_vs_pepper)
num_pepper = int(amount * img.size * (1 - salt_vs_pepper))
coords = [np.random.randint(0, i - 1, num_salt) for i in img.shape]
noisy_img[tuple(coords)] = 255
coords = [np.random.randint(0, i - 1, num_pepper) for i in img.shape]
noisy_img[tuple(coords)] = 0
return noisy_img

def apply_vignette(img, strength=100):


rows, cols = img.shape
kernel_x = cv2.getGaussianKernel(cols, strength)
kernel_y = cv2.getGaussianKernel(rows, strength)
mask = kernel_y @ kernel_x.T
mask = mask / np.max(mask)
vignette = img * mask
return np.clip(vignette, 0, 255).astype(np.uint8)

# Apply modifications
gaussian_img = add_gaussian_noise(image)
sp_img = add_salt_pepper_noise(image)
vignette_img = apply_vignette(image)

# Function to plot histogram


def plot_histogram(img, title, bins=64):
plt.hist(img.ravel(), bins=bins, range=(0, 256), color='gray')
plt.title(f'{title}')
plt.xlabel('Pixel Intensity')
plt.ylabel('Frequency')

# Plot all histograms


plt.figure(figsize=(12, 6))
plt.subplot(2, 2, 1)
plot_histogram(image, 'Original Image Histogram')

plt.subplot(2, 2, 2)
plot_histogram(gaussian_img, 'Gaussian Noise Histogram')

plt subplot(2 2 3)
https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 2/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab
plt.subplot(2, 2, 3)
plot_histogram(sp_img, 'Salt & Pepper Histogram')

plt.subplot(2, 2, 4)
plot_histogram(vignette_img, 'Uneven Illumination Histogram')

plt.tight_layout()
plt.show()

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

# Load grayscale and color version of the image


image_path = 'br.jpg' # Replace with actual image path
image_color = cv2.imread(image_path)
image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)

# 1. Basic Global Thresholding (Fixed threshold at 127)


_, basic_thresh = cv2.threshold(image_gray, 127, 255, cv2.THRESH_BINARY)

# 2. Otsu's Thresholding (automatic)


_, otsu_thresh = cv2.threshold(image_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# 3. Multispectral Thresholding (each RGB channel separately)


b_channel, g_channel, r_channel = cv2.split(image_color)

# Apply threshold to each channel


_, b_thresh = cv2.threshold(b_channel, 127, 255, cv2.THRESH_BINARY)
_, g_thresh = cv2.threshold(g_channel, 127, 255, cv2.THRESH_BINARY)
_, r_thresh = cv2.threshold(r_channel, 127, 255, cv2.THRESH_BINARY)

# Combine using logical OR


multi_thresh = cv2.bitwise_or(cv2.bitwise_or(r_thresh, g_thresh), b_thresh)

# Display all outputs


plt.figure(figsize=(12, 8))

plt.subplot(2, 2, 1)
plt.imshow(image_gray, cmap='gray')
plt.title('Original Grayscale')
l i (' ff')
https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 3/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab
plt.axis('off')

plt.subplot(2, 2, 2)
plt.imshow(basic_thresh, cmap='gray')
plt.title('Basic Global Thresholding')
plt.axis('off')

plt.subplot(2, 2, 3)
plt.imshow(otsu_thresh, cmap='gray')
plt.title("Otsu's Thresholding")
plt.axis('off')

plt.subplot(2, 2, 4)
plt.imshow(multi_thresh, cmap='gray')
plt.title('Multispectral Thresholding (RGB)')
plt.axis('off')

plt.tight_layout()
plt.show()

import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.segmentation import felzenszwalb, flood
https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 4/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab
from skimage.segmentation import felzenszwalb, flood
from skimage import img_as_float

# ----------------------------
# 1. Load & Resize Image
# ----------------------------
image_path = 'br.jpg' # 🔁 Replace with your file
image_color = cv2.imread(image_path)

if image_color is None:
raise FileNotFoundError("⚠️ Image not found. Check your path or upload again.")

resized_image = cv2.resize(image_color, (256, 256))


resized_float = img_as_float(resized_image)

# ----------------------------
# 2. Felzenszwalb Segmentation
# ----------------------------
felz_segments = felzenszwalb(resized_float, scale=100, sigma=0.5, min_size=50)

# ----------------------------
# 3. Region Growing (auto seed)
# ----------------------------
gray_resized = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)
gray_norm = cv2.normalize(gray_resized, None, 0, 255, cv2.NORM_MINMAX)

# Auto select brightest pixel as seed


min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(gray_norm)
seed_point = (max_loc[1], max_loc[0]) # (row, col)

region = flood(gray_norm, seed_point, tolerance=50) # 💥 high tolerance

# ----------------------------
# 4. Show Results
# ----------------------------
plt.figure(figsize=(15, 5))

# Original
plt.subplot(1, 3, 1)
plt.imshow(cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.axis('off')

# Region Growing
plt.subplot(1, 3, 2)
plt.imshow(region, cmap='gray')
plt.title(f'Region Growing\nAuto Seed: {seed_point}')
plt.axis('off')

# Felzenszwalb
plt.subplot(1, 3, 3)
plt.imshow(felz_segments, cmap='nipy_spectral')
plt.title("Felzenszwalb's Segmentation")
plt.axis('off')

plt.tight_layout()
plt.show()

https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 5/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab

import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.segmentation import flood

# ----------------------------
# 1. Load and Resize Image
# ----------------------------
image_path = 'br.jpg' # Replace with your image file name
image_color = cv2.imread(image_path)
resized_image = cv2.resize(image_color, (256, 256))
gray_original = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)

# ----------------------------
# 2. Add Gaussian Noise
# ----------------------------
def add_gaussian_noise(img, mean=0, sigma=50):
noise = np.random.normal(mean, sigma, img.shape).astype(np.float32)
noisy = np.clip(img.astype(np.float32) + noise, 0, 255).astype(np.uint8)
return noisy

gray_noisy = add_gaussian_noise(gray_original)

# ----------------------------
# 3. Apply Thresholding
# ----------------------------
_, basic_thresh = cv2.threshold(gray_original, 127, 255, cv2.THRESH_BINARY)

# ----------------------------
# 4. Region Growing Segmentation
# ----------------------------
# Normalize and auto-pick brightest point as seed
gray_norm = cv2.normalize(gray_original, None, 0, 255, cv2.NORM_MINMAX)
_, _, _, max_loc = cv2.minMaxLoc(gray_norm)
seed_point = (max_loc[1], max_loc[0]) # (row, col)
region = flood(gray_norm, seed_point, tolerance=50)

# ----------------------------
# 5. Display Side-by-Side Comparison
# ----------------------------
plt.figure(figsize=(14, 8))

# --- Before/After Noise ---


plt.subplot(2, 2, 1)
plt.imshow(gray_original, cmap='gray')
plt.title("Original (Grayscale)")
plt.axis('off')

https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 6/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab
plt.subplot(2, 2, 2)
plt.imshow(gray_noisy, cmap='gray')
plt.title("After Gaussian Noise")
plt.axis('off')

# --- Thresholding vs Region Growing ---


plt.subplot(2, 2, 3)
plt.imshow(basic_thresh, cmap='gray')
plt.title("Thresholding (Binary @127)")
plt.axis('off')

plt.subplot(2, 2, 4)
plt.imshow(region, cmap='gray')
plt.title(f"Region Growing (Seed: {seed_point})")
plt.axis('off')

plt.tight_layout()
plt.show()

import cv2
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# ----------------------------------------
https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 7/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab
# 1. Load & Resize Image
# ----------------------------------------
image_path = 'br.jpg' # 🔁 Replace with your image filename
image_color = cv2.imread(image_path)

if image_color is None:
raise FileNotFoundError("⚠️ Image not found. Please check the path.")

resized_image = cv2.resize(image_color, (256, 256))


gray = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)
rows, cols = gray.shape

# ----------------------------------------
# 2. Prepare Features (Intensity + Position)
# ----------------------------------------
X = []
for i in range(rows):
for j in range(cols):
intensity = gray[i, j]
X.append([intensity, i, j])

X = np.array(X)

# Normalize features for better clustering


scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# ----------------------------------------
# 3. Train KMeans (2 clusters: foreground & background)
# ----------------------------------------
kmeans = KMeans(n_clusters=2, random_state=0, n_init=10)
labels = kmeans.fit_predict(X_scaled)

# Reshape labels into image form


segmented_img = labels.reshape(rows, cols)

# ----------------------------------------
# 4. Display Results
# ----------------------------------------
plt.figure(figsize=(10, 5))

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

plt.subplot(1, 2, 2)
plt.imshow(segmented_img, cmap='gray')
plt.title('KMeans Segmentation (2 Clusters)')
plt.axis('off')

plt.tight_layout()
plt.show()

https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 8/9
4/16/25, 10:08 PM Untitled12.ipynb - Colab

https://colab.research.google.com/drive/1c-YnbIsIZJ8J0JYjSYZDOKnjdcUwwpVs#scrollTo=KOkv9qjbdGBc&printMode=true 9/9

You might also like