























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
























Name: Adiyan Ahmed Redg No: 22-CP-
[ ]: # Import necessary libraries import cv import numpy as np import matplotlib.pyplot as plt %matplotlib inline from google.colab import files from IPython.display import Image, display
# Step 1: Upload image from your computer print(" Please upload an image file:") uploaded = files.upload()
# Step 2: Get uploaded file name image_path = list(uploaded.keys())[0] print(f" Image uploaded successfully: { image_path } ")
# Step 3: Read the image using OpenCV img = cv2.imread(image_path, cv2.IMREAD_COLOR)
# Display the uploaded image display(Image(filename=image_path, width=400))
# --- Brightness Adjustment --- matrix = np.ones(img.shape, dtype='uint8') * 30 img_brighter = cv2.add(img, matrix) img_darker = cv2.subtract(img, matrix)
# Display the images plt.figure(figsize=[18,5]) plt.subplot(131); plt.imshow(img_darker[:,:,::-1]); plt.title('Darker')
plt.subplot(132); plt.imshow(img[:,:,::-1]); plt.title('Original') plt.subplot(133); plt.imshow(img_brighter[:,:,::-1]); plt.title('Brighter') plt.show()
# --- Contrast Adjustment (Method 1) --- matrix1 = np.ones(img.shape) * 0. matrix2 = np.ones(img.shape) * 1.
img_lower = np.uint8(cv2.multiply(np.float64(img), matrix1)) img_higher = np.uint8(cv2.multiply(np.float64(img), matrix2))
plt.figure(figsize=[18,5]) plt.subplot(131); plt.imshow(img_lower[:,:,::-1]); plt.title('Lower Contrast') plt.subplot(132); plt.imshow(img[:,:,::-1]); plt.title('Original') plt.subplot(133); plt.imshow(img_higher[:,:,::-1]); plt.title('Higher Contrast') plt.show()
# --- Contrast Adjustment (Method 2) --- matrix_ones = np.ones(img.shape, dtype='float64') img_lower = np.uint8(cv2.multiply(np.float64(img), matrix_ones, scale=.8)) img_higher = np.uint8(np.clip(cv2.multiply(np.float64(img), matrix_ones,␣ ↪scale=1.2), 0, 255))
plt.figure(figsize=[18,5]) plt.subplot(131); plt.imshow(img_lower[:,:,::-1]); plt.title('Lower Contrast') plt.subplot(132); plt.imshow(img[:,:,::-1]); plt.title('Original') plt.subplot(133); plt.imshow(img_higher[:,:,::-1]); plt.title('Higher Contrast') plt.show()
Please upload an image file:
Saving new-zealand-lake.jpg to new-zealand-lake.jpg Image uploaded successfully: new-zealand-lake.jpg
[ ]: # Imports import cv import numpy as np import matplotlib.pyplot as plt %matplotlib inline
from google.colab import files from IPython.display import Image, display
def upload_image(): print(" Please upload an image file (grayscale or color):") uploaded = files.upload() img_name = list(uploaded.keys())[0] print("Uploaded:", img_name) return img_name
def read_image(img_path, as_gray= False ): if as_gray: return cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) else : # read color & convert to grayscale later if needed return cv2.imread(img_path, cv2.IMREAD_COLOR)
def show_img(img, title="", cmap= None , size=(6,6)): plt.figure(figsize=size) if cmap: plt.imshow(img, cmap=cmap) else : # If color, convert BGR → RGB if len(img.shape) == 3: plt.imshow(img[:,:,::-1]) else :
plt.imshow(img, cmap='gray') plt.title(title) plt.axis('off') plt.show()
def threshold_simple(gray_img, thresh_val=127): # Binary threshold: pixels > thresh_val → max (255); else 0 _, th = cv2.threshold(gray_img, thresh_val, 255, cv2.THRESH_BINARY) return th
def threshold_inverse(gray_img, thresh_val=127): _, th_inv = cv2.threshold(gray_img, thresh_val, 255, cv2.THRESH_BINARY_INV) return th_inv
def threshold_truncate(gray_img, thresh_val=127): _, th_trunc = cv2.threshold(gray_img, thresh_val, 255, cv2.THRESH_TRUNC) return th_trunc
def threshold_tozero(gray_img, thresh_val=127): _, th_tozero = cv2.threshold(gray_img, thresh_val, 255, cv2.THRESH_TOZERO) return th_tozero
def threshold_tozero_inv(gray_img, thresh_val=127): _, th_tozero_inv = cv3.threshold(gray_img, thresh_val, 255, cv2. ↪THRESH_TOZERO_INV) return th_tozero_inv
def threshold_otsu(gray_img): # Otsu's thresholding (automatically finds threshold) _, th_otsu = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY + cv2. ↪THRESH_OTSU) return th_otsu
def threshold_adaptive(gray_img, method="mean", block_size=11, C=2): """ method: "mean" or "gaussian" block_size: size of neighbourhood (must be odd, >1) C: constant subtracted from mean """ if method == "mean": return cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, block_size, C) elif method == "gaussian": return cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
raise ValueError ("Could not read the image. Check the file format or path.") process_and_show_all(img_color)
Please upload an image file (grayscale or color):
Saving road_lanes.png to road_lanes.png Uploaded: road_lanes.png
[ ]: import cv import numpy as np import matplotlib.pyplot as plt %matplotlib inline
from google.colab import files from IPython.display import Image, display
def upload_images(): print(" Please upload two images of same size (for binary operations): ↪") uploaded = files.upload() keys = list(uploaded.keys()) if len(keys) < 2: raise ValueError ("Please upload two images.") return keys[0], keys[1]
def read_image(path, gray= False ): if gray: return cv2.imread(path, cv2.IMREAD_GRAYSCALE) else : return cv2.imread(path, cv2.IMREAD_COLOR)
def show(img, title="", cmap= None , size=(6,6)): plt.figure(figsize=size) if cmap: plt.imshow(img, cmap=cmap) else : if img.ndim == 3: plt.imshow(img[:,:,::-1]) # BGR → RGB else : plt.imshow(img, cmap='gray') plt.title(title) plt.axis('off') plt.show()
def resize_to_same(img1, img2): h1, w1 = img1.shape[:2] h2, w2 = img2.shape[:2] if (h1, w1) != (h2, w2): img2 = cv2.resize(img2, (w1, h1))
return img1, img
def logical_operations_demo(img1, img2): # Convert to grayscale for simpler binary logic demo (optional) gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
_# Optionally threshold them to get binary masks
_, mask1 = cv2.threshold(gray1, 127, 255, cv2.THRESH_BINARY) _, mask2 = cv2.threshold(gray2, 127, 255, cv2.THRESH_BINARY)
show(mask1, "Mask 1", cmap='gray') show(mask2, "Mask 2", cmap='gray')
# Bitwise operations and_img = cv2.bitwise_and(mask1, mask2) or_img = cv2.bitwise_or(mask1, mask2) xor_img = cv2.bitwise_xor(mask1, mask2) not1 = cv2.bitwise_not(mask1) not2 = cv2.bitwise_not(mask2)
show(and_img, "Bitwise AND", cmap='gray') show(or_img, "Bitwise OR", cmap='gray') show(xor_img, "Bitwise XOR", cmap='gray') show(not1, "Bitwise NOT (mask1)", cmap='gray') show(not2, "Bitwise NOT (mask2)", cmap='gray')
_# Also, show overlay/composite using a mask on a color image
mask1_3c = cv2.merge([mask1, mask1, mask1]) result_overlay = cv2.bitwise_and(img2, mask1_3c) show(result_overlay, "Overlay img2 where mask1 is ON")
def main(): img_path1, img_path2 = upload_images() img1 = read_image(img_path1, gray= False ) img2 = read_image(img_path2, gray= False ) if img1 is None or img2 is None : raise ValueError ("One of the images could not be read.") img1, img2 = resize_to_same(img1, img2) show(img1, "Image 1 (color)") show(img2, "Image 2 (color)") logical_operations_demo(img1, img2)
if name == "main":
if len(keys) < 2: raise ValueError ("Need two images") return keys[0], keys[1]
def show(img, title="", cmap= None , size=(6,6)): plt.figure(figsize=size) if cmap: plt.imshow(img, cmap=cmap) else : if img.ndim == 3: plt.imshow(img[:,:,::-1]) # convert BGR → RGB else : plt.imshow(img, cmap='gray') plt.title(title) plt.axis('off') plt.show()
def blend_using_alpha(fg, bg, alpha_mask): _""" fg: foreground color image (H x W x 3) bg: background color image (H x W x 3) alpha_mask: single channel mask (H x W) with values 0–255 (uint8) returns: blended result """
alpha = alpha_mask.astype(float) / 255. # Make 3-channel alpha alpha_3 = np.dstack([alpha, alpha, alpha]) # Blend: result = fg * alpha + bg * (1 - alpha) blended = fg.astype(float)alpha_3 + bg.astype(float)(1.0 - alpha_3) blended = blended.astype(np.uint8) return blended
def main(): fg_path, bg_path = upload_images() fg = cv2.imread(fg_path, cv2.IMREAD_UNCHANGED) # try to read with alpha if ␣ ↪ present bg = cv2.imread(bg_path, cv2.IMREAD_COLOR)
if fg is None or bg is None : raise ValueError ("Error reading images")
# Check if fg has alpha channel if fg.shape[2] == 4: # Separate color + alpha fg_color = fg[:, :, :3] alpha_mask = fg[:, :, 3]
else : # No alpha in input; we’ll create one (e.g. from threshold, or user ␣ ↪ mask) fg_color = fg # Convert to grayscale and threshold to make a mask (simple example) gray = cv2.cvtColor(fg_color, cv2.COLOR_BGR2GRAY) _, alpha_mask = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Resize background to match foreground (if needed) h, w = fg_color.shape[:2] bg = cv2.resize(bg, (w, h))
# Show inputs show(fg_color, "Foreground (color)") show(alpha_mask, "Alpha mask (0=transparent, 255=opaque)", cmap='gray') show(bg, "Background")
# Blend result = blend_using_alpha(fg_color, bg, alpha_mask) show(result, "Result (Foreground over Background)")
if name == "main": main()
Upload two images: foreground (with transparency or mask) and background
Saving kangaroo_sign_with_green_marker.jpg to kangaroo_sign_with_green_marker.jpg Saving opencv_logo.png to opencv_logo.png