การพัฒนาโปรแกรมตรวจจับวัตถุในภาพด้วย Muti-template Matching
import cv2
import numpy as np
def non_maximum_suppression(boxes, overlapThresh=0.5):
if len(boxes) == 0:
return []
boxes = np.array(boxes)
x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
indices = np.argsort(y2) # Sort by bottom-right y-coordinate
pick = []
while len(indices) > 0:
last = len(indices) - 1
i = indices[last]
pick.append(i)
xx1 = np.maximum(x1[i], x1[indices[:last]])
yy1 = np.maximum(y1[i], y1[indices[:last]])
xx2 = np.minimum(x2[i], x2[indices[:last]])
yy2 = np.minimum(y2[i], y2[indices[:last]])
w = np.maximum(0, xx2 - xx1 + 1)
h = np.maximum(0, yy2 - yy1 + 1)
overlap = (w * h) / areas[indices[:last]]
indices = indices[np.where(overlap <= overlapThresh)[0]]
return boxes[pick]
def multi_template_matching(image_path, template_paths, threshold=0.4):
# Load the main image
image = cv2.imread(image_path, cv2.IMREAD_COLOR)
if image is None:
print("Error: Could not load image.")
return
class_counts = {}
for template_path in template_paths:
# Load template
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is None:
print(f"Error: Could not load template {template_path}.")
continue
# Get template dimensions
w, h = template.shape[1], template.shape[0]
# Perform template matching
result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
# Find locations where matching score is above the threshold
locations = np.where(result >= threshold)
boxes = [(pt[0], pt[1], pt[0] + w, pt[1] + h) for pt in zip(*locations[::-1])]
# Apply Non-Maximum Suppression (NMS) to remove duplicates
filtered_boxes = non_maximum_suppression(boxes)
count = len(filtered_boxes) # Corrected count
class_counts[template_path] = count
# Draw rectangles around detected objects
for (x1, y1, x2, y2) in filtered_boxes:
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Display counts on image
y_offset = 20
for class_name, count in class_counts.items():
text = f"{class_name}: {count}"
cv2.putText(image, text, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
y_offset += 30
# Print counts
print("Object Counts:")
for class_name, count in class_counts.items():
print(f"{class_name}: {count}")
# Show the result
cv2.imshow("Detected Objects", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Example usage
multi_template_matching(r"C:\Users\user\Desktop\p0.jpg", [r"C:\Users\user\Desktop\p2.jpg", r"C:\Users\user\Desktop\p3.jpg"])
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้