Opening, shrinking and saving images with Pillow
Preparing dataset images at a uniform size.
Goal: Converting an image to grayscale, detecting edges and counting shapes.
import cv2, numpy as np
img = np.zeros((200, 300, 3), dtype=np.uint8)
cv2.rectangle(img, (20, 20), (90, 90), (255, 255, 255), -1)
cv2.circle(img, (160, 100), 40, (0, 255, 0), -1)
cv2.ellipse(img, (250, 150), (30, 20), 0, 0, 360, (0, 0, 255), -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("Edge pixels:", int((edges > 0).sum()))
print("Number of shapes:", len(contours))
print("Areas:", sorted(int(cv2.contourArea(c)) for c in contours))
We draw three shapes on a black image, then apply the Canny filter to detect edges and findContours to extract and count the outer contours. Remember that OpenCV stores channels in BGR order.
Edge pixels: 712 Number of shapes: 3 Areas: [1884, 4900, 4912]
This example was actually run and tested on 21 November 2026 on a CPU — opencv-python-headless 5.1.0.95, numpy 2.5.5, python 3.13.18
Preparing dataset images at a uniform size.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.