Objective: To perform basic image operations using the Python Imaging Library (PIL) and OpenCV.
!pip install opencv-python
!pip install pillow
!pip install matplotlib
import cv2
from google.colab.patches import cv2_imshow
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# Open the image.
img = cv2.imread("content/cv.png")
cv2_imshow(img)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Display sizes of original and grayscale images
print(f"Original Image Size: {img.shape}")
print(f"Grayscale Image Size: {gray_img.shape}")
# Display both images
cv2_imshow(img)
cv2_imshow(gray_img)
blue_channel = img[:,:,0]
green_channel = img[:,:,1]
red_channel = img[:,:,2]
# Display individual channels
print("Blue Channel Shape:", blue_channel.shape)
print("Green Channel Shape:", green_channel.shape)
print("Red Channel Shape:", red_channel.shape)
# Display individual channel images
cv2_imshow(blue_channel)
cv2_imshow(green_channel)
cv2_imshow(red_channel)
plt.imshow(img)
bad_img = cv2.imread("content/lata.png")
cv2_imshow(bad_img)
median_blurred = cv2.medianBlur(bad_img, 3)
cv2_imshow(median_blurred)
low_pass_filtered = cv2.GaussianBlur(median_blurred, (3, 3),0)
cv2_imshow(low_pass_filtered)
import cv2
from google.colab.patches import cv2_imshow
import numpy as np
import matplotlib.pyplot as plt
def transform_image(image, angle, scale):
rows, cols = image.shape[:2]
center = (cols / 2, rows / 2)
M = cv2.getRotationMatrix2D(center, angle, scale)
transformed_img = cv2.warpAffine(image, M, (cols, rows))
return transformed_img
def kmeans_clustering(image, k):
pixel_vals = image.reshape((-1, 1))
pixel_vals = np.float32(pixel_vals)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.85)
_, labels, centers = cv2.kmeans(pixel_vals, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
centers = np.uint8(centers)
clustered_image = centers[labels.flatten()]
clustered_image = clustered_image.reshape(image.shape)
return clustered_image
img = cv2.imread("clock.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
resized_img = cv2.resize(gray_img, (400, 450))
cv2_imshow(resized_img)
angle = 45
scale = 0.5
rotated_img = transform_image(resized_img, angle, scale)
correct_k = 3
undersampled_k = 2
oversampled_k = 5
correctly_sampled_img = kmeans_clustering(rotated_img, correct_k)
undersampled_img = cv2.resize(rotated_img, (200, 225))
undersampled_result = kmeans_clustering(undersampled_img, undersampled_k)
oversampled_img = cv2.resize(rotated_img, (800, 900))
oversampled_result = kmeans_clustering(oversampled_img, oversampled_k)
plt.figure(figsize=(12, 8))
plt.subplot(1, 3, 1)
plt.imshow(correctly_sampled_img, cmap='gray')
plt.title('Correctly Sampled')
plt.subplot(1, 3, 2)
plt.imshow(undersampled_result, cmap='gray')
plt.title('Undersampled')
plt.subplot(1, 3, 3)
plt.imshow(oversampled_result, cmap='gray')
plt.title('Oversampled')
plt.show()