๐ธ OpenCV Image Reading
OpenCV is a huge open-source library for computer vision, machine learning, and image processing.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import cv2 import numpy as np # 1. Create a synthetic test image (100x100 with color patches) img = np.zeros((200, 300, 3), dtype="uint8") cv2.rectangle(img, (10, 10), (140, 90), (255, 0, 0), -1) # Blue cv2.rectangle(img, (150, 10), (290, 90), (0, 255, 0), -1) # Green cv2.rectangle(img, (10, 100), (290, 190), (0, 0, 255), -1) # Red cv2.putText(img, "Pynfinity", (70, 155), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 3) print(f"Image shape: {img.shape}") # (200, 300, 3) HxWxC # 2. Color space conversion gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) print(f"Gray shape: {gray.shape}") # (200, 300) โ no channels # 3. Gaussian blur (noise reduction) blurred = cv2.GaussianBlur(gray, (5, 5), 0) # 4. Edge detection (Canny) edges = cv2.Canny(blurred, threshold1=50, threshold2=150) # 5. Resize โ 50% scale small = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) print(f"Resized shape: {small.shape}") # (100, 150, 3) # 6. Pixel statistics print(f"\nChannel means (BGR): {img.mean(axis=(0,1)).round(1)}") print(f"Max pixel value: {img.max()}") # 7. Save outputs cv2.imwrite("pynfinity_original.png", img) cv2.imwrite("pynfinity_edges.png", edges) print("\nSaved: pynfinity_original.png, pynfinity_edges.png")
Keep exploring and happy coding! ๐ป