import cv2
import numpy as np
# Загрузка изображений:
dr_image = cv2.imread('original.png')
# Преобразуем в серое:
gray = cv2.cvtColor(dr_image, cv2.COLOR_BGR2GRAY)
# Бинаризация: черные линии → белые (на чёрном фоне).
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# Шаблоны:
template1 = cv2.imread('temp2.png', cv2.IMREAD_GRAYSCALE) # ёлочка
template2 = cv2.imread('temp1.png', cv2.IMREAD_GRAYSCALE) # круг
_, template1 = cv2.threshold(template1, 127, 255, cv2.THRESH_BINARY_INV)
_, template2 = cv2.threshold(template2, 127, 255, cv2.THRESH_BINARY_INV)
# Параметры:
threshold1 = 0.7 # для ёлочки
threshold2 = 0.5 # для круга
# Поиск "ёлочки":
result1 = cv2.matchTemplate(binary, template1, cv2.TM_CCOEFF_NORMED)
loc1 = np.where(result1 >= threshold1)
# Поиск "круга":
result2 = cv2.matchTemplate(binary, template2, cv2.TM_CCOEFF_NORMED)
loc2 = np.where(result2 >= threshold2)
# Результат:
result = dr_image.copy()
detected_boxes = []
# Обработка "ёлочки":
for pt in zip(*loc1[::-1]):
x, y = pt
w, h = template1.shape[1], template1.shape[0]
box = (x, y, x + w, y + h)
if not any(np.allclose(box, b, atol=10) for b in detected_boxes):
detected_boxes.append(box)
cv2.rectangle(result, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv2.putText(result, "Tree", (pt[0], pt[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
# Обработка "круга":
for pt in zip(*loc2[::-1]):
x, y = pt
w, h = template2.shape[1], template2.shape[0]
box = (x, y, x + w, y + h)
if not any(np.allclose(box, b, atol=10) for b in detected_boxes):
detected_boxes.append(box)
cv2.rectangle(result, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)
cv2.putText(result, "Circle", (pt[0], pt[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
# Сохраняем результат:
cv2.imwrite('result_with_labels.png', result)
print(f"Найдено объектов: {len(detected_boxes)}")
# Показываем:
cv2.imshow('Detected', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
>>> Найдено объектов: 12