def __init__(self, weights, config, confidence=0.5, use_gpu=True):
     self.network = dnn.readNetFromDarknet(config, weights)
     if use_gpu:
         self.network.setPreferableBackend(dnn.DNN_BACKEND_CUDA)
         self.network.setPreferableTarget(dnn.DNN_TARGET_CUDA)
     layer_names = self.network.getLayerNames()
     self.output_layers = [
         layer_names[i[0] - 1]
         for i in self.network.getUnconnectedOutLayers()
     ]
     self.confidence = confidence
Esempio n. 2
0
    def __init__(self, cfgPath, weightsPath, names):
        self._model = readNetFromDarknet(cfgPath, weightsPath)
        self._names = names

        self._colors = {name: randomColor() for name in self._names}

        # extract output layer names
        layerNames = self._model.getLayerNames()
        self._layerNames = [
            layerNames[i[0] - 1]
            for i in self._model.getUnconnectedOutLayers()
        ]
Esempio n. 3
0
    def __init__(self, hasGPU, classesFile, modelConfiguration, modelWeights):
        # Initialize the parameters
        self.confThreshold = 0.5  # Confidence threshold
        self.nmsThreshold = 0.4  # Non-maximum suppression threshold
        self.inpWidth = 416  # Width of network's input image
        self.inpHeight = 416  # Height of network's input image
        self.frame = None

        with open(classesFile, 'rt') as f:
            self.classes = f.read().rstrip('\n').split('\n')
        self.net = dnn.readNetFromDarknet(modelConfiguration, modelWeights)
        self.net.setPreferableBackend(dnn.DNN_BACKEND_OPENCV)
        if hasGPU:
            self.net.setPreferableTarget(dnn.DNN_TARGET_OPENCL)
        else:
            self.net.setPreferableTarget(dnn.DNN_TARGET_CPU)
Esempio n. 4
0
def bolean():
    if request.method == "POST":
        try:
            imgb64 = request.data['image']
            img = fromstring(b64decode(imgb64), uint8)
            img = imdecode(img, IMREAD_COLOR)
            net = readNetFromDarknet('app/yolo_cfg/yolov3-custom.cfg',
                                     'app/yolo_cfg/yolov3.weights')
            blob = blobFromImage(img,
                                 1 / 255.5, (416, 416),
                                 swapRB=True,
                                 crop=False)
            ln = net.getLayerNames()
            ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
            net.setInput(blob)
            layerOutputs = net.forward(ln)
            classIDs = []
            for output in layerOutputs:
                for detection in output:
                    scores = detection[5:]
                    classID = argmax(scores)
                    confidence = scores[classID]
                    if confidence > 0.5:
                        classIDs.append(classID)
            try:
                boolean = "false" if classIDs[0] else "true"
            except:
                boolean = "null"
            return {
                'nomeArquivo': request.data['nomeArquivo'],
                'pred': boolean
            }

        except:
            return {'image': "Imagem invalida!"}

    return {'message': 'Darknet Api Vizentec'}
Esempio n. 5
0
#encoding:utf-8
import cv2
import numpy as np 
from cv2 import dnn

confThreshold = 0.2


net = dnn.readNetFromDarknet("yolov3.cfg","yolov3.weights")
# net = dnn.readNetFromDarknet("yolov3-tiny.cfg","yolov3-tiny.weights")
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
#net.setPreferableTarget(DNN_TARGET_CPU)

def getOutputsNames(net):
    # Get the names of all the layers in the network
    layersNames = net.getLayerNames()
    # Get the names of the output layers, i.e. the layers with unconnected outputs
    return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]


def postprocess(frame, outs):
    frameHeight = frame.shape[0]
    frameWidth = frame.shape[1]
 
    classIds = []
    confidences = []
    boxes = []
    # Scan through all the bounding boxes output from the network and keep only the
    # ones with high confidence scores. Assign the box's class label as the class with the highest score.
    classIds = []
    confidences = []
Esempio n. 6
0
def index():
    if request.method == "POST":
        try:
            imgb64 = request.data['image']
            img = fromstring(b64decode(imgb64), uint8)
            img = imdecode(img, IMREAD_COLOR)
            (H, W) = img.shape[:2]

            net = readNetFromDarknet('app/yolo_cfg/yolov3-custom.cfg',
                                     'app/yolo_cfg/yolov3.weights')
            ln = net.getLayerNames()
            ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]

            blob = blobFromImage(img,
                                 1 / 255.5, (416, 416),
                                 swapRB=True,
                                 crop=False)
            net.setInput(blob)
            layerOutputs = net.forward(ln)

            boxes = []
            confidences = []
            classIDs = []

            for output in layerOutputs:
                for detection in output:
                    scores = detection[5:]
                    classID = argmax(scores)
                    confidence = scores[classID]

                    if confidence > 0.5:
                        box = detection[0:4] * array([W, H, W, H])
                        (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))
                        classIDs.append(classID)

            idxs = NMSBoxes(boxes, confidences, 0.5, 0.4)
            labels = open('app/yolo_cfg/display.names').read().strip().split(
                '\n')
            colors = [[0, 255, 0], [0, 0, 255]]

            if len(idxs) > 0:
                for i in idxs.flatten():
                    (x, y) = (boxes[i][0], boxes[i][1])
                    (w, h) = (boxes[i][2], boxes[i][3])

                    color = [int(c) for c in colors[classIDs[i]]]
                    rectangle(img, (x - 2, y - 2), (x + w + 2, y + h + 2),
                              color, 1)
                    text = '{}'.format(labels[classIDs[i]])
                    acc = '{:.2f}%'.format(confidences[i] * 100)
                    rectangle(img, (x - 2, y + 62), (x + 47, y + 47), color,
                              -1)
                    putText(img, text, (x - 2, y + 60), FONT_HERSHEY_SIMPLEX,
                            0.5, (0, 0, 0), 1)
                    putText(img, acc, (x - 2, y + 77), FONT_HERSHEY_SIMPLEX,
                            0.5, color, 1)

            _, pred = imencode('.jpg', img)
            pred = pred.tobytes()
            pred = b64encode(pred)

            try:
                boolean = "false" if classIDs[0] else "true"
            except:
                boolean = "null"
            return {
                'nomeArquivo': request.data['nomeArquivo'],
                'image': pred.decode('utf-8'),
                'pred': boolean
            }

        except:
            return {'image': "Imagem invalida!"}

    return {'message': 'Darknet Api Vizentec'}
Esempio n. 7
0
 def loadModel(self):
     self.network = dnn.readNetFromDarknet(self.config, self.weights)