top of page

Image Processing with OpenCV Part II | OpenCV Assignment Help

In the previous article, we covered the basics of image processing using OpenCV, which included reading, writing, and displaying images, as well as basic image manipulation tasks such as resizing, rotating, and flipping images. We also covered color space conversion and image thresholding.


In this article, we will dive deeper into image processing techniques by discussing contour detection and shape analysis. We will explore how to detect the boundaries of objects in an image and analyze their shape properties such as area, perimeter, and centroid. Additionally, we will cover image filtering techniques such as smoothing and sharpening, which are used to reduce noise and enhance details in an image.


Finally, we will also explore the Canny edge detector, which is a powerful tool for edge detection in an image. The Canny edge detector is widely used in computer vision applications such as object detection, motion detection, and image segmentation.


By mastering these image processing techniques, you will be better equipped to tackle more complex image processing tasks using OpenCV.



Contour Detection and Shape Analysis

Contour detection and shape analysis are fundamental operations in image processing. A contour is simply a curve joining all the continuous points (along the boundary) having the same color or intensity. Contours are a useful tool for shape analysis, object detection, and recognition. In this section, we will explore how to detect contours and perform shape analysis using OpenCV.


Contour Detection

To detect contours in an image using OpenCV, we use the cv2.findContours() function. This function takes three arguments: the input image, the contour retrieval mode, and the contour approximation method. The output of the function is a list of contours and a hierarchy.

import cv2

# read the image
img = cv2.imread('image.jpg')

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# apply thresholding to obtain a binary image
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# find the contours in the binary image
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

The cv2.drawContours() function can be used to draw the contours on an image. The function takes four arguments: the input image, the list of contours, the contour index (if -1, all contours are drawn), and the color and thickness of the contour line.

# draw the contours on the image
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

# display the image
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


Shape Analysis

Once we have detected the contours in an image, we can perform shape analysis using OpenCV. For example, we can compute the area and perimeter of a contour using the cv2.contourArea() and cv2.arcLength() functions, respectively.

# compute the area and perimeter of the first contour
cnt = contours[0]
area = cv2.contourArea(cnt)
perimeter = cv2.arcLength(cnt, True)

# display the area and perimeterprint("Area: {}".format(area))
print("Perimeter: {}".format(perimeter))

In addition, we can also compute the bounding box, minimum enclosing circle, and convex hull of a contour using OpenCV.

# compute the bounding box of the first contour
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)

# compute the minimum enclosing circle of the first contour
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
cv2.circle(img, center, radius, (0, 255, 0), 2)

# compute the convex hull of the first contour
hull = cv2.convexHull(cnt)
cv2.drawContours(img, [hull], 0, (255, 0, 0), 2)


Image Filtering Techniques

Image filtering is a technique used to enhance the quality of an image by removing unwanted noise and artifacts. In this section, we will explore some commonly used image filtering techniques in OpenCV.


Smoothing Filters

Smoothing filters, also known as blurring filters, are used to reduce the amount of noise in an image. The most common smoothing filter is the Gaussian filter, which applies a Gaussian function to the image. The Gaussian filter is implemented in OpenCV using the cv2.GaussianBlur() function.

import cv2

# read the image
img = cv2.imread('image.jpg')

# apply Gaussian blur
blur = cv2.GaussianBlur(img, (5, 5), 0)

# display the original and blurred images
cv2.imshow('Original', img)
cv2.imshow('Blur', blur)
cv2.waitKey(0)
cv2.destroyAllWindows()

Other smoothing filters include the median filter, which replaces each pixel value with the median of its neighboring pixels, and the bilateral filter, which preserves edges while smoothing other regions. These filters can also be applied using the corresponding functions in OpenCV.


Sharpening Filters

Sharpening filters are used to enhance the edges and details in an image. The most common sharpening filter is the Laplacian filter, which calculates the second derivative of the image to emphasize the edges. The Laplacian filter is implemented in OpenCV using the cv2.Laplacian() function.

import cv2

# read the image
img = cv2.imread('image.jpg')

# apply Laplacian filter
laplacian = cv2.Laplacian(img, cv2.CV_64F)

# display the original and sharpened images
cv2.imshow('Original', img)
cv2.imshow('Laplacian', laplacian)
cv2.waitKey(0)
cv2.destroyAllWindows()

Other sharpening filters include the Sobel filter and the Scharr filter, which calculate the first derivative of the image in the x and y directions to emphasize the edges. These filters can also be applied using the corresponding functions in OpenCV.


Edge Detection using Canny Edge Detector

Edge detection is a fundamental operation in image processing that involves identifying the boundaries between objects in an image. The Canny edge detector is a popular edge detection algorithm that was developed by John F. Canny in 1986. The Canny edge detector is a multi-stage algorithm that involves the following steps:

  1. Apply a Gaussian filter to smooth the image and reduce noise.

  2. Calculate the gradient magnitude and direction of the image.

  3. Apply non-maximum suppression to thin the edges.

  4. Apply hysteresis thresholding to remove weak edges.


The Canny edge detector is implemented in OpenCV using the cv2.Canny() function.

import cv2

# read the image
img = cv2.imread('image.jpg')

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# apply Canny edge detection
edges = cv2.Canny(gray, 100, 200)

# display the original and edge-detected images
cv2.imshow('Original', img)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

The cv2.Canny() function takes three arguments: the input image, the lower threshold, and the upper threshold. The lower threshold controls the sensitivity of the detector, while the upper threshold controls the threshold for strong edges. The Canny edge detector is a powerful tool for edge detection and is widely used in applications such as object detection, motion detection, and image segmentation.



bottom of page