Links

Object Counting

Use computer vision to understand how many times certain objects appear in a given set of images.
To install dependencies, pip install roboflow
Setting up the logic for object counts on a single target class:
from roboflow import Roboflow
import os, sys, re, glob
# obtaining your API key: https://docs.roboflow.com/rest-api#obtaining-your-api-key
rf = Roboflow(api_key="INSERT_PRIVATE_API_KEY")
workspace = rf.workspace("INSERT_WORKSPACE_ID")
project = rf.workspace("INSERT_WORKSPACE_ID").project("INSERT_MODEL/PROJECT_ID")
# replace REPLACE_WITH_MODEL_VERSION_NUM with your model version number
version = project.version(REPLACE_WITH_MODEL_VERSION_NUM)
model = version.model
def count_object_occurances(predictions, target_class):
"""
Helper method to count the number of objects in an image for a given class
:param predictions: predictions returned from calling the predict method
:param target_class: str, target class for object count
:return: dictionary with target class and total count of occurrences in image
"""
object_counts = {target_class : 0}
for prediction in predictions:
if prediction['class'] in target_class:
object_counts[prediction['class']] += 1
return object_counts
Example: Setting up object counting logic, with target class of 'face' (API Key removed for security)
Run model inference and object counting on a single image file:
# perform inference on the selected image
predictions = model.predict("YOUR_IMAGE.jpg") # or
## uncomment the following line to run inference on a hosted image
# prediction_hosted = model.predict("https://www.yourimageurl.com", hosted=True)
## replace target_class with name of target_class
## example, target class is 'face': count_object_occurances(predictions, 'face')
class_counts = count_object_occurances(predictions, target_class)
print(predictions, class_counts)
print('\n')
Example: Object counting on a single image file
Run model inference and object counting on a folder (directory) of image files:
raw_data_location = "INSERT_PATH_TO_IMG_DIRECTORY"
raw_data_extension = ".jpg" # e.g jpg, jpeg, png
globbed_files = glob.glob(raw_data_location + '/*' + raw_data_extension)
## replace target_class with name of target_class
## example, target class is 'face': count_object_occurances(predictions, 'face')
for img_file in globbed_files:
predictions = model.predict(img_file)
class_counts = count_object_occurances(predictions, target_class)
print(predictions, class_counts)
print('\n')
Example: Object counting on an entire folder (directory) of images