0% found this document useful (0 votes)
83 views8 pages

DIP First 5 Prog

The document contains multiple Python scripts demonstrating various image processing techniques using OpenCV and NumPy, including negative transformation, logarithmic transformation, gamma transformation, contrast stretching, intensity level slicing, and histogram equalization. Each script loads an image, applies specific transformations, and displays the original and processed images using Matplotlib. The techniques are illustrated with both grayscale and color images, showcasing different methods for enhancing image quality and visual representation.

Uploaded by

likith9380
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)
83 views8 pages

DIP First 5 Prog

The document contains multiple Python scripts demonstrating various image processing techniques using OpenCV and NumPy, including negative transformation, logarithmic transformation, gamma transformation, contrast stretching, intensity level slicing, and histogram equalization. Each script loads an image, applies specific transformations, and displays the original and processed images using Matplotlib. The techniques are illustrated with both grayscale and color images, showcasing different methods for enhancing image quality and visual representation.

Uploaded by

likith9380
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/ 8

1.

pip install opencv-python numpy matplotlib

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

# Load image in grayscale


image = cv2.imread('grayscale_image.jpg', cv2.IMREAD_GRAYSCALE)

# Check if image is loaded


if image is None:
raise ValueError("Image not found or not loaded.")

# Negative Transformation
def negative_transformation(img):
return 255 - img

# Logarithmic Transformation
def log_transformation(img):
c = 255 / np.log(1 + np.max(img))
return np.uint8(c * np.log(1 + img))

# Power Law (Gamma) Transformation


def gamma_transformation(img, gamma=0.5):
# Normalize image to range 0 to 1
img_normalized = img / 255.0
gamma_corrected = np.power(img_normalized, gamma)
return np.uint8(gamma_corrected * 255)

# Apply transformations
negative_img = negative_transformation(image)
log_img = log_transformation(image)
gamma_img = gamma_transformation(image, gamma=0.4) # try
gamma=0.4 or 2.2 for different effects

# Display results
titles = ['Original Image', 'Negative', 'Logarithmic', 'Gamma (0.4)']
images = [image, negative_img, log_img, gamma_img]

plt.figure(figsize=(12, 8))
for i in range(4):
plt.subplot(2, 2, i+1)
plt.imshow(images[i], cmap='gray')
plt.title(titles[i])
plt.axis('off')
plt.tight_layout()
plt.show()

2.import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

# Load the image using PIL


image = Image.open('color_image.jpg') # Replace with your image path
image = image.convert('RGB') # Ensure it's in RGB format

# Convert image to numpy array


img_array = np.array(image)

# Manually perform negative transformation without using predefined


functions
height, width, channels = img_array.shape
negative_img = np.zeros((height, width, channels), dtype=np.uint8)

for i in range(height):
for j in range(width):
for c in range(channels):
negative_img[i, j, c] = 255 - img_array[i, j, c]

# Display original and negative images


plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(img_array)
plt.title("Original Image")
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(negative_img)
plt.title("Negative Image")
plt.axis('off')

plt.tight_layout()
plt.show()

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

# Load grayscale image


image = cv2.imread('grayscale_image.jpg', cv2.IMREAD_GRAYSCALE)

if image is None:
raise ValueError("Image not found. Please check the path.")

# Operation (a) s = r + 50
add_50 = np.clip(image + 50, 0, 255).astype(np.uint8)

# Operation (b) s = r - 50
sub_50 = np.clip(image - 50, 0, 255).astype(np.uint8)

# Operation (c) s = r * 0.5


mul_05 = np.clip(image * 0.5, 0, 255).astype(np.uint8)

# Operation (d) s = r * 2
mul_2 = np.clip(image * 2, 0, 255).astype(np.uint8)

# Display results
titles = [
"Original Image",
"s = r + 50",
"s = r - 50",
"s = r * 0.5",
"s = r * 2"
]
images = [image, add_50, sub_50, mul_05, mul_2]

plt.figure(figsize=(12, 8))
for i in range(5):
plt.subplot(2, 3, i+1)
plt.imshow(images[i], cmap='gray')
plt.title(titles[i])
plt.axis('off')

plt.tight_layout()
plt.show()

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

# Load grayscale image


image = cv2.imread('grayscale_image.jpg', cv2.IMREAD_GRAYSCALE)
if image is None:
raise ValueError("Image not found. Please check the path.")

# 1. Contrast Stretching
def contrast_stretch(img, a=70, b=180):
stretched = np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
r = img[i, j]
if r < a:
s=0
elif r > b:
s = 255
else:
s = (r - a) * 255 / (b - a)
stretched[i, j] = np.clip(s, 0, 255)
return stretched.astype(np.uint8)

# 2. Intensity Level Slicing


def intensity_level_slicing(img, lower=100, upper=150, high_value=255):
sliced = np.where((img >= lower) & (img <= upper), high_value, img)
return sliced.astype(np.uint8)

# 3. Bit Plane Slicing


def bit_plane_slicing(img):
bit_planes = [(img >> i) & 1 for i in range(8)]
return [plane * 255 for plane in bit_planes] # scale to 0–255 for
visualization

# Apply transformations
contrast_img = contrast_stretch(image)
sliced_img = intensity_level_slicing(image)
bit_planes = bit_plane_slicing(image)

# Display results
plt.figure(figsize=(12, 10))

# Original and transformations


plt.subplot(2, 3, 1)
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.axis('off')

plt.subplot(2, 3, 2)
plt.imshow(contrast_img, cmap='gray')
plt.title("Contrast Stretching")
plt.axis('off')
plt.subplot(2, 3, 3)
plt.imshow(sliced_img, cmap='gray')
plt.title("Intensity Level Slicing")
plt.axis('off')

# Display 3 of 8 bit planes for brevity


for i in range(3):
plt.subplot(2, 3, 4 + i)
plt.imshow(bit_planes[7 - i], cmap='gray')
plt.title(f'Bit Plane {7 - i}')
plt.axis('off')

plt.tight_layout()
plt.show()

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

# Load grayscale image


image = cv2.imread('grayscale_image.jpg', cv2.IMREAD_GRAYSCALE)
if image is None:
raise ValueError("Image not found. Please check the file path.")

# Manual Histogram Equalization Function


def manual_hist_equalization(img):
# Flatten image to 1D array
hist, bins = np.histogram(img.flatten(), 256, [0, 256])
cdf = hist.cumsum() # Cumulative distribution function
cdf_normalized = cdf * 255 / cdf[-1] # Normalize

# Mask all zeros (if any)


cdf_masked = np.ma.masked_equal(cdf, 0)
cdf_masked = (cdf_masked - cdf_masked.min()) * 255 /
(cdf_masked.max() - cdf_masked.min())
cdf_final = np.ma.filled(cdf_masked, 0).astype('uint8')

# Map original image pixels to equalized values


equalized_img = cdf_final[img]
return equalized_img

# Apply manual equalization


equalized_image = manual_hist_equalization(image)

# For comparison (OpenCV built-in)


equalized_cv2 = cv2.equalizeHist(image)

# Plotting helper
def plot_histogram(img, title):
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
plt.plot(hist, color='black')
plt.title(title)
plt.xlabel('Pixel Intensity')
plt.ylabel('Frequency')
plt.grid()

# Plot images and histograms


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

# Original Image
plt.subplot(2, 3, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')

# Histogram of Original
plt.subplot(2, 3, 4)
plot_histogram(image, 'Original Histogram')

# Equalized Image (Manual)


plt.subplot(2, 3, 2)
plt.imshow(equalized_image, cmap='gray')
plt.title('Equalized Image (Manual)')
plt.axis('off')

# Histogram of Equalized Image (Manual)


plt.subplot(2, 3, 5)
plot_histogram(equalized_image, 'Equalized Histogram (Manual)')

# Equalized using OpenCV (Optional)


plt.subplot(2, 3, 3)
plt.imshow(equalized_cv2, cmap='gray')
plt.title('Equalized Image (OpenCV)')
plt.axis('off')

plt.tight_layout()
plt.show()

You might also like