OpenCV Python Program | Load, Convert, Crop, and Save Image Example
SOLUTION……
import cv2 # (a) Load an image and give it a title img = cv2.imread('2.png') # Replace 'image.jpg' with your image filename cv2.imshow('Original Image', img) # (b) Change the colour of image and convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow('Grayscale Image', gray) # (c) Print the shape of the image print("Shape of Image:", img.shape) # (Height, Width, Channels) # (d) Display the maximum and minimum pixels of the image print("Maximum Pixel Value:", img.max()) print("Minimum Pixel Value:", img.min()) # (e) Crop the image and extract a part of it cropped = img[50:200, 100:300] # [y1:y2, x1:x2] cv2.imshow('Cropped Image', cropped) # (f) Save the cropped image cv2.imwrite('cropped_image.jpg', cropped) print("Cropped image saved successfully as 'cropped_image.jpg'") # Wait until a key is pressed and close all windows cv2.waitKey(0) cv2.destroyAllWindows()