import cv2
import numpy as np
import yt_dlp
# YOLO
weights_path = 'yolov3.weights'
config_path = 'yolov3.cfg'
coco_names_path = 'coco.names'
# COCO
with open(coco_names_path, 'r') as f:
class_names = f.read().strip().split('n')
# YOLO
net = cv2.dnn.readNetFromDarknet(config_path, weights_path)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
# YouTube API
API_KEY = ''
VIDEO_ID = 'DnUFAShZKus'
url = f"https://www.youtube.com/watch?v={VIDEO_ID}"
ydl_opts = {
'format': 'best',
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(url, download=False)
video_url = info_dict.get('url', None)
if not video_url:
print("Canlı yayının video URL'si alınamadı.")
else:
# OpenCV
cap = cv2.VideoCapture(video_url)
frame_count = 0
while True:
ret, frame = cap.read()
frame_count += 1
if not ret:
break
if frame_count % 40 == 0:
# YOLO ile nesne tespiti
blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
# YOLO modelindeki çıkış katmanlarının isimlerini al
layer_names = net.getLayerNames()
# YOLO modelindeki çıkış katmanlarının indislerini al
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
detections = net.forward(output_layers)
boxes = []
confidences = []
class_ids = []
for detection in detections:
for obj in detection:
scores = obj[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5 and class_names[class_id] == 'car':
box = obj[0:4] * np.array([frame.shape[1], frame.shape[0], frame.shape[1], frame.shape[0]])
(centerX, centerY, width, height) = box.astype('int')
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
class_ids.append(class_id)
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in indices:
i = i[0]
box = boxes[i]
(x, y, w, h) = box
color = (0, 255, 0)
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
text = f"{class_names[class_ids[i]]}: {confidences[i]:.2f}"
cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
cv2.imshow('Live Stream', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
In this code I tried to use YOLO for the first time. Also I used a lot of chatGPT in here so there are parts that I don’t understand. It should of make a square around the cars in the live video , but after that I press to start button for a 6 or 7 seconds there are only video with a VERY LOW performance and no squares . . After 7 seconds video close itself and the program gives the
Traceback (most recent call last): File “C:UserscasperOneDriveMasaüstüKunorDenemeCar_AICar_AI_Video.py”, line 78, in i = i[0] IndexError: invalid index to scalar variable.
error.
Orkun Arslantürk is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.