AI Features

Counting Objects

Learn how to detect objects and count them.

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 ...