Edge and contour detection with OpenCV
Converting an image to grayscale, detecting edges and counting shapes.
Goal: Preparing dataset images at a uniform size.
from PIL import Image, ImageOps
img = Image.new("RGB", (640, 480), (30, 120, 200))
img.save("sample.jpg", quality=90)
im = Image.open("sample.jpg")
print("Original size:", im.size, im.mode)
im.thumbnail((224, 224))
print("After thumbnail:", im.size)
sq = ImageOps.fit(Image.open("sample.jpg"), (224, 224))
print("After square crop:", sq.size, "| grey:", sq.convert("L").mode)
We create an image, save it and reopen it, use thumbnail to shrink it while keeping the aspect ratio, and convert to change colour modes.
Original size: (640, 480) RGB After thumbnail: (224, 168) After square crop: (224, 224) | grey: L
This example was actually run and tested on 21 November 2026 on a CPU — pillow 13.0.0, python 3.13.18
Converting an image to grayscale, detecting edges and counting shapes.
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.