Code With Python
39.2K subscribers
888 photos
27 videos
22 files
770 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Topic: Python OpenCV – Part 3: Contours, Morphological Operations, and Image Masking

---

1. Finding Contours

Contours are curves joining all continuous points along a boundary having the same color or intensity.

import cv2

image = cv2.imread('shapes.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Threshold to get binary image
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Draw contours
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)

cv2.imshow("Contours", image)
cv2.waitKey(0)
cv2.destroyAllWindows()


---

2. Morphological Operations

• Used to remove noise or fill gaps.

* Erosion: Removes pixels on object boundaries.

* Dilation: Adds pixels to object boundaries.

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

eroded = cv2.erode(thresh, kernel, iterations=1)
dilated = cv2.dilate(thresh, kernel, iterations=1)


• Other useful operations:

* Opening: erosion followed by dilation (removes noise).

* Closing: dilation followed by erosion (closes small holes).

opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)


---

3. Image Masking

• Use a mask to isolate part of an image.

mask = cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)
masked_img = cv2.bitwise_and(image, mask)

cv2.imshow("Masked Image", masked_img)
cv2.waitKey(0)
cv2.destroyAllWindows()


---

Summary

Contours help detect shapes and boundaries.

Morphological operations clean up binary images by removing noise or filling holes.

Masks isolate regions of interest for further processing.

---

Exercise

• Load an image with multiple shapes, use contour detection to count the number of distinct shapes, then draw bounding rectangles around each.

---

#Python #OpenCV #Contours #Morphology #ImageMasking

https://t.iss.one/DataScience4
3