Python code yolo OD

Python code yolo OD


import cv2
import numpy as np
import threading
import serial
import time

net = cv2.dnn.readNet("yolov3_training_3000.weights", "yolov3_testing.cfg")
# net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
# net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

classes = ["1", "2"]

layer_names = net.getLayerNames()
outputlayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

colors = np.random.uniform(0, 255, size=(len(classes), 3))
# try:
#     arduino_data = serial.Serial('/dev/ttyACM0', 115200)
#     print("Entered")
# except:
#     print("Not entered")


class CamThread(threading.Thread):
    def __init__(self, camID):
        threading.Thread.__init__(self)
        self.camID = camID

    def run(self):
        detect(self.camID)



def detect(camID):
    global toDetect
    cap = cv2.VideoCapture(camID)
    font = cv2.FONT_HERSHEY_PLAIN
    toDetect = False
    arduino_data = serial.Serial('/dev/ttyACM0', 115200)
    while True:
        if arduino_data.inWaiting():
            arduino = arduino_data.readline()
            if 'Start detection' in str(arduino):
                toDetect = True

        _, frame = cap.read()

        cv2.imshow("Camera", frame)

        if toDetect:

            height, width, channels = frame.shape

            blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0,), True, crop=False)

            net.setInput(blob)
            outs = net.forward(outputlayers)

            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.3:
                        center_x = int(detection[0] * width)
                        center_y = int(detection[1] * height)
                        w = int(detection[2] * width)
                        h = int(detection[3] * height)

                        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.4, 0.6)
            if len(indexes) != 1: #chislo detaley dlya ne brakovannoy formy
                arduino_data.write('0'.encode())
                print("not detected")
            for i in range(len(boxes)):
                if i in indexes:
                    x, y, w, h = boxes[i]
                    label = str(classes[int(class_ids[i])])
                    confidence = confidences[i]
                    color = colors[class_ids[i]]
                    cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
                    cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y + 30), font, 1, (255, 255, 255),
                                2)

            cv2.imshow("Image" + str(camID), frame)
            toDetect = False
        key = cv2.waitKey(1)

        if key == 27:
            break
    cap.release()
    cv2.destroyAllWindows()


CamThread(0).start()
# CamThread("1234.mp4").start()
import cv2
import numpy as np
import threading
import serial
import time

net = cv2.dnn.readNet("yolov3_training_3000.weights", "yolov3_testing.cfg")
# net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
# net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

classes = ["1", "2"]

layer_names = net.getLayerNames()
outputlayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

colors = np.random.uniform(0, 255, size=(len(classes), 3))
# try:
#     arduino_data = serial.Serial('/dev/ttyACM0', 115200)
#     print("Entered")
# except:
#     print("Not entered")


class CamThread(threading.Thread):
    def __init__(self, camID):
        threading.Thread.__init__(self)
        self.camID = camID

    def run(self):
        detect(self.camID)



def detect(camID):
    global toDetect
    cap = cv2.VideoCapture(camID)
    font = cv2.FONT_HERSHEY_PLAIN
    toDetect = False
    arduino_data = serial.Serial('/dev/ttyACM0', 115200)
    while True:
        if arduino_data.inWaiting():
            arduino = arduino_data.readline()
            if 'Start detection' in str(arduino):
                toDetect = True

        _, frame = cap.read()

        cv2.imshow("Camera", frame)

        if toDetect:

            height, width, channels = frame.shape

            blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0,), True, crop=False)

            net.setInput(blob)
            outs = net.forward(outputlayers)

            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.3:
                        center_x = int(detection[0] * width)
                        center_y = int(detection[1] * height)
                        w = int(detection[2] * width)
                        h = int(detection[3] * height)

                        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.4, 0.6)
            if len(indexes) != 1: #chislo detaley dlya ne brakovannoy formy
                arduino_data.write('0'.encode())
                print("not detected")
            for i in range(len(boxes)):
                if i in indexes:
                    x, y, w, h = boxes[i]
                    label = str(classes[int(class_ids[i])])
                    confidence = confidences[i]
                    color = colors[class_ids[i]]
                    cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
                    cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y + 30), font, 1, (255, 255, 255),
                                2)

            cv2.imshow("Image" + str(camID), frame)
            toDetect = False
        key = cv2.waitKey(1)

        if key == 27:
            break
    cap.release()
    cv2.destroyAllWindows()


CamThread(0).start()
# CamThread("1234.mp4").start()


Report Page