|
|
from ultralytics import YOLO |
|
|
from PIL import Image, ImageDraw, ImageFont |
|
|
|
|
|
import matplotlib.pyplot as plt |
|
|
import matplotlib.image as mpimg |
|
|
import os |
|
|
import shutil |
|
|
import cv2 |
|
|
import subprocess |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def getKeyByValue(dictionary, value): |
|
|
for key, val in dictionary.items(): |
|
|
if val == value: |
|
|
return key |
|
|
return None |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def detectObjectsAndCount(imageFile, confidence_score, class_type): |
|
|
|
|
|
|
|
|
model = YOLO("yolov8n.pt") |
|
|
|
|
|
|
|
|
custom_save_dir = "/app/runs/detect/predict" |
|
|
|
|
|
custom_read_dir = "./" |
|
|
class_index = getKeyByValue(model.names, class_type) |
|
|
count_of_class_type = 0; |
|
|
|
|
|
|
|
|
results = model.predict( |
|
|
source=f"{imageFile}", |
|
|
save=True, |
|
|
conf=confidence_score, |
|
|
save_dir=custom_save_dir, |
|
|
exist_ok=True, |
|
|
classes=[class_index] |
|
|
) |
|
|
|
|
|
|
|
|
for result in results: |
|
|
for box in result.boxes: |
|
|
class_name = model.names[int(box.cls)] |
|
|
if class_name == class_type: |
|
|
count_of_class_type += 1 |
|
|
|
|
|
|
|
|
image_path = f"{custom_save_dir}/{imageFile}" |
|
|
|
|
|
|
|
|
img = Image.open(image_path) |
|
|
|
|
|
|
|
|
draw = ImageDraw.Draw(img) |
|
|
font_path = "/System/Library/Fonts/Supplemental/Arial.ttf" |
|
|
font_size = 30 |
|
|
|
|
|
try: |
|
|
font = ImageFont.truetype(font_path, font_size) |
|
|
except OSError: |
|
|
font = ImageFont.load_default() |
|
|
|
|
|
|
|
|
text = f"Number of {class_type}s are: {count_of_class_type}" |
|
|
|
|
|
|
|
|
text_position = (200, 10) |
|
|
|
|
|
|
|
|
text_color = (0, 0, 139) |
|
|
|
|
|
|
|
|
draw.text(text_position, text, fill=text_color, font=font) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return img, count_of_class_type |
|
|
|
|
|
|
|
|
|
|
|
|