DIP Lab Codes
DIP Lab Codes
# For skimage
image = io.imread('C:/Users/YourUsername/Pictures/input_image.jpg')
# For OpenCV
image = cv2.imread('C:/Users/YourUsername/Pictures/input_image.jpg')
# Using skimage
image = io.imread('/home/user/images/input_image.jpg')
# Using OpenCV
image = cv2.imread('/home/user/images/input_image.jpg')
Notes:
In skimage, the image is read as a NumPy array, and you need to use img_as_ubyte to convert
the image data to 8-bit format before saving it.
In OpenCV, the image is directly read as a NumPy array, and the cv2.imwrite method saves the
image in the specified format.
Both libraries handle images as NumPy arrays, but skimage tends to focus on scientific and
analytical image processing, while OpenCV is more widely used for general-purpose computer
vision tasks.
3. Loading an image from a local dataset (folder of images) Example using os and
skimage
import os
from skimage import io
import matplotlib.pyplot as plt
Notes:
In skimage, the functions rgb2gray and rgb2hsv are used for conversions.
In OpenCV, use cv2.cvtColor() with the appropriate conversion code.
These conversions demonstrate how to change from one color space to another, specifically
RGB/BGR to Grayscale and HSV. The saved images reflect the changes in color channels.
# 1. Read the image (We only use skimage to read and save the image, processing will be
manual)
image = io.imread('input_image.jpg')
plt.imshow(grayscale_image, cmap='gray')
plt.axis('off')
plt.show()
# Normalize the hue to [0, 360] and save the HSV image
hsv_image[..., 0] = hsv_image[..., 0] / 360.0 # Scale Hue to [0, 1] for visualization
# Modify a region of pixels (for example, a 10x10 region starting at (x, y))
image[y:y+10, x:x+10] = [0, 255, 0] # Change the region to green
# Modify a region of pixels (for example, a 10x10 region starting at (x, y))
image[y:y+10, x:x+10] = [0, 255, 0] # Change the region to green (BGR format)
# Save the updated image
cv2.imwrite('updated_image.jpg', image)
Explanation:
image[y, x] = new_color updates the pixel at (x, y) with the new color value.
You can also modify a block of pixels by specifying a region, such as image[y:y+10, x:x+10],
which changes a 10x10 region of the image.
Explanation:
Reading the Image: io.imread() from skimage is used to load the image into a NumPy array.
Updating Pixels: We use the function update_pixel to change the color of a single pixel and
update_region to change the color of a rectangular region.
Manual Pixel Access: Pixels are accessed and modified using image[y, x], where (x, y) are the
coordinates, and the color is represented as an array like [255, 0, 0] (RGB format for red).
Saving the Image: After modifying the pixel values, the updated image is saved using
io.imsave().
Explanation:
Reading the Image: We use OpenCV to read the image, but the pixel updates are done
manually.
Updating Pixel Values: The function update_pixel manually changes the pixel at (x, y) to the
new_color. The color in OpenCV is in BGR format (blue, green, red).
Region Update: The update_region function uses loops to modify a rectangular region of pixels,
applying the same logic as single pixel modification.
Saving the Image: After the modification, the updated image is saved using cv2.imwrite.
Manual Logic:
Pixel Access: image[y, x] accesses the pixel at coordinates (x, y) in the 2D array. We manually
set it to the desired color.
Pixel Bounds Check: Before updating, we check that the pixel coordinates are within the image
bounds to prevent out-of-bounds errors.
This approach allows you to understand how images are essentially arrays of pixel values and
how to manipulate them directly.
# Convert the image from BGR (OpenCV's default) to RGB for correct display in matplotlib
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot the image using matplotlib
plt.imshow(image_rgb)
plt.axis('off') # Turn off axis labels
plt.title('Image Display with Matplotlib')
plt.show()
Explanation:
Image Reading: We use cv2.imread() to read the image in BGR format (the default for OpenCV).
Color Conversion: Since matplotlib expects images in RGB format, we convert the image from
BGR to RGB using cv2.cvtColor().
Plotting: plt.imshow() is used to display the image, and plt.axis('off') removes the axis labels for
a cleaner display.
# 1. Read the image (Use skimage for reading, but arithmetic will be done manually)
image = io.imread('input_image.jpg')
return result_image
return result_image
return result_image
plt.subplot(1, 4, 1)
plt.imshow(image)
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 4, 2)
plt.imshow(added_image)
plt.title('Added Scalar')
plt.axis('off')
plt.subplot(1, 4, 3)
plt.imshow(subtracted_image)
plt.title('Subtracted Scalar')
plt.axis('off')
plt.subplot(1, 4, 4)
plt.imshow(multiplied_image)
plt.title('Multiplied by Scalar')
plt.axis('off')
plt.show()
Explanation:
Manual Addition: We manually add a scalar to each pixel’s RGB value. If the result exceeds 255,
we clip it to 255.
Manual Subtraction: We manually subtract a scalar from each pixel’s RGB value. If the result
goes below 0, we clip it to 0.
Manual Multiplication: We multiply each pixel’s RGB value by a scalar, making sure the values
stay within the range of 0 to 255.
Clipping: Clipping ensures that the pixel values don’t exceed the valid range (0-255) for an 8-bit
image.
Summary:
Addition: Brightens the image by increasing the intensity of each pixel.
Subtraction: Darkens the image by decreasing the intensity of each pixel.
Multiplication: Adjusts the contrast of the image, where values greater than 1 increase
contrast, and values between 0 and 1 reduce contrast.
(2) Arithmetic Operations Using skimage (built-in functions)
from skimage import io, img_as_ubyte
import numpy as np
import matplotlib.pyplot as plt
# 1. Addition of a scalar
scalar = 50
added_image = np.clip(image + scalar, 0, 255).astype(np.uint8)
# 2. Subtraction of a scalar
subtracted_image = np.clip(image - scalar, 0, 255).astype(np.uint8)
# 3. Multiplication by a scalar
multiplier = 1.2
multiplied_image = np.clip(image * multiplier, 0, 255).astype(np.uint8)
plt.subplot(1, 4, 1)
plt.imshow(image)
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 4, 2)
plt.imshow(added_image)
plt.title('Added Scalar')
plt.axis('off')
plt.subplot(1, 4, 3)
plt.imshow(subtracted_image)
plt.title('Subtracted Scalar')
plt.axis('off')
plt.subplot(1, 4, 4)
plt.imshow(multiplied_image)
plt.title('Multiplied by Scalar')
plt.axis('off')
plt.show()
Explanation:
Addition: np.clip(image + scalar, 0, 255) adds a scalar to the image and clips the result to ensure
values are within the 0-255 range.
Subtraction: np.clip(image - scalar, 0, 255) subtracts a scalar from the image and clips the
result.
Multiplication: np.clip(image * multiplier, 0, 255) multiplies the image pixel values by a scalar
and clips the result.
(3) Arithmetic Operations Using OpenCV (built-in functions)
import cv2
import numpy as np
# 1. Addition of a scalar
scalar = 50
added_image = cv2.add(image, scalar) # OpenCV handles clipping automatically
# 2. Subtraction of a scalar
subtracted_image = cv2.subtract(image, scalar) # OpenCV handles clipping automatically
# 3. Multiplication by a scalar
multiplier = 1.2
multiplied_image = cv2.multiply(image, np.array([multiplier])) # OpenCV handles clipping
automatically
Explanation:
Addition: cv2.add(image, scalar) adds a scalar value to each pixel and handles clipping
internally.
Subtraction: cv2.subtract(image, scalar) subtracts a scalar from each pixel and handles clipping.
Multiplication: cv2.multiply(image, np.array([multiplier])) multiplies pixel values by a scalar and
handles clipping.
Summary:
skimage and OpenCV simplify arithmetic operations on images by providing functions that
handle these operations efficiently and automatically clip the results to ensure pixel values
remain within valid ranges.
skimage uses NumPy operations and requires manual clipping, while OpenCV provides
convenient functions (add, subtract, multiply) that handle clipping and other edge cases
internally.
6. Point processing(negative, gamma, logarithmic,
exponential) based on scenario
# 1. Negative Transformation
def negative_transformation(image_array):
return 255 - image_array
# 2. Gamma Correction
def gamma_correction(image_array, gamma):
normalized = image_array / 255.0
corrected = 255 * np.power(normalized, gamma)
return corrected.astype(np.uint8)
# 3. Logarithmic Transformation
def logarithmic_transformation(image_array, c):
normalized = image_array / 255.0
transformed = c * np.log1p(normalized)
return np.clip(transformed * 255, 0, 255).astype(np.uint8)
# 4. Exponential Transformation
def exponential_transformation(image_array, c):
normalized = image_array / 255.0
transformed = c * (np.exp(normalized) - 1)
return np.clip(transformed * 255, 0, 255).astype(np.uint8)
# Apply transformations
negative_image = negative_transformation(image)
gamma_corrected_image = gamma_correction(image, gamma_value)
logarithmic_image = logarithmic_transformation(image, log_constant)
exponential_image = exponential_transformation(image, exp_constant)
plt.subplot(2, 3, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(2, 3, 2)
plt.imshow(negative_image, cmap='gray')
plt.title('Negative Transformation')
plt.axis('off')
plt.subplot(2, 3, 3)
plt.imshow(gamma_corrected_image, cmap='gray')
plt.title('Gamma Correction')
plt.axis('off')
plt.subplot(2, 3, 4)
plt.imshow(logarithmic_image, cmap='gray')
plt.title('Logarithmic Transformation')
plt.axis('off')
plt.subplot(2, 3, 5)
plt.imshow(exponential_image, cmap='gray')
plt.title('Exponential Transformation')
plt.axis('off')
plt.show()
Explanation:
Negative Transformation:
Subtracts pixel values from 255 to invert the image.
255 - image_array inverts the pixel values.
Gamma Correction:
Adjusts image brightness based on gamma.
Normalizes pixel values to [0, 1], applies gamma correction, and scales back to [0, 255].
Logarithmic Transformation:
Enhances details in darker regions.
Normalizes pixel values, applies logarithmic transformation, and scales to [0, 255].
Exponential Transformation:
Enhances lighter regions.
Normalizes pixel values, applies exponential transformation, and scales to [0, 255].
Summary:
Negative Transformation: Inverts the image colors.
Gamma Correction: Adjusts brightness.
Logarithmic Transformation: Enhances dark regions.
Exponential Transformation: Enhances light regions.
# 1. Negative Transformation
def negative_transformation(image_array):
height, width, channels = image_array.shape
result_image = np.zeros_like(image_array)
for y in range(height):
for x in range(width):
for c in range(channels):
result_image[y, x, c] = 255 - image_array[y, x, c]
return result_image
# 2. Gamma Correction
def gamma_correction(image_array, gamma):
height, width, channels = image_array.shape
result_image = np.zeros_like(image_array)
for y in range(height):
for x in range(width):
for c in range(channels):
normalized = image_array[y, x, c] / 255.0
corrected = 255 * (normalized ** gamma)
result_image[y, x, c] = min(max(int(corrected), 0), 255)
return result_image
# 3. Logarithmic Transformation
def logarithmic_transformation(image_array, c):
height, width, channels = image_array.shape
result_image = np.zeros_like(image_array)
for y in range(height):
for x in range(width):
for c in range(channels):
normalized = image_array[y, x, c] / 255.0
transformed = c * np.log1p(normalized)
result_image[y, x, c] = min(max(int(transformed * 255), 0), 255)
return result_image
# 4. Exponential Transformation
def exponential_transformation(image_array, c):
height, width, channels = image_array.shape
result_image = np.zeros_like(image_array)
for y in range(height):
for x in range(width):
for c in range(channels):
normalized = image_array[y, x, c] / 255.0
transformed = c * (np.exp(normalized) - 1)
result_image[y, x, c] = min(max(int(transformed * 255), 0), 255)
return result_image
# Apply transformations
negative_image = negative_transformation(image)
gamma_corrected_image = gamma_correction(image, gamma_value)
logarithmic_image = logarithmic_transformation(image, log_constant)
exponential_image = exponential_transformation(image, exp_constant)
plt.subplot(2, 3, 1)
plt.imshow(image)
plt.title('Original Image')
plt.axis('off')
plt.subplot(2, 3, 2)
plt.imshow(negative_image)
plt.title('Negative Transformation')
plt.axis('off')
plt.subplot(2, 3, 3)
plt.imshow(gamma_corrected_image)
plt.title('Gamma Correction')
plt.axis('off')
plt.subplot(2, 3, 4)
plt.imshow(logarithmic_image)
plt.title('Logarithmic Transformation')
plt.axis('off')
plt.subplot(2, 3, 5)
plt.imshow(exponential_image)
plt.title('Exponential Transformation')
plt.axis('off')
plt.show()
Explanation:
Image Reading: The image is read and converted to 8-bit format.
Negative Transformation: Subtracts each pixel value from 255.
Gamma Correction: Adjusts brightness using gamma correction formula.
Logarithmic Transformation: Enhances dark regions using logarithmic scaling.
Exponential Transformation: Enhances light regions using exponential scaling.
Display: Uses matplotlib to display the original and transformed images in a grid layout.
7. Image enhancement with histogram equalization
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(equalized_image, cmap='gray')
plt.title('Equalized Image (Manual)')
plt.axis('off')
plt.show()
Note
Manual histogram equalization involves calculating the histogram of the image, computing the
cumulative distribution function (CDF), and then mapping the pixel values to their new values
based on the CDF.
(2) skimage Built-in Function Implementation
from skimage import exposure
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(equalized_image_skimage, cmap='gray')
plt.title('Equalized Image (skimage)')
plt.axis('off')
plt.show()
(3) opencv Built-in Function Implementation
import cv2
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(equalized_image_cv2, cmap='gray')
plt.title('Equalized Image (OpenCV)')
plt.axis('off')
plt.show()
8. Filtering(Smoothening, Sharpening) [with or without given
kernel]
return result_image
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(blurred_image, cmap='gray')
plt.title('Blurred Image (Manual)')
plt.axis('off')
plt.show()
(2) Smoothening (Blurring) Using skimage Built-in Functions
from skimage import filters
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(blurred_image_skimage, cmap='gray')
plt.title('Blurred Image (skimage)')
plt.axis('off')
plt.show()
(3) Smoothening (Blurring) Using openCV Built-in Functions
import cv2
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(blurred_image_cv2, cmap='gray')
plt.title('Blurred Image (OpenCV)')
plt.axis('off')
plt.show()
(4) Sharpening Manual Implementation (Using a 3x3 Sharpening Filter)
# Manual sharpening with a 3x3 sharpening filter
def apply_sharpening_filter(image_array, kernel):
height, width = image_array.shape
k_height, k_width = kernel.shape
pad_height = k_height // 2
pad_width = k_width // 2
for y in range(height):
for x in range(width):
region = padded_image[y:y+k_height, x:x+k_width]
result_image[y, x] = np.sum(region * kernel)
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(sharpened_image, cmap='gray')
plt.title('Sharpened Image (Manual)')
plt.axis('off')
plt.show()
(5) Sharpening Using skimage Built-in Functions
from skimage import restoration
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(sharpened_image_skimage, cmap='gray')
plt.title('Sharpened Image (skimage)')
plt.axis('off')
plt.show()
(6) Sharpening Using openCV Built-in Functions
# Define a 3x3 sharpening filter kernel
sharpening_filter_kernel_cv2 = np.array([[ 0, -1, 0],
[-1, 5, -1],
[ 0, -1, 0]])
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(sharpened_image_cv2, cmap='gray')
plt.title('Sharpened Image (OpenCV)')
plt.axis('off')
plt.show()
9. Noise reduction with given image using filtering tech
for y in range(height):
for x in range(width):
region = padded_image[y:y+k_height, x:x+k_width]
result_image[y, x] = np.sum(region * kernel)
plt.subplot(1, 2, 2)
plt.imshow(filtered_image, cmap='gray')
plt.title('Filtered Image (Manual)')
plt.axis('off')
plt.show()
(2) Built-in Function Implementation Using skimage
from skimage import filters
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(filtered_image_skimage, cmap='gray')
plt.title('Filtered Image (skimage)')
plt.axis('off')
plt.show()
(3) Built-in Function Implementation Using OpenCV
import cv2
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(filtered_image_cv2, cmap='gray')
plt.title('Filtered Image (OpenCV)')
plt.axis('off')
plt.show()
10. Solving a segmentation problem (point/line/edge
detection)
# Compute gradients
dx = np.gradient(image_array, axis=1)
dy = np.gradient(image_array, axis=0)
# Compute products of gradients
Ix2 = gaussian_filter(dx[0]**2, sigma)
Iy2 = gaussian_filter(dy[0]**2, sigma)
Ixy = gaussian_filter(dx[0]*dy[0], sigma)
return R
plt.subplot(1, 2, 2)
plt.imshow(corners, cmap='hot')
plt.title('Harris Corners (Manual)')
plt.axis('off')
plt.show()
(ii) Using Built-in Function skimage
from skimage.feature import corner_harris, corner_peaks
plt.subplot(1, 2, 2)
plt.imshow(image, cmap='gray')
plt.scatter(corner_peaks_result[:, 1], corner_peaks_result[:, 0], c='red', s=1)
plt.title('Harris Corners (skimage)')
plt.axis('off')
plt.show()
(2) Line Detection
(i) Manual Implementation (Using Hough Line Transform)
from skimage import transform, feature
from skimage.color import rgb2gray
# Apply edge detection
edges = feature.canny(image)
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(edges, cmap='gray')
plt.title('Edges')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(np.log(1 + hspace), cmap='hot')
plt.title('Hough Space')
plt.axis('off')
plt.show()
(ii) Using Built-in Function skimage
from skimage.transform import probabilistic_hough_line
# Display results
plt.figure(figsize=(12, 6))
plt.imshow(image, cmap='gray')
for line in lines:
p0, p1 = line
plt.plot((p0[1], p1[1]), (p0[0], p1[0]), 'r-')
plt.title('Detected Lines (skimage)')
plt.axis('off')
plt.show()
# Sobel filters
sobel_x = np.array([[1, 0, -1],
[2, 0, -2],
[1, 0, -1]])
sobel_y = np.array([[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]])
plt.subplot(1, 2, 2)
plt.imshow(edges, cmap='gray')
plt.title('Edges (Manual)')
plt.axis('off')
plt.show()
(ii) Using Built-in Function skimage
from skimage import filters
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(edges_skimage, cmap='gray')
plt.title('Edges (skimage)')
plt.axis('off')
plt.show()
11. Use of thresholding for a given problem
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(binary_image, cmap='gray')
plt.title('Binary Image (Manual)')
plt.axis('off')
plt.show()
(2) Built-in Function Implementation Using skimage
from skimage import filters
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(binary_image_skimage, cmap='gray')
plt.title('Binary Image (Otsu - skimage)')
plt.axis('off')
plt.show()
(3) Built-in Function Implementation Using openCV for Binary Thresholding
import cv2
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(binary_image_cv2, cmap='gray')
plt.title('Binary Image (OpenCV)')
plt.axis('off')
plt.show()
(4) Built-in Function Implementation Using openCV for Adaptive Thresholding
# Apply adaptive thresholding using OpenCV
binary_image_adaptive_cv2 = cv2.adaptiveThreshold(image, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(binary_image_adaptive_cv2, cmap='gray')
plt.title('Binary Image (Adaptive - OpenCV)')
plt.axis('off')
plt.show()