I have several questions with using yolo in python

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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()
</code>
<code>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() </code>
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.

New contributor

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật