The following is one of the techniques to detect objects in images
#! /usr/bin/python
import requests
import cv2
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import normalize
import hdbscan
import matplotlib.pyplot as plt
from io import BytesIO
from azure.core.credentials import AzureKeyCredential
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
import os
match_threshold = 0.5
min_number_of_cluster_members = 2
object_uri = os.getenv("AZURE_RED_CAR_2_SAS_URL").strip('"')
scene_uri = os.getenv("AZURE_QUERY_SAS_URI").strip('"')
# Step 1: Download images from SAS URLs
def download_image(url):
response = requests.get(url)
image_array = np.frombuffer(response.content, np.uint8)
return cv2.imdecode(image_array, cv2.IMREAD_COLOR)
# Step 2: Use OpenCV template matching to find object occurrences
def count_object_occurrences(scene, template, threshold=match_threshold):
scene_gray = cv2.cvtColor(scene, cv2.COLOR_BGR2GRAY)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
result = cv2.matchTemplate(scene_gray, template_gray, cv2.TM_CCOEFF_NORMED)
locations = np.where(result >= threshold)
w, h = template_gray.shape[::-1]
rects = [[pt[0], pt[1], pt[0] + w, pt[1] + h] for pt in zip(*locations[::-1])]
rects, _ = cv2.groupRectangles(rects, groupThreshold=1, eps=0.5)
return len(rects)
# Step 3: Count matches
def count_matches():
scene_img = download_image(scene_uri)
object_img = download_image(object_uri)
count = count_object_occurrences(scene_img, object_img)
return count
# print(f"Detected {count_matches()} occurrences of the object.")
#Output: Detected 1 occurrences of the object.
#Codingexercise: codingexercise-07-06-2025.pdf
https://1drv.ms/b/c/d609fb70e39b65c8/EQti1RQIDMpNrxM0jjPPYzkBI0PX5cBV-eUmQR_Js0nsBQ?e=sssW8n
No comments:
Post a Comment