Counting Objects
Learn how to detect objects and count them.
We'll cover the following...
Detecting objects
Now that we can detect the edges of an object, we can perform other useful functions like object detection. Let’s start.
Press + to interact
import cv2import sysdef count_cards(infile="cards.jpg", nogui=False):# Read the imageimage = cv2.imread(infile)#convert to grayscalegray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#blur itblurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)# Run the Canny edge detectorcanny = 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 ...