Search⌘ K

Counting Objects

Explore how to detect and count objects in images by applying edge detection and contour analysis with Python and OpenCV. Understand how blurring and background conditions affect object counting accuracy in image processing tasks.

Detecting objects

Now that we can detect the edges of an object, we can perform other useful functions like object detection. Let’s start.

Python 3.8
import cv2
import sys
def count_cards(infile="cards.jpg", nogui=False):
# Read the image
image = cv2.imread(infile)
#convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#blur it
blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
# Run the Canny edge detector
canny = cv2.Canny(blurred_image, 30, 100)
if nogui:
cv2.imwrite('test_count_cards.png', image2)
return len(contours)
else:
# Show both our images'
image = cv2.imread(infile)
cv2.imwrite("output/Original_image.png", image)
cv2.imwrite("output/Blurred_image.png", blurred_image)
cv2.imwrite("output/Canny.png", canny)
if __name__ == "__main__":
count_cards()

This code is the same as before. We’ve detected the edges in the original and blurred image.

Now, we need to find the contours (which is just another fancy word for edges) in the image. This is because the code ...