Digital Image Processing Lab Manual
Digital Image Processing Lab Manual
You can use the Python library Pillow (PIL) to extract different attributes of an image, such as:
# Load an image
img = Image.open(image_path)
print(f"Filename: {img.filename}")
print(f"Format: {img.format}")
print(f"Mode: {img.mode}")
exif_data = img._getexif()
if exif_data:
print("\nEXIF Data:")
print(f"{tag_name}: {value}")
1
else:
Explanation
Sample Output
Filename: sample.jpg
Format: JPEG
Mode: RGB
EXIF Data:
Make: Canon
ExposureTime: 1/250
FNumber: 2.8
...
2
2. Write a program to display gray scale image, resize image, transform image.
You can use the Pillow (PIL) library in Python to:
Python Program
# Load an image
img = Image.open(image_path)
# Convert to grayscale
gray_img = img.convert("L")
gray_img.show(title="Grayscale Image")
resized_img = img.resize(new_size)
resized_img.show(title="Resized Image")
# Apply transformations
rotated_img.show(title="Rotated Image")
flipped_img.show(title="Flipped Image")
3
# Save modified images
gray_img.save("gray_image.jpg")
resized_img.save("resized_image.jpg")
rotated_img.save("rotated_image.jpg")
flipped_img.save("flipped_image.jpg")
Explanation
Expected Output
A grayscale image
A resized image (300×300 pixels)
A rotated image (45° rotation)
A flipped image (mirrored horizontally)
4
3. Write a program to convert color image to gray scale image, Color image into
Binary Image, Separate color image into three separate R, G, B planes, combine
three separate R, G, B planes to create color image.
Here’s a Python program that performs the following operations using the OpenCV (cv2) library:
Python Program
import cv2
import numpy as np
img = cv2.imread(image_path)
# Convert to grayscale
B, G, R = cv2.split(img)
5
# Display images
cv2.imshow("Original Image", img)
cv2.imshow("Grayscale Image", gray_img)
cv2.imshow("Binary Image", binary_img)
cv2.imshow("Red Channel", R)
cv2.imshow("Green Channel", G)
cv2.imshow("Blue Channel", B)
cv2.imshow("Merged Image", merged_img)
cv2.imwrite("gray_image.jpg", gray_img)
cv2.imwrite("binary_image.jpg", binary_img)
cv2.imwrite("red_channel.jpg", R)
cv2.imwrite("green_channel.jpg", G)
cv2.imwrite("blue_channel.jpg", B)
cv2.imwrite("merged_image.jpg", merged_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation
1. Convert to Grayscale:
o cv2.cvtColor(img, cv2.COLOR_BGR2GRAY): Converts the color image to grayscale.
2. Convert to Binary:
o cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY): Converts grayscale
to binary using a threshold of 127.
3. Split RGB Channels:
o cv2.split(img): Splits the image into Red, Green, and Blue channels.
4. Merge RGB Channels Back:
o cv2.merge([B, G, R]): Combines the separate color planes to reconstruct the
original image.
5. Display and Save Images:
o cv2.imshow() → Displays images.
o cv2.imwrite() → Saves images for later use.
Expected Output
Grayscale Image
Binary (Black & White) Image
Red, Green, and Blue Channel Images
Reconstructed (Merged) Image
6
4. Write a program for Flip given image horizontally, modify program of
horizontal flipping for getting vertical flipping, Perform image arithmetic
operation.
Here’s a Python program that performs the following operations using OpenCV (cv2):
Python Program
import cv2
import numpy as np
img = cv2.imread(image_path)
horizontal_flip = cv2.flip(img, 1)
vertical_flip = cv2.flip(img, 0)
7
# Image Subtraction (Darkening)
# Display images
cv2.imshow("Original Image", img)
cv2.imshow("Horizontally Flipped Image", horizontal_flip)
cv2.imshow("Vertically Flipped Image", vertical_flip)
cv2.imshow("Brightened Image (Addition)", brightened_img)
cv2.imshow("Darkened Image (Subtraction)", darkened_img)
cv2.imwrite("horizontal_flip.jpg", horizontal_flip)
cv2.imwrite("vertical_flip.jpg", vertical_flip)
cv2.imwrite("brightened_image.jpg", brightened_img)
cv2.imwrite("darkened_image.jpg", darkened_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation
1. Flip Horizontally
o cv2.flip(img, 1): Flips the image left-right (mirroring).
2. Flip Vertically
o cv2.flip(img, 0):
Flips the image upside-down.
3. Image Addition (Brightening Effect)
o cv2.add(img, white_img): Increases pixel values to make the image brighter.
4. Image Subtraction (Darkening Effect)
o cv2.subtract(img, white_img): Decreases pixel values to make the image
darker.
5. Displaying & Saving Images
o cv2.imshow() → Displays images.
o cv2.imwrite() → Saves images to disk.
Expected Output
Power Law Transformation is used to enhance images by adjusting brightness and contrast. It
follows the formula:
where:
import cv2
import numpy as np
return transformed_img
# Display results
cv2.imwrite("gamma_0.5.jpg", gamma_low)
cv2.imwrite("gamma_2.0.jpg", gamma_high)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation
Expected Output
10
6. Write a program for Histogram Mapping and Equalization.
import cv2
import numpy as np
equalized_img = cv2.equalizeHist(img)
plt.figure(figsize=(10, 5))
# Original Histogram
plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title("Original Image")
plt.axis("off")
plt.subplot(2, 2, 2)
# Equalized Histogram
plt.subplot(2, 2, 3)
plt.imshow(equalized_img, cmap='gray')
plt.title("Equalized Image")
plt.axis("off")
plt.subplot(2, 2, 4)
plt.tight_layout()
plt.show()
cv2.imwrite("equalized_image.jpg", equalized_img)
Explanation
Expected Output
12
7. Write a program for Image Smoothening and Sharpening.
Image smoothing helps reduce noise, while sharpening enhances the edges in an image.
import cv2
import numpy as np
img = cv2.imread(image_path)
median_blur = cv2.medianBlur(img, 5)
# Sharpening Kernel
13
[-1, 9, -1],
plt.figure(figsize=(12, 8))
# Original Image
plt.subplot(2, 3, 1)
plt.imshow(img)
plt.title("Original Image")
plt.axis("off")
plt.subplot(2, 3, 2)
plt.imshow(gaussian_blur)
plt.title("Gaussian Blur")
plt.axis("off")
plt.subplot(2, 3, 3)
plt.imshow(median_blur)
plt.title("Median Blur")
plt.axis("off")
14
# Bilateral Filtered Image
plt.subplot(2, 3, 4)
plt.imshow(bilateral_blur)
plt.title("Bilateral Filter")
plt.axis("off")
# Sharpened Image
plt.subplot(2, 3, 5)
plt.imshow(sharpened_img)
plt.title("Sharpened Image")
plt.axis("off")
plt.tight_layout()
plt.show()
Explanation
Gaussian Blur: Uses a Gaussian kernel to blur the image and remove noise.
Median Blur: Replaces each pixel with the median of its surrounding pixels; effective against "salt
and pepper" noise.
Bilateral Filter: Reduces noise while preserving edges.
2. Image Sharpening
Expected Output
1. Original Image
2. Gaussian Blurred Image
3. Median Blurred Image
4. Bilateral Filtered Image
5. Sharpened Image
15
8. Write a program for Edge Detection using
Edge detection is used to identify boundaries within an image. This program applies three different
operators:
Sobel Operator: Detects edges in horizontal and vertical directions using gradient-based
detection.
Prewitt Operator: Similar to Sobel but uses a different kernel for calculating gradients.
Roberts Operator: Uses small 2×2 kernels for detecting edges.
import cv2
import numpy as np
prewitt_x = cv2.filter2D(img, -1, np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])) # X-direction
16
prewitt_y = cv2.filter2D(img, -1, np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])) # Y-direction
plt.figure(figsize=(12, 8))
# Original Image
plt.subplot(2, 3, 1)
plt.imshow(img, cmap="gray")
plt.title("Original Image")
plt.axis("off")
plt.subplot(2, 3, 2)
plt.imshow(sobel_combined, cmap="gray")
plt.axis("off")
plt.subplot(2, 3, 3)
17
plt.imshow(prewitt_combined, cmap="gray")
plt.axis("off")
plt.tight_layout()
plt.show()
Explanation
1. Sobel Operator
o Uses 3×3 kernels to detect edges.
o Computes gradients in X and Y directions separately.
o Magnitude is calculated to combine the two gradient components.
2. Prewitt Operator
o Similar to Sobel but with a different filter matrix.
o Less sensitive to noise compared to Sobel.
3. Roberts Operator
o Uses 2×2 kernels, making it computationally less expensive.
o Detects edges at diagonal orientations.
Expected Output
Original Image
Sobel Edge Detection Result
Prewitt Edge Detection Result
Roberts Edge Detection Result
18
9. Write a program to implement segmentation using Global threshold method.
Global thresholding is a simple image segmentation technique that converts a grayscale image into a
binary image based on a threshold value. All pixel values above the threshold are set to white (255),
and all values below are set to black (0).
import numpy as np
plt.figure(figsize=(10, 5))
# Original Image
plt.subplot(1, 2, 1)
plt.imshow(img, cmap="gray")
plt.axis("off")
19
# Thresholded Image
plt.subplot(1, 2, 2)
plt.imshow(binary_img, cmap="gray")
plt.axis("off")
plt.tight_layout()
plt.show()
cv2.imwrite("global_threshold.jpg", binary_img)
Explanation
Expected Output
Next Steps
cv2.THRESH_BINARY, 11, 2)
20
10. Write a program to implement segmentation using local thresholding
method.
Local (or Adaptive) thresholding is useful when the image has varying lighting conditions. Instead
of using a single threshold value for the entire image, it calculates the threshold for small regions.
import cv2
import numpy as np
cv2.THRESH_BINARY, 11, 2)
cv2.THRESH_BINARY, 11, 2)
plt.figure(figsize=(15, 5))
# Original Image
plt.subplot(1, 3, 1)
21
plt.imshow(img, cmap="gray")
plt.axis("off")
plt.subplot(1, 3, 2)
plt.imshow(adaptive_mean, cmap="gray")
plt.axis("off")
plt.subplot(1, 3, 3)
plt.imshow(adaptive_gaussian, cmap="gray")
plt.axis("off")
plt.tight_layout()
plt.show()
cv2.imwrite("adaptive_mean_threshold.jpg", adaptive_mean)
cv2.imwrite("adaptive_gaussian_threshold.jpg", adaptive_gaussian)
Explanation
Expected Output
Next Steps
Try different block sizes (e.g., cv2.adaptiveThreshold(..., 15, 5)) to fine-tune the
segmentation.
Use Otsu’s thresholding for a hybrid approach:
23
11. Write a program for Morphological Operations on Binary Images.
Morphological operations are used for image preprocessing, noise removal, and object shape
analysis. The most common operations include:
import cv2
import numpy as np
# Display results
plt.figure(figsize=(15, 8))
for i in range(6):
plt.subplot(2, 3, i+1)
plt.imshow(images[i], cmap="gray")
plt.title(titles[i])
plt.axis("off")
plt.tight_layout()
plt.show()
cv2.imwrite("erosion.jpg", erosion)
cv2.imwrite("dilation.jpg", dilation)
cv2.imwrite("opening.jpg", opening)
cv2.imwrite("closing.jpg", closing)
cv2.imwrite("gradient.jpg", gradient)
Explanation
25
1. Load the Image: Reads a binary image (black and white).
2. Thresholding: Ensures the image is binary (if not already).
3. Define Kernel: A 5×5 structuring element for operations.
4. Apply Morphological Operations:
o Erosion: Removes small white pixels.
o Dilation: Expands white regions.
o Opening: Removes small noise.
o Closing: Fills small holes.
o Gradient: Highlights edges of objects.
5. Display & Save Results: Shows the original and processed images.
Expected Output
Next Steps
26