AI/ML OpenCV YOLO Python

Computer Vision з OpenCV та YOLO

Від основ обробки зображень до real-time object detection

28 лютого 2026 | 35 хв читання

Computer Vision — це здатність комп'ютерів «бачити» та розуміти зображення. Tesla Autopilot, Face ID, медична діагностика — все це CV.

Object Detection
Знаходження об'єктів на фото/відео
Face Recognition
Ідентифікація людей
OCR
Розпізнавання тексту

OpenCV: основи

# pip install opencv-python numpy matplotlib
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Читання зображення
img = cv2.imread('photo.jpg')

# OpenCV читає в BGR, конвертуємо в RGB для matplotlib
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Розміри
height, width, channels = img.shape
print(f"Розмір: {width}x{height}, канали: {channels}")

# Зміна розміру
resized = cv2.resize(img, (640, 480))

# Обрізка
cropped = img[100:400, 200:500]  # [y1:y2, x1:x2]

# Відображення
plt.figure(figsize=(12, 4))
plt.subplot(1, 3, 1); plt.imshow(img_rgb); plt.title('Original')
plt.subplot(1, 3, 2); plt.imshow(cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)); plt.title('Resized')
plt.subplot(1, 3, 3); plt.imshow(cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB)); plt.title('Cropped')
plt.show()

Фільтри та трансформації

# Градації сірого
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Розмиття (для видалення шуму)
blurred = cv2.GaussianBlur(img, (5, 5), 0)

# Виділення країв (Canny edge detection)
edges = cv2.Canny(gray, 50, 150)

# Бінаризація (thresholding)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Адаптивна бінаризація (краще для нерівномірного освітлення)
adaptive = cv2.adaptiveThreshold(
    gray, 255,
    cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
    cv2.THRESH_BINARY, 11, 2
)

# Морфологічні операції
kernel = np.ones((5, 5), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=1)
eroded = cv2.erode(binary, kernel, iterations=1)
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)  # видалення шуму
closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)  # заповнення дірок

Face Detection

Haar Cascades (класичний метод)

# Завантаження pre-trained каскаду для обличь
face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)

# Детекція
def detect_faces_haar(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,     # масштаб зменшення
        minNeighbors=5,      # мін. кількість сусідів
        minSize=(30, 30)     # мін. розмір обличчя
    )

    result = image.copy()
    for (x, y, w, h) in faces:
        cv2.rectangle(result, (x, y), (x+w, y+h), (0, 255, 0), 2)

    return result, faces

MediaPipe (сучасний підхід)

# pip install mediapipe
import mediapipe as mp

mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils

def detect_faces_mediapipe(image):
    with mp_face_detection.FaceDetection(
        model_selection=1,  # 0: короткі дистанції, 1: далекі
        min_detection_confidence=0.5
    ) as face_detection:

        # MediaPipe працює з RGB
        rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        results = face_detection.process(rgb)

        result = image.copy()

        if results.detections:
            for detection in results.detections:
                # Координати bounding box
                bbox = detection.location_data.relative_bounding_box
                h, w, _ = image.shape

                x = int(bbox.xmin * w)
                y = int(bbox.ymin * h)
                width = int(bbox.width * w)
                height = int(bbox.height * h)

                # Confidence
                confidence = detection.score[0]

                cv2.rectangle(result, (x, y), (x+width, y+height), (0, 255, 0), 2)
                cv2.putText(result, f'{confidence:.1%}', (x, y-10),
                           cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        return result

YOLO: Real-time Object Detection

YOLO (You Only Look Once) — найшвидший детектор об'єктів. YOLOv8 — остання версія від Ultralytics.

# pip install ultralytics
from ultralytics import YOLO
import cv2

# Завантаження pre-trained моделі
model = YOLO('yolov8n.pt')  # nano (найшвидша)
# model = YOLO('yolov8s.pt')  # small
# model = YOLO('yolov8m.pt')  # medium
# model = YOLO('yolov8l.pt')  # large
# model = YOLO('yolov8x.pt')  # extra large (найточніша)

# Детекція на зображенні
def detect_objects(image_path):
    results = model(image_path)

    for result in results:
        boxes = result.boxes

        for box in boxes:
            # Координати
            x1, y1, x2, y2 = box.xyxy[0].int().tolist()

            # Клас та confidence
            cls = int(box.cls[0])
            conf = float(box.conf[0])
            label = model.names[cls]

            print(f"{label}: {conf:.2%} at [{x1}, {y1}, {x2}, {y2}]")

    # Візуалізація
    annotated = results[0].plot()
    cv2.imshow('Detection', annotated)
    cv2.waitKey(0)

detect_objects('street.jpg')

Real-time детекція з веб-камери

def realtime_detection():
    model = YOLO('yolov8n.pt')
    cap = cv2.VideoCapture(0)  # 0 = веб-камера

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # Детекція
        results = model(frame, verbose=False)
        annotated = results[0].plot()

        # FPS
        fps = 1000 / results[0].speed['inference']
        cv2.putText(annotated, f'FPS: {fps:.1f}', (10, 30),
                   cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

        cv2.imshow('YOLOv8 Real-time', annotated)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

realtime_detection()

Навчання власної YOLO моделі

# Структура даних для тренування
# dataset/
#   train/
#     images/
#       img001.jpg
#     labels/
#       img001.txt  # class x_center y_center width height (normalized)
#   val/
#     images/
#     labels/

# data.yaml
"""
train: dataset/train/images
val: dataset/val/images

nc: 3  # кількість класів
names: ['cat', 'dog', 'bird']
"""

from ultralytics import YOLO

# Завантажуємо базову модель
model = YOLO('yolov8n.pt')

# Тренування
results = model.train(
    data='data.yaml',
    epochs=100,
    imgsz=640,
    batch=16,
    patience=20,           # early stopping
    device=0,               # GPU 0, або 'cpu'
    project='runs/train',
    name='my_model'
)

# Використання натренованої моделі
trained_model = YOLO('runs/train/my_model/weights/best.pt')
results = trained_model('test_image.jpg')

OCR: розпізнавання тексту

# pip install pytesseract easyocr
import pytesseract
import easyocr
import cv2

# === Tesseract OCR ===
def ocr_tesseract(image_path):
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Preprocessing для кращих результатів
    gray = cv2.threshold(gray, 0, 255,
                        cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

    # Розпізнавання
    text = pytesseract.image_to_string(gray, lang='ukr+eng')
    return text


# === EasyOCR (deep learning, краща якість) ===
def ocr_easyocr(image_path):
    reader = easyocr.Reader(['uk', 'en'], gpu=True)

    results = reader.readtext(image_path)

    img = cv2.imread(image_path)

    for (bbox, text, confidence) in results:
        # bbox: [[x1,y1], [x2,y1], [x2,y2], [x1,y2]]
        (top_left, top_right, bottom_right, bottom_left) = bbox
        top_left = tuple(map(int, top_left))
        bottom_right = tuple(map(int, bottom_right))

        cv2.rectangle(img, top_left, bottom_right, (0, 255, 0), 2)
        cv2.putText(img, text, (top_left[0], top_left[1] - 10),
                   cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        print(f"{text} ({confidence:.2%})")

    cv2.imshow('OCR', img)
    cv2.waitKey(0)

    return results


# Приклад: розпізнавання номерного знаку
def recognize_license_plate(image_path):
    # 1. Детекція номерного знаку (можна YOLO)
    # 2. Вирізання області
    # 3. Preprocessing
    # 4. OCR

    img = cv2.imread(image_path)

    # Спрощено: припускаємо, що номер вже вирізано
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.bilateralFilter(gray, 11, 17, 17)

    reader = easyocr.Reader(['en'])
    results = reader.readtext(gray, allowlist='ABCEHIKMOPTX0123456789')

    if results:
        plate_text = ''.join([r[1] for r in results])
        return plate_text.upper()

    return None

Потрібна допомога з проектом?

Computer Vision з OpenCV, YOLO, MediaPipe -- одна з найперспективніших областей AI. Наші ML-інженери реалізують ваш проект професійно.

Замовити ML проект

Відеоаналітика

# Підрахунок людей, що перетинають лінію
from ultralytics import YOLO
import cv2
import numpy as np

class PeopleCrossingCounter:
    def __init__(self, line_y: int):
        self.model = YOLO('yolov8n.pt')
        self.line_y = line_y
        self.tracked_objects = {}  # id -> last_y
        self.count_in = 0
        self.count_out = 0

    def process_frame(self, frame):
        # Детекція з трекінгом
        results = self.model.track(
            frame,
            persist=True,
            classes=[0],  # тільки люди
            verbose=False
        )

        if results[0].boxes.id is not None:
            boxes = results[0].boxes.xyxy.cpu().numpy()
            ids = results[0].boxes.id.cpu().numpy().astype(int)

            for box, obj_id in zip(boxes, ids):
                x1, y1, x2, y2 = box
                center_y = (y1 + y2) / 2

                # Перевірка перетину лінії
                if obj_id in self.tracked_objects:
                    prev_y = self.tracked_objects[obj_id]

                    # Перетнув лінію знизу вгору
                    if prev_y > self.line_y and center_y <= self.line_y:
                        self.count_in += 1
                    # Перетнув лінію зверху вниз
                    elif prev_y < self.line_y and center_y >= self.line_y:
                        self.count_out += 1

                self.tracked_objects[obj_id] = center_y

        # Візуалізація
        annotated = results[0].plot()

        # Лінія підрахунку
        cv2.line(annotated, (0, self.line_y),
                (frame.shape[1], self.line_y), (0, 0, 255), 2)

        # Лічильники
        cv2.putText(annotated, f'IN: {self.count_in}', (10, 60),
                   cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
        cv2.putText(annotated, f'OUT: {self.count_out}', (10, 100),
                   cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

        return annotated


# Використання
counter = PeopleCrossingCounter(line_y=300)
cap = cv2.VideoCapture('entrance_video.mp4')

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    result = counter.process_frame(frame)
    cv2.imshow('People Counter', result)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

print(f"Total IN: {counter.count_in}, OUT: {counter.count_out}")

Ідеї для курсової роботи

Функціонал: Детекція авто, локалізація номера, OCR, база даних.

Технології: YOLOv8, EasyOCR, OpenCV, SQLite

Складність: Середня

Функціонал: Реєстрація обличь, ідентифікація, логування входів.

Технології: face_recognition, OpenCV, Flask, PostgreSQL

Складність: Середня

Функціонал: Класифікація знімків (норма/патологія), heatmap областей.

Технології: PyTorch, ResNet/EfficientNet, Grad-CAM

Складність: Висока

Потрібна допомога з курсовою?

Computer Vision — одна з найперспективніших областей AI. Ми допоможемо з вибором теми, реалізацією та оформленням роботи.

Замовити курсову з Computer Vision

Потрібна допомога з роботою?

Замовте професійне виконання — без передоплати, оплата після демонстрації!

Курсова з Machine Learning Курсова з Python