0% found this document useful (0 votes)
12 views6 pages

Image Formation

The document outlines a series of image processing tasks aimed at understanding geometric transformations, photometric models, sampling, quantization, and neighborhood metrics. Each section includes objectives, instructions, and code snippets for performing operations such as translation, rotation, brightness adjustment, downsampling, and calculating neighborhood metrics. The tasks involve using Python libraries like NumPy, Matplotlib, and PIL to manipulate and display images in a Google Colab environment.

Uploaded by

Arnab Mondal
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)
12 views6 pages

Image Formation

The document outlines a series of image processing tasks aimed at understanding geometric transformations, photometric models, sampling, quantization, and neighborhood metrics. Each section includes objectives, instructions, and code snippets for performing operations such as translation, rotation, brightness adjustment, downsampling, and calculating neighborhood metrics. The tasks involve using Python libraries like NumPy, Matplotlib, and PIL to manipulate and display images in a Google Colab environment.

Uploaded by

Arnab Mondal
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/ 6

19/09/2024, 22:30 Arghyadip Sahu 221003003001 - Colab

Arghyadip Sahu BCS-AI-3C 221003003001

1: Image Formation

● Objective: Understand how geometric transformations affect images. ● Instructions:

1. Write a function to perform translation, rotation, and scaling on an image without using any library functions.
2. Use a sample image and apply each transformation.
3. Display the original and transformed images side by side.

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from google.colab import files
def upload_image():
uploaded = files.upload()
image_path = next(iter(uploaded.keys()))
return Image.open(image_path)
# Function to perform translation
def translate(image, tx, ty):
img_array = np.array(image)
height, width, _ = img_array.shape
new_img_array = np.zeros_like(img_array)

for y in range(height):
for x in range(width):
new_x = int(x + tx)
new_y = int(y + ty)
if 0 <= new_x < width and 0 <= new_y < height:
new_img_array[new_y, new_x] = img_array[y, x]

return Image.fromarray(new_img_array)
def rotate(image, angle):
theta = np.radians(angle)
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)

R = np.array([
[cos_theta, -sin_theta],
[sin_theta, cos_theta]
])

img_array = np.array(image)
height, width, _ = img_array.shape
center_x, center_y = width // 2, height // 2
new_img_array = np.zeros_like(img_array)

for y in range(height):
for x in range(width):
tx, ty = x - center_x, y - center_y
new_tx, new_ty = R.dot([tx, ty])
new_x, new_y = int(new_tx + center_x), int(new_ty + center_y)

if 0 <= new_x < width and 0 <= new_y < height:


new_img_array[new_y, new_x] = img_array[y, x]

return Image.fromarray(new_img_array)
def scale(image, sx, sy):
img_array = np.array(image)
height, width, _ = img_array.shape
new_img_array = np.zeros_like(img_array)

for y in range(height):
for x in range(width):
new_x, new_y = int(x * sx), int(y * sy)

if 0 <= new_x < width and 0 <= new_y < height:


new_img_array[new_y, new_x] = img_array[y, x]

return Image.fromarray(new_img_array)
def main():
image = upload_image()
translated_image = translate(image, 50, 30)
rotated_image = rotate(image, 45)
scaled_image = scale(image, 1.5, 1.5)
fig, ax = plt.subplots(1, 4, figsize=(16, 4))

https://colab.research.google.com/drive/1MtX7ZVviBFjVWnSwLGhHjyw6pnO7hiAF?usp=classroom_web#scrollTo=znDPGFSDrF9C&printMode=true 1/6
19/09/2024, 22:30 Arghyadip Sahu 221003003001 - Colab

ax[0].imshow(image)
ax[0].set_title('Original')
ax[0].axis('off')

ax[1].imshow(translated_image)
ax[1].set_title('Translated')
ax[1].axis('off')

ax[2].imshow(rotated_image)
ax[2].set_title('Rotated')
ax[2].axis('off')

ax[3].imshow(scaled_image)
ax[3].set_title('Scaled')
ax[3].axis('off')

plt.show()
if __name__ == '__main__':
main()

Choose files No file chosen Upload widget is only available when the cell has been
executed in the current browser session. Please rerun this cell to enable.
Saving dog1.jpg to dog1.jpg

2: Photometric Models

● Objective: Understand how lighting conditions affect pixel intensities. ● Instructions:

1. Write a function to simulate different lighting conditions (e.g., increase brightness, decrease brightness).
2. Apply these changes to a sample image.
3. Display the original and altered images.

https://colab.research.google.com/drive/1MtX7ZVviBFjVWnSwLGhHjyw6pnO7hiAF?usp=classroom_web#scrollTo=znDPGFSDrF9C&printMode=true 2/6
19/09/2024, 22:30 Arghyadip Sahu 221003003001 - Colab
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from google.colab import files
def upload_and_load_image():
uploaded = files.upload()
image_path = next(iter(uploaded))
img = Image.open(image_path).convert('RGB')
return np.array(img), image_path
def increase_brightness(image, amount):
image_float = image.astype(np.float32)
brightened_image = np.clip(image_float + amount, 0, 255).astype(np.uint8)
return brightened_image
def decrease_brightness(image, amount):
image_float = image.astype(np.float32)
darkened_image = np.clip(image_float - amount, 0, 255).astype(np.uint8)
return darkened_image
def process_and_display_lighting_changes(brightness_increase, brightness_decrease):
image_array, image_path = upload_and_load_image()
brightened_image = increase_brightness(image_array, brightness_increase)
darkened_image = decrease_brightness(image_array, brightness_decrease)
plt.figure(figsize=(15, 5))
plt.subplot(1, 3, 1)

plt.imshow(image_array)
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 3, 2)
plt.imshow(brightened_image)
plt.title(f'Increased Brightness (+{brightness_increase})')
plt.axis('off')
plt.subplot(1, 3, 3)
plt.imshow(darkened_image)
plt.title(f'Decreased Brightness (-{brightness_decrease})')
plt.axis('off')
plt.show()
process_and_display_lighting_changes(brightness_increase=100, brightness_decrease=150)

Choose files No file chosen Upload widget is only available when the cell has been
executed in the current browser session. Please rerun this cell to enable.
Saving otter-sea-wallpaper-preview.jpg to otter-sea-wallpaper-preview.jpg

3: Sampling and Quantization

● Objective: Understand the effects of sampling and quantization on image quality. ● Instructions:

1. Write a function to downsample and upsample an image.

2. Write a function to quantize an image to different levels (e.g., 2-bit, 4-bit).

3. Apply these functions to a sample image.

4. Display the results on image quality.

https://colab.research.google.com/drive/1MtX7ZVviBFjVWnSwLGhHjyw6pnO7hiAF?usp=classroom_web#scrollTo=znDPGFSDrF9C&printMode=true 3/6
19/09/2024, 22:30 Arghyadip Sahu 221003003001 - Colab
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from google.colab import files
def upload_and_load_image():
uploaded = files.upload()
image_path = next(iter(uploaded))
img = Image.open(image_path)
return np.array(img), image_path
def downsample_image(image, factor):
image_pil = Image.fromarray(image)
new_size = (int(image_pil.width / factor), int(image_pil.height / factor))
downsampled_image = image_pil.resize(new_size, Image.ANTIALIAS)
return np.array(downsampled_image)
def upsample_image(image, original_size):
image_pil = Image.fromarray(image)
upsampled_image = image_pil.resize(original_size, Image.ANTIALIAS)
return np.array(upsampled_image)
def quantize_image(image, bits):
image_pil = Image.fromarray(image)
if image_pil.mode != 'L':
image_pil = image_pil.convert('L')
levels = 2 ** bits
factor = 255 // (levels - 1)
image_array = np.array(image_pil)
quantized_array = (image_array // factor) * factor
quantized_image = Image.fromarray(quantized_array.astype(np.uint8))
return np.array(quantized_image)
def process_and_display_image(downsample_factor, quantize_bits_list):
image_array, image_path = upload_and_load_image()
original_size = (image_array.shape[1], image_array.shape[0])
downsampled_image = downsample_image(image_array, downsample_factor)
upsampled_image = upsample_image(downsampled_image, original_size)
quantized_images = {bits: quantize_image(image_array, bits) for bits in quantize_bits_list}
plt.figure(figsize=(15, 15))
plt.subplot(len(quantize_bits_list) + 2, 2, 1)
plt.imshow(image_array)
plt.title('Original Image')
plt.axis('off')
plt.subplot(len(quantize_bits_list) + 2, 2, 2)
plt.imshow(downsampled_image)
plt.title('Downsampled Image')
plt.axis('off')
plt.subplot(len(quantize_bits_list) + 2, 2, 3)
plt.imshow(upsampled_image)
plt.title('Upsampled Image')
plt.axis('off')
for idx, bits in enumerate(quantize_bits_list):
plt.subplot(len(quantize_bits_list) + 2, 2, 4 + idx * 2)
plt.imshow(quantized_images[bits], cmap='gray')
plt.title(f'{bits}-bit Quantized Image')
plt.axis('off')
plt.show()
process_and_display_image(downsample_factor=4, quantize_bits_list=[2, 4])

https://colab.research.google.com/drive/1MtX7ZVviBFjVWnSwLGhHjyw6pnO7hiAF?usp=classroom_web#scrollTo=znDPGFSDrF9C&printMode=true 4/6
19/09/2024, 22:30 Arghyadip Sahu 221003003001 - Colab

Choose files No file chosen Upload widget is only available when the cell has been executed in the current browser session. Please rerun this
cell to enable.
Saving OIP.jfif to OIP.jfif
<ipython-input-17-d29df8e7425f>:13: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (202
downsampled_image = image_pil.resize(new_size, Image.ANTIALIAS)
<ipython-input-17-d29df8e7425f>:17: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (202
upsampled_image = image_pil.resize(original_size, Image.ANTIALIAS)

4: Image Definition and Neighbourhood Metrics

● Objective: Understand how images are defined and represented, and explore neighborhood metrics. ● Instructions:

1. Define an image as a 2D matrix and implement functions to compute basic neighborhood metrics (e.g., mean, median, standard deviation
within a neighborhood).
2. Apply these metrics to a sample image.
3. Display the results and discuss their significance.

https://colab.research.google.com/drive/1MtX7ZVviBFjVWnSwLGhHjyw6pnO7hiAF?usp=classroom_web#scrollTo=znDPGFSDrF9C&printMode=true 5/6
19/09/2024, 22:30 Arghyadip Sahu 221003003001 - Colab
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from google.colab import files
from scipy.ndimage import generic_filter
def upload_and_load_image():
uploaded = files.upload()
image_path = next(iter(uploaded))
img = Image.open(image_path).convert('L')
return np.array(img), image_path
def neighborhood_mean(image, size=3):
def mean_func(window):
return np.mean(window)
return generic_filter(image, mean_func, size=size)
def neighborhood_median(image, size=3):
def median_func(window):
return np.median(window)
return generic_filter(image, median_func, size=size)
def neighborhood_std(image, size=3):
def std_func(window):
return np.std(window)
return generic_filter(image, std_func, size=size)
def process_and_display_metrics():
image_array, image_path = upload_and_load_image()
mean_image = neighborhood_mean(image_array, size=3)
median_image = neighborhood_median(image_array, size=3)
std_image = neighborhood_std(image_array, size=3)
plt.figure(figsize=(15, 12))
plt.subplot(2, 2, 1)
plt.imshow(image_array, cmap='gray')
plt.title('Original Image')
l i (' ff')

https://colab.research.google.com/drive/1MtX7ZVviBFjVWnSwLGhHjyw6pnO7hiAF?usp=classroom_web#scrollTo=znDPGFSDrF9C&printMode=true 6/6

You might also like