import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
from hashlib import md5
from model import Web_Detector
from chinese_name_list import Label_list
def generate_color_based_on_name(name):
hash_object = md5(name.encode())
hex_color = hash_object.hexdigest()[:6]
r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
return (b, g, r)
def draw_with_chinese(image, text, position, font_size=20, color=(255, 0, 0)):
image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(image_pil)
font = ImageFont.truetype("simsun.ttc", font_size, encoding="unic")
draw.text(position, text, font=font, fill=color)
return cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
def draw_detections(image, info):
name, bbox = info['class_name'], info['bbox']
x1, y1, x2, y2 = bbox
cv2.rectangle(image, (x1, y1), (x2, y2), color=(0, 0, 255), thickness=3)
image = draw_with_chinese(image, name, (x1, y1 - 10), font_size=20)
return image
def process_frame(model, image):
pre_img = model.preprocess(image)
pred = model.predict(pre_img)
det = pred[0]
if det is not None and len(det):
det_info = model.postprocess(pred)
for info in det_info:
image = draw_detections(image, info)
return image
if __name__ == "__main__":
model = Web_Detector()
model.load_model("./weights/yolov8s-seg.pt")
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
processed_frame = process_frame(model, frame)
cv2.imshow('Camera Feed', processed_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
import os
import torch
import yaml
from ultralytics import YOLO
if __name__ == '__main__':
workers = 1
batch = 8
device = "0" if torch.cuda.is_available() else "cpu"
data_path = abs_path(f'datasets/data/data.yaml', path_type='current')
with open(data_path, 'r') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
if 'train' in data and 'val' in data and 'test' in data:
directory_path = os.path.dirname(data_path.replace(os.sep, '/'))
data['train'] = directory_path + '/train'
data['val'] = directory_path + '/val'
data['test'] = directory_path + '/test'
with open(data_path, 'w') as file:
yaml.safe_dump(data, file, sort_keys=False)
model = YOLO(r"C:\codeseg\codenew\50+ 种 YOLOv8 算法改进源码大全和调试加载训练教程(非必要)\改进 YOLOv8 模型配置文件\yolov8-seg-C2f-Faster.yaml").load("./weights/yolov8s-seg.pt")
results = model.train(
data=data_path,
device=device,
workers=workers,
imgsz=640,
epochs=100,
batch=batch
)
import numpy as np
from scipy.spatial.distance import cdist
from ultralytics.utils.metrics import bbox_ioa
def linear_assignment(cost_matrix, thresh, use_lap=True):
if cost_matrix.size == 0:
return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
if use_lap:
try:
import lap
_, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0]
unmatched_a = np.where(x < 0)[0]
unmatched_b = np.where(y < 0)[0]
except ImportError:
pass
else:
from scipy.optimize import linear_sum_assignment
x, y = linear_sum_assignment(cost_matrix)
matches = np.asarray([[x[i], y[i]] for i in range(len(x)) if cost_matrix[x[i], y[i]] <= thresh])
unmatched_a = list(set(np.arange(cost_matrix.shape[0])) - set(matches[:, 0]))
unmatched_b = list(set(np.arange(cost_matrix.shape[1])) - set(matches[:, 1]))
return matches, unmatched_a, unmatched_b
def iou_distance(atracks, btracks):
atlbrs = [track.tlbr for track in atracks] if atracks else []
btlbrs = [track.tlbr for track in btracks] if btracks else []
ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32)
if len(atlbrs) and len(btlbrs):
ious = bbox_ioa(np.ascontiguousarray(atlbrs, dtype=np.float32), np.ascontiguousarray(btlbrs, dtype=np.float32), iou=True)
return 1 - ious