Показываемое изображение с opencv очень медленное
Я новичок в пайтоне, и впринципе в програмировании, сделал проект на основе yolo (начинаю разбираться) , использовал opencv2. Когда скачал нейросеть, попробовал использовать её в обнаружении оружия, у меня запись с вебки лагает, прочитал в интернете насчёт этой проблемы, оказалось что библиотека .read блокирует видеопоток, тем самым создавая эти лаги, как решить проблему? Вот отрывок кода:
from threading import Thread
import cv2
import time
import numpy as np
import pichalka
from weapon_detection.weapon_detection import img, width, height
net = cv2.dnn.readNet("yolov3_training_2000.weights", "yolov3_testing.cfg")
classes = ["Weapon"]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
class VideoStreamWidget(object):
def __init__(self, src=0):
(self.status, self.frame) = self.capture.read()
self.capture = cv2.VideoCapture(src)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
pass
time.sleep(0.1)
def value(self):
val = input("Enter file name or press enter to start webcam : \n")
if val == "":
val = 0
return val
def show_frame(self):
# Display frames in main program
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# Showing information on the screen
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
print(indexes)
if indexes == 0:
pichalka.play()
print("weapon detected in frame")
font = cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y + 30), font, 3, color, 3)
cv2.imshow('Image', img)
key = cv2.waitKey(1)
if key == 27:
self.capture.release()
cv2.destroyAllWindows()
exit(1)
if __name__ == '__main__':
video_stream_widget = VideoStreamWidget()
while True:
try:
video_stream_widget.show_frame()
except AttributeError:
pass