As a beginner this project would be a great start to learn openCv. In OpenCV, CV applications detect edges first and then collect other information.
There are many edge detection algorithms, and the most popular is the Canny edge detector because it’s pretty effective compared to others. It’s also a complex edge-detection technique. Below are the steps for Canny edge detection:
Reduce noise and smoothen image,
Calculate the gradient,
Non-maximum suppression,
Double the threshold,
Linking and edge detecting – hysteresis.
Edge Detection:
Let’s take a sample image for edge detection with OpenCv

Full Code:
import cv2
import matplotlib.pyplot as plt
# Open the image
img = cv2.imread('my.png')
# Apply Canny
edges = cv2.Canny(img, 100, 200, 3, L2gradient=True)
plt.figure()
plt.title('Astronaut')
plt.imsave('my-image.png', edges, cmap='gray', format='png')
plt.imshow(edges, cmap='gray')
plt.show()
Note: Don’t forget to replace the image path with yours
Output:


Explanation of the above code:
import cv2: This line imports the OpenCV library, which is used for image processing tasks.import matplotlib.pyplot as plt: This line imports the pyplot module from the matplotlib library, which is used for plotting and displaying images.img = cv2.imread('my.png'): This line reads the image file named ‘my.png’ and stores it in the variableimg.edges = cv2.Canny(img, 100, 200, 3, L2gradient=True): This line applies the Canny edge detection algorithm to the imageimg. The parameters100and200are the thresholds for edge detection. The parameter3is the aperture size for the Sobel operator, andL2gradient=Trueindicates that the L2-norm should be used for gradient calculation.plt.figure(): This line creates a new figure for plotting.plt.title('Astronaut'): This line sets the title of the plot to ‘Astronaut’.plt.imsave('my-image.png', edges, cmap='gray', format='png'): This line saves the edges image to a file named ‘my-image.png’. The parametercmap='gray'specifies that the image should be saved in grayscale, andformat='png'specifies the file format as PNG.plt.imshow(edges, cmap='gray'): This line displays the edges image in the plot. The parametercmap='gray'specifies that the image should be displayed in grayscale.plt.show(): This line displays the plot with the edges image.
Now, let us see how we can detect the Countours
Contours are lines joining all the continuous objects or points (along the boundary), having the same color or intensity.
Contours in image processing can be thought of as the outlines or boundaries of objects in an image. Imagine you have a coloring book page with different shapes drawn on it. If you were to trace the outline of each shape with a marker, the lines you draw would represent contours.
In image processing, contours are used to detect and recognize objects or shapes within an image. They can be used for tasks like object detection, shape recognition, and measuring object dimensions. For example, in a medical image, contours could be used to identify and measure the size of tumors.
Full Code:
import cv2
import numpy as np
# this is the code for detecting countour , i have taken an image of a brain, let us see the output
image = cv2.imread('brain.jpg')
#now let me show you the original image
cv2.waitKey(0)
# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)
# Finding Contours
# Use a copy of the image e.g. edged.copy()
# since findContours alters the image
contours, hierarchy = cv2.findContours(edged,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.imshow('Canny Edges After Contouring', edged)
cv2.waitKey(0)
print("Number of Contours found = " + str(len(contours)))
# Draw all contours
# -1 signifies drawing all contours
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
Original Image:

Explanation of the above code:
import cv2: This line imports the OpenCV library, which is used for image processing tasks.import numpy as np: This line imports the NumPy library, which is used for numerical computations.image = cv2.imread('brain.jpg'): This line reads the image file named ‘brain.jpg’ and stores it in the variableimage.cv2.waitKey(0): This line waits indefinitely (until a key is pressed) for the window to close. It is used to display the original image before proceeding to the next step.gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY): This line converts the color image to grayscale, which is easier to process for contour detection.edged = cv2.Canny(gray, 30, 200): This line applies the Canny edge detection algorithm to the grayscale image to detect edges.cv2.waitKey(0): This line again waits indefinitely to display the Canny edges image before proceeding.contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE): This line finds contours in the Canny edges image. Thecv2.RETR_EXTERNALflag retrieves only the external contours, andcv2.CHAIN_APPROX_NONEstores all the boundary points of the contours.cv2.imshow('Canny Edges After Contouring', edged): This line displays the Canny edges image with the detected contours.cv2.waitKey(0): This line waits indefinitely to display the Canny edges image with contours before proceeding.print("Number of Contours found = " + str(len(contours))): This line prints the number of contours found in the image.cv2.drawContours(image, contours, -1, (0, 255, 0), 3): This line draws the contours on the original color image. The-1parameter indicates that all contours should be drawn, and(0, 255, 0)specifies the color of the contours (in this case, green).cv2.imshow('Contours', image): This line displays the original image with the drawn contours.cv2.waitKey(0): This line waits indefinitely to display the final image with contours before proceeding.cv2.destroyAllWindows(): This line closes all OpenCV windows.
In conclusion,
using Python and OpenCV for edge and contour detection in images allows us to find the boundaries of objects and highlight them. This process is like tracing the outline of objects in a picture, which can be useful for tasks like object recognition and measurement. By applying edge detection, we can identify the edges of objects, and by finding contours, we can extract the shape and structure of those objects. Overall, these techniques help us analyze images and extract useful information from them.





Leave a Reply