У меня есть скрипт на рассбери. import io import logging import socketserver from http…
- User
У меня есть скрипт на рассбери. import io import logging import socketserver from http import server from threading import Condition import json import cv2 import numpy as np import os from picamera2 import Picamera2 from picamera2.encoders import JpegEncoder from picamera2.outputs import FileOutput
Загружаем эталонные изображения
CARDS_DIR = 'carts' reference_images = [] for filename in os.listdir(CARDS_DIR): if filename.endswith(('.jpg', '.jpeg', '.png')): img_path = os.path.join(CARDS_DIR, filename) img = cv2.imread(img_path) if img is not None: reference_images.append({ 'name': filename, 'image': img })
Функция для поиска объекта на изображении
def find_object(frame): frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
for ref in reference_images: ref_gray = cv2.cvtColor(ref['image'], cv2.COLOR_BGR2GRAY) # Используем SIFT для поиска ключевых точек и дескрипторов sift = cv2.SIFT_create() kp1, des1 = sift.detectAndCompute(ref_gray, None) kp2, des2 = sift.detectAndCompute(frame_gray, None) if des1 is not None and des2 is not None: # Создаем матчер FLANN FLANN_INDEX_KDTREE = 1 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) # Находим соответствия matches = flann.knnMatch(des1, des2, k=2) # Применяем фильтр Лоу good_matches = [] for m, n in matches: if m.distance < 0.75 * n.distance: good_matches.append(m) # Если достаточно хороших совпадений if len(good_matches) > 10: match_percent = len(good_matches) / len(matches) * 100 if match_percent > 75: # Получаем координаты точек src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2) # Находим матрицу гомографии M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) if M is not None: # Получаем углы объекта h, w = ref_gray.shape pts = np.float32([[0, 0], [0, h-1], [w-1, h-1], [w-1, 0]]).reshape(-1, 1, 2) dst = cv2.perspectiveTransform(pts, M) # Рисуем зеленый прямоугольник frame = cv2.polylines(frame, [np.int32(dst)], True, (0, 255, 0), 3, cv2.LINE_AA) return frameclass StreamingOutput(io.BufferedIOBase): def init(self): self.frame = None self.condition = Condition()
def write(self, buf): # Преобразуем буфер в numpy массив data = np.frombuffer(buf, dtype=np.uint8) img = cv2.imdecode(data, cv2.IMREAD_COLOR) if img is not None: # Применяем распознавание объектов processed_img = find_object(img) # Кодируем обратно в JPEG _, buf = cv2.imencode('.jpg', processed_img) with self.condition: self.frame = buf.tobytes() self.condition.notify_all() - Assistant