import cv2
import requests
import numpy as np
import matplotlib.pyplot as plt
# Fetch the image from the URL using requests
url = 'https://i.postimg.cc/KYWtQ9YP/Capture-d-cran-2024-09-25-093130.png'
response = requests.get(url)
image = np.asarray(bytearray(response.content), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply a Gaussian blur to the image
blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)
# Detect edges using the Canny edge detection algorithm
edges = cv2.Canny(blurred_image, 100, 200)
# Find contours from the edges
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Count the number of contours detected
contour_count = len(contours)
# Create a copy of the original image for labeling
labeled_image = image.copy()
# Loop through each contour and label it
for i, contour in enumerate(contours):
# Get the contour's bounding rectangle to place the label
x, y, w, h = cv2.boundingRect(contour)
# Create the label (contour number)
label = f'{i + 1}'
# Add label to the image in red color with a small offset
cv2.putText(labeled_image, label, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
# Draw contours on the labeled image
cv2.drawContours(labeled_image, contours, -1, (0, 255, 0), 1)
# Display the original and processed images
plt.figure(figsize=(10, 7))
plt.subplot(2, 2, 1)
plt.title('Original Image')
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.subplot(2, 2, 2)
plt.title('Grayscale Image')
plt.imshow(gray_image, cmap='gray')
plt.axis('off')
plt.subplot(2, 2, 3)
plt.title('Blurred Image')
plt.imshow(blurred_image, cmap='gray')
plt.axis('off')
# Display the labeled image with contour numbers
plt.subplot(2, 2, 4)
plt.title(f'Contours Detected (Count: {contour_count})')
plt.imshow(cv2.cvtColor(labeled_image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.tight_layout()
plt.show()
# Print contours count
print(f'Number of contours detected: {contour_count}') Click Run or press shift + ENTER to run code