示例#1
0
def batch_detection_example():
    args = parser()
    check_arguments_errors(args)
    batch_size = 3
    random.seed(3)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file,
        args.data_file,
        args.weights,
        batch_size=batch_size
    )
    image_names = ['data/horses.jpg', 'data/horses.jpg', 'data/eagle.jpg']
    images = [cv2.imread(image) for image in image_names]
    images, detections,  = batch_detection(network, images, class_names,
                                           class_colors, batch_size=batch_size)
    for name, image in zip(image_names, images):
        cv2.imwrite(name.replace("data/", ""), image)
    print(detections)
示例#2
0
    def __init__(self):
        self.image_sub = rospy.Subscriber("/color1/image_raw", Image,
                                          self.callback)
        self.pub = rospy.Publisher('/tmp', Int32, queue_size=10)
        self.bridge = CvBridge()

        r = rospkg.RosPack()
        path = r.get_path('yolo') + '/config/libdarknet.so'
        self.config_path = r.get_path('yolo') + '/config/yolo-obj.cfg'
        self.weight_path = r.get_path('yolo') + '/config/yolo.weights'
        self.data_path = r.get_path('yolo') + '/config/obj.data'

        self.network, self.class_names, self.class_colors = darknet.load_network(
            self.config_path, self.data_path, self.weight_path, batch_size=1)
        self.thresh = 0.50

        self.width = darknet.network_width(self.network)
        self.height = darknet.network_height(self.network)
        print('complete to load')
示例#3
0
def main():
    pub = rospy.Publisher("/yolo_traffic")  #WS_ADDED
    args = parser()
    check_arguments_errors(args)
    random.seed(3)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file,
        args.data_file,
        args.weights,
        batch_size=args.batch_size)

    images = load_images(args.input)

    index = 0
    while True:
        # loop asking for new image paths if no list is given
        if args.input:
            if index >= len(images):
                break
            image_name = images[index]
        else:
            image_name = input("Enter Image Path: ")
        prev_time = time.time()
        image, detections = image_detection(image_name, network, class_names,
                                            class_colors, args.thresh)
        # Call Yolo publishing ftn

        rt = publish_yolo(detections)  #WS_ADDED
        if rt != 0:
            pub.publish(rt)  #WS_ADDED
        else:
            ROS_INFO("TRAFFIC LIGHT UNDETECTED")
        if args.save_labels:
            save_annotations(image_name, image, detections, class_names)
        darknet.print_detections(detections, args.ext_output)
        fps = int(1 / (time.time() - prev_time))
        print("FPS: {}".format(fps))
        if not args.dont_show:
            cv2.imshow('Inference', image)
            if cv2.waitKey() & 0xFF == ord('q'):
                break
        index += 1
示例#4
0
def main():
    args = parser()
    check_arguments_errors(args)

    random.seed(3)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file,
        args.data_file,
        args.weights,
        batch_size=args.batch_size
    )

    images = load_images(args.input)

    index = 0
    while True:
        # loop asking for new image paths if no list is given
        if args.input:
            if index >= len(images):
                break
            image_name = images[index]
        else:
            image_name = input("Enter Image Path: ")
        prev_time = time.time()
        image, detections = image_detection(
            image_name, network, class_names, class_colors, args.thresh
            )
        if args.save_labels:
            save_annotations(image_name, image, detections, class_names)
        darknet.print_detections(detections, args.ext_output)
        fps = int(1/(time.time() - prev_time))
        print("FPS: {}".format(fps))
         #################
        #print(darknet.draw_boxes(detections, image_resized, class_colors))
        print('Found {} boxes for {}'.format(len(out_boxes), image_name))
        
        if not args.dont_show:
            cv2.imshow('Inference', image)
            if cv2.waitKey() & 0xFF == ord('q'):
                break
        index += 1
示例#5
0
def main():
    args = parser()
    check_arguments_errors(args)

    random.seed(3)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file,
        args.data_file,
        args.weights,
        batch_size=args.batch_size
    )
    print('Load Net Successfully!')
    images = load_images(args.input)
    vs= VideoStream(usePiCamera=True).start() #
    time.sleep(2.0) #

    index = 0
    while True:
        # loop asking for new image paths if no list is given
        frame = vs.read() #
        frame = imutils.resize(frame, width=400) #

        prev_time = time.time()
        image, detections = image_detection(
            frame, network, class_names, class_colors, args.thresh
        )
#        if args.save_labels:
        save_annotations("image_name.txt", image, detections, class_names)
#        darknet.print_detections(detections, args.ext_output)
        for label, confidence, bbox in detections:
            print(label + ": " + confidence + "%")
        fps = int(1/(time.time() - prev_time))
        print("FPS: {}".format(fps))
        if not args.dont_show:
            image = cv2.resize(image, (400, 400))
            cv2.imshow('Inference', image)
            key = cv2.waitKey(10) & 0xFF
            if key == ord('q'):
                vs.stop()
                break
        index += 1
示例#6
0
def main():
    args = parser()
    check_arguments_errors(args)

    random.seed(3)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file,
        args.data_file,
        args.weights,
        batch_size=args.batch_size)

    images = load_images(args.input)

    index = 0
    while True:
        # loop asking for new image paths if no list is given
        if args.input:
            if index >= len(images):
                break
            image_name = images[index]
            name = os.path.basename(image_name)
        else:
            image_name = input("Enter Image Path: ")
            name = image_name.split('/')[-1]
        prev_time = time.time()
        image, detections = image_detection(image_name, network, class_names,
                                            class_colors, args.thresh)
        if args.save_labels:
            save_annotations(image_name, image, detections, class_names)
        darknet.print_detections(detections, args.ext_output)
        path = './prediction/'
        if not os.path.exists(path):
            os.makedirs(path)
        cv2.imwrite(f'{path}/predicted_{name}', image)
        fps = int(1 / (time.time() - prev_time))
        print("FPS: {}".format(fps))
        #if not args.dont_show:
        #    cv2.imshow('Inference', image)
        #    if cv2.waitKey() & 0xFF == ord('q'):
        #        break
        index += 1
示例#7
0
def InitialiseYOLO():

    print('YOLO Init')
    global network, class_names, darknet_image

    #configPath = "./cfg/yolov4.cfg"      /home/yokoyamalab/tmp/darknet/cfg/person.cfg
    configPath = "/home/hayashida/yolov4/darknet/cfg/yolov4.cfg"
    #weightPath = "./yolov4.weights"     /home/yokoyamalab/tmp/darknet/backup/person/mix2/person_best.weights
    weightPath = "/home/hayashida/yolov4/darknet/yolov4.weights"
    #metaPath = "./cfg/coco.data"        /home/yokoyamalab/tmp/darknet/cfg/person.data
    dataPath = "/home/hayashida/yolov4/darknet/cfg/coco.data"
    network, class_names, class_colors = darknet.load_network(configPath,
                                                              dataPath,
                                                              weightPath,
                                                              batch_size=1)
    # Darknet doesn't accept numpy images.
    # Create one with image we reuse for each detect
    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)
    return network, class_names, class_colors
示例#8
0
def main(
        cfg = "./cfg/yolov4-tiny.cfg",
        data = "./cfg/coco.data",
        weights = "./bin/yolov4-tiny.weights"
        ):
    global network, class_names, class_colors, width, height, darknet_image

    network, class_names, class_colors = darknet.load_network(
        cfg,
        data,
        weights,
        batch_size=1
    )
    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)
    width = int(width)
    height = int(height)
    print(width, height)
    ip = "192.168.55.1"
    app.run(host=ip, port=5000, debug=False)
示例#9
0
    def __init__(self, detect_config):
        print("=== {}".format(YOLOv4ObjectDetector))
        parser = DetectConfigParser(detect_config)
        self.WEIGHTS = parser.weights()
        self.CONFIG = parser.config()
        self.DATA = parser.data()
        self.OUTPUTS = parser.outputs()

        self.THRESHOLD = parser.threshold()

        self.SAVE_LABELS = True

        self.output_dir = os.path.join(os.getcwd(), self.OUTPUTS)
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

        #random.seed(3)  # deterministic bbox color
        self.BATCH_SIZE = 1
        self.network, self.class_names, self.class_colors = darknet.load_network(
            self.CONFIG, self.DATA, self.WEIGHTS, batch_size=self.BATCH_SIZE)
        print("=== class_names {}".format(self.class_names))
示例#10
0
def main():
    args = parser()
    check_arguments_errors(args)

    random.seed(3)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file,
        args.data_file,
        args.weights,
        batch_size=args.batch_size)

    images = load_images(args.input)

    index = 0
    while True:
        # loop asking for new image paths if no list is given
        if args.input:
            if index >= len(images):
                break
            image_name = images[index]
        else:
            image_name = input("Enter Image Path: ")
        prev_time = time.time()
        image, detections = image_detection(image_name, network, class_names,
                                            class_colors, args.thresh)
        if args.save_labels:
            save_annotations(image_name, image, detections, class_names)
        darknet.print_detections(detections, args.ext_output)
        fps = int(1 / (time.time() - prev_time))
        print("FPS: {}".format(fps))
        cv2.imwrite(
            os.path.join(args.output, "out_" + image_name.split("/")[-1]),
            image)
        if not args.dont_show:
            im = Image.open(
                os.path.join(args.output, "out_" + image_name.split("/")[-1]))
            im.show()
            if cv2.waitKey() & 0xFF == ord('q'):
                break
        index += 1
示例#11
0
 def __init__(self):
     self.network, self.class_names, self.class_colors = darknet.load_network(
         config_file="./cfg/yolov3-voc-mask-detect.cfg",
         data_file="./data/voc-mask-detect.data",
         weights="./backup/yolov3-voc-mask-detect_final-extend.weights",
         batch_size=1)
     self.mask_detection = MaskDetection()
     self.drew_images = Queue()
     self.input_video = "sources/mask-detect-test.mp4"
     self.output_video = None
     self.frame_queue = Queue()
     self.frame_queue_face = Queue()
     self.face_image_queue = Queue(maxsize=1)
     self.darknet_image_queue = Queue(maxsize=1)
     self.detections_queue = Queue(maxsize=1)
     self.face_detections_queue = Queue(maxsize=1)
     self.fps_queue = Queue(maxsize=1)
     self.width = darknet.network_width(self.network)
     self.height = darknet.network_height(self.network)
     self.cap = cv2.VideoCapture(0)
     self.darknet_image = darknet.make_image(self.width, self.height, 3)
     self.thresh = 0.5
示例#12
0
def main():
    args = parser()
    check_arguments_errors(args)

    random.seed(3)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file,
        args.data_file,
        args.weights,
        batch_size=args.batch_size
    )

    images = load_images(args.input)

    index = 0< /home/fadi/다운로드/Yolo_mark/x64/Release/data/train.txt >
    while True:
        # loop asking for new image paths if no list i< /home/fadi/다운로드/Yolo_mark/x64/Release/data/train.txt >s given
        if args.input:
            if index >= len(images):
                break
            image_name = images[index]
        else:
            image_name = input("Enter Image Path: ")
        prev_time = time.time()
        image, detections = image_detection(
            image_name, network, class_names, class_colors, args.thresh
            )< /home/fadi/다운로드/Yolo_ /home/fadi/다운로드/Yolo_mark/x64/Release/data/train.txt mark/x64/Release/data/train.txt >
        if args.save_labels:
            save_annotations(image_name, image, detections, class_names)
        darknet.print_detections(detections, args.ext_output)
        fps = int(1/(time.time() - prev_time))
        print("FPS: {}".format(fps))
        if not args.dont_show:
            cv2.imshow('Inference', image)
	    #cv2.imwrite('./'+str(index)+'.jpg', image)
            if cv2.waitKey() & 0xFF == ord('q'):
                break
        index += 1
示例#13
0
def batch_detection_example():
    args = parser()
    check_arguments_errors(args)
    batch_size = 64
    random.seed(64)  # deterministic bbox colors
    network, class_names, class_colors = darknet.load_network(
        args.config_file, args.data_file, args.weights, batch_size=batch_size)
    image_names = [
        '/ws/data/ADD/images/2_23_000020_097.jpg',
        '/ws/data/ADD/images/2_23_000020_097.jpg',
        '/ws/data/ADD/images/2_23_000020_097.jpg',
        '/ws/data/ADD/images/3_35_000008_318.jpg',
        '/ws/data/ADD/images/4_49_000031_838.jpg'
    ]
    images = [cv2.imread(image) for image in image_names]
    images, detections, = batch_detection(network,
                                          images,
                                          class_names,
                                          class_colors,
                                          batch_size=batch_size)
    for name, image in zip(image_names, images):
        cv2.imwrite(name.replace("data/", ""), image)
    print(detections)
def build_detection_engine(config_file: str, data_file: str, weights: str,
                           thresh: float):
    network, class_names, class_colors = darknet.load_network(config_file,
                                                              data_file,
                                                              weights,
                                                              batch_size=1)
    labels_rev = {}
    for i, label in enumerate(class_names):
        labels_rev[label] = i

    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)

    def inference(flow_id: str, frame: object):
        image = frame_data_2_bytes(frame, width, height)
        darknet.copy_image_from_bytes(darknet_image, image)
        detections = darknet.detect_image(network,
                                          class_names,
                                          darknet_image,
                                          thresh=thresh)
        result = PyDetectionBox(frame_id=frame.frame_id, engine_id='darknet')
        for label, confidence, bbox in detections:
            left, top, right, bottom = darknet.bbox2points(bbox)
            result.add_box(category_id=labels_rev.get(label, ''),
                           category_label=label,
                           x1=left,
                           y1=top,
                           x2=right,
                           y2=left,
                           probability=float(confidence))
        darknet.free_image(darknet_image)

        return flow_id, result

    return inference
示例#15
0
        name = ''
        if idx_track in idx_dict:
            name = idx_dict[idx_track]['name']
        cv2.rectangle(image, (left, top), (right, bottom), (255, 0, 0), 1)
        cv2.putText(image, "ID: {} {}".format(idx_track,
                                              name), (left, top - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    return image


if __name__ == '__main__':
    db_dir = './database'
    MAX_FRAME = 15
    THRESHOLD = 1.0
    # load yolo
    network, class_names, colors = darknet.load_network(
        "yolo/fs_192.cfg", "yolo/obj.data", "yolo/yolo.weights")
    vid_path = 0
    #vid_path = "videoplayback.mp4"
    cap = cv2.VideoCapture(vid_path)
    vid_width = int(cap.get(3))
    vid_height = int(cap.get(4))
    vid_fps = cap.get(5)
    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)
    mot_tracker = Sort()
    # load face feature extraction model
    export_dir = "./tf131_model"
    sess = tf.Session(graph=tf.Graph())
    tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING],
                               export_dir)
示例#16
0
                    help='Show verbose finded and processed data')
parser.add_argument('-s',
                    '--save',
                    action='store_true',
                    required=False,
                    help='Save objects to directory')
args = parser.parse_args()

if (args.image is None and args.video is None):
    print('No input given!')
    sys.exit(-1)

configPath = './cfg/yolov4.cfg'
weightPath = './cfg/yolov4.weights'
metaPath = './cfg/coco.data'
net, classes, colors = darknet.load_network(configPath, metaPath, weightPath)

# Single image processing
if (args.image is not None):
    filename = args.image

    # Read image image
    im = cv2.imread(filename)
    imheight, imwidth, channels = im.shape

    # Create an image we reuse for each detect
    darknet_image = darknet.make_image(imwidth, imheight, channels)
    darknet.copy_image_from_bytes(darknet_image, im.tobytes())
    detections = darknet.detect_image(net, classes, darknet_image)
    print(detections)
import argparse
import cv2
import youtube_dl
import darknet
import ultis
import caches

parser = argparse.ArgumentParser()
parser.add_argument("--url", help="Live youtube url")
parser.add_argument("--quality", help="quality of video", default=720)
args = parser.parse_args()

darknet_network, class_names, _ = darknet.load_network(
    "./cfg/vizyal.cfg",
    "./cfg/vizyal.data",
    "./models/vizyal.weights",
    batch_size=1
)
caches.darknet_width = darknet.network_width(darknet_network)
caches.darknet_height = darknet.network_height(darknet_network)

if __name__ == '__main__':
    ydl_opts = {}
    ydl = youtube_dl.YoutubeDL(ydl_opts)
    info_dict = ydl.extract_info(args.url, download=False)
    formats = info_dict.get('formats', None)

    frame_id = 0

    for f in formats:
        if (f.get('height', None) == int(args.quality)):
示例#18
0
import cv2
from flask import Flask, request, Response
import darknet
import os
from PIL import Image
from io import BytesIO
from flask_cors import CORS

app = Flask(__name__)
CORS(app)
app.config["DEBUG"] = True
app.config["IMAGE_UPLOADS"] = "./upload/"

network, class_names, class_colors = darknet.load_network(
    "./custom-yolov4-detector.cfg",
    "./obj.data",
    "./custom-yolov4-detector_final_1.weights",
    batch_size=1)


def image_detection(image_path, network, class_names, class_colors, thresh):
    # Darknet doesn't accept numpy images.
    # Create one with image we reuse for each detect
    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)

    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image_resized = cv2.resize(image_rgb, (width, height),
                               interpolation=cv2.INTER_LINEAR)
            if 'out.mp4' != None:
                video.write(image)
            if cv2.waitKey(fps) == 27:
                break
    cap.release()
    video.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    frame_queue = Queue()
    darknet_image_queue = Queue(maxsize=1)
    detections_queue = Queue(maxsize=1)
    fps_queue = Queue(maxsize=1)

    # args = parser()
    # check_arguments_errors(args)
    network, class_names, class_colors = darknet.load_network(
            'yolov4-tiny-obj.cfg',
            'obj.data',
            'yolov4-tiny-obj_best.weights',
            batch_size=1
        )
    darknet_width = darknet.network_width(network)
    darknet_height = darknet.network_height(network)
    # input_path = str2int(args.input)
    input_path = "1.mp4"
    cap = cv2.VideoCapture(input_path)
    Thread(target=video_capture, args=(frame_queue, darknet_image_queue)).start()
    Thread(target=inference, args=(darknet_image_queue, detections_queue, fps_queue)).start()
    Thread(target=drawing, args=(frame_queue, detections_queue, fps_queue)).start()
示例#20
0
            if args.out_filename is not None:
                video.release()
            cv2.destroyAllWindows()
    return


if __name__ == '__main__':
    frame_queue = Queue()
    darknet_image_queue = Queue(maxsize=1)
    detections_queue = Queue(maxsize=1)
    fps_queue = Queue(maxsize=1)

    args = parser()
    check_arguments_errors(args)
    network, class_names, class_colors = darknet.load_network(args.config_file,
                                                              args.data_file,
                                                              args.weights,
                                                              batch_size=1)
    # Darknet doesn't accept numpy images.
    # Create one with image we reuse for each detect
    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)
    input_path = str2int(args.input)
    cap = cv2.VideoCapture(input_path)
    Thread(target=video_capture,
           args=(frame_queue, darknet_image_queue)).start()
    Thread(target=inference,
           args=(darknet_image_queue, detections_queue, fps_queue)).start()
    Thread(target=drawing,
           args=(frame_queue, detections_queue, fps_queue)).start()
def YOLO():
    """
    Perform Object detection
    """
    global metaMain, netMain, altNames
    configPath = "./cfg/yolov4.cfg"
    weightPath = "./yolov4.weights"
    metaPath = "./cfg/coco.data"
    deep_sort = "./deep_sort_app.py"
    if not os.path.exists(configPath):
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    if netMain is None:
        network, class_names, class_colors = darknet.load_network(configPath,
                                                                  metaPath,
                                                                  weightPath,
                                                                  batch_size=1)
        # netMain = darknet.load_net_custom(configPath.encode(
        #     "ascii"), weightPath.encode("ascii"), 0, 1)  # batch size = 1
    if metaMain is None:
        metaMain = darknet.load_meta(metaPath.encode("ascii"))
    if altNames is None:
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass
    #cap = cv2.VideoCapture(0)
    cap = cv2.VideoCapture("./data/bridge.mp4")
    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))
    new_height, new_width = frame_height // 2, frame_width // 2
    # print("Video Reolution: ",(width, height))

    out = cv2.VideoWriter("./demo/traffic_output.avi",
                          cv2.VideoWriter_fourcc(*"MJPG"), 10.0,
                          (new_width, new_height))

    # print("Starting the YOLO loop...")

    # Create an image we reuse for each detect
    darknet_image = darknet.make_image(new_width, new_height, 3)

    while True:
        prev_time = time.time()
        ret, frame_read = cap.read()
        # Check if frame present :: 'ret' returns True if frame present, otherwise break the loop.
        if not ret:
            break

        frame_rgb = cv2.cvtColor(frame_read, cv2.COLOR_BGR2RGB)
        frame_resized = cv2.resize(frame_rgb, (new_width, new_height),
                                   interpolation=cv2.INTER_LINEAR)

        darknet.copy_image_from_bytes(darknet_image, frame_resized.tobytes())

        # detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=0.25)
        detections = darknet.detect_image(network,
                                          class_names,
                                          darknet_image,
                                          thresh=0.25)
        image = cvDrawBoxes(detections, frame_resized)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        print(1 / (time.time() - prev_time))
        cv2.imshow('Demo', image)
        cv2.waitKey(3)
        out.write(image)

    cap.release()
    out.release()
    print(":::Video Write Completed")
示例#22
0
restore_var = [v for v in tf.global_variables()]
loader = tf.train.Saver(var_list=restore_var)
ckpt = const.SNAPSHOT_DIR
load(loader, sess, ckpt)

# Yolo Initializer
config_file = "/content/test/cfg/yolov4.cfg"
weights = "/content/test/yolov4.weights"
data_file = "/content/test/cfg/coco.data"
batch_size = 1
thresh = 0.25  # remove object with confidence score < 0.25

save_labels = False  # do not export output to .txt file

random.seed(3)  # deterministic bbox colors
network, class_names, class_colors = darknet.load_network(
    config_file, data_file, weights, batch_size=batch_size)

count = 0
# print("Images: ", images)

# Initialize MONAD
# Create Training Feature Space
Train_FS = list()
trainingClasses = ["person"]

import json
with open('result_train_ucsd.json', 'r') as f:
    D = json.load(f)

train_objects = []
for i in range(len(D)):
示例#23
0
def YOLO():

    global altNames
    configPath = "../cfg/yolov4.cfg"  # Path to cfg
    weightPath = "../yolov4.weights"  # Path to weights
    metaPath = "../cfg/coco.data"  # Path to meta data
    if not os.path.exists(
            configPath
    ):  # Checks whether file exists otherwise return ValueError
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    network, class_names, class_colors = darknet.load_network(configPath,
                                                              metaPath,
                                                              weightPath,
                                                              batch_size=1)

    if altNames is None:
        try:
            # Read the metadata file and find the class names file path.
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass
    #cap = cv2.VideoCapture(0)                                      # Uncomment to use Webcam
    cap = cv2.VideoCapture(
        "../data/test50.mp4")  # Local Stored video detection - Set input video
    #cap = cv2.VideoCapture("../data/Video_for_Testing.mp4")                             # Local Stored video detection - Set input video
    frame_width = int(
        cap.get(3))  # Returns the width and height of capture video
    frame_height = int(cap.get(4))
    # Set out for video writer
    out = cv2.VideoWriter(  # Set the Output path for video writer
        "./Demo/output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 10.0,
        (frame_width, frame_height))

    print("Starting the YOLO loop...")

    # Create an image we reuse for each detect
    darknet_image = darknet.make_image(
        frame_width, frame_height,
        3)  # Create image according darknet for compatibility of network
    while True:  # Load the input frame and write output frame.
        prev_time = time.time()
        ret, frame_read = cap.read(
        )  # Capture frame and return true if frame present
        # For Assertion Failed Error in OpenCV
        if not ret:  # Check if frame present otherwise he break the while loop
            break

        frame_rgb = cv2.cvtColor(
            frame_read, cv2.COLOR_BGR2RGB
        )  # Convert frame into RGB from BGR and resize accordingly
        frame_resized = cv2.resize(frame_rgb, (frame_width, frame_height),
                                   interpolation=cv2.INTER_LINEAR)

        darknet.copy_image_from_bytes(
            darknet_image,
            frame_resized.tobytes())  # Copy that frame bytes to darknet_image

        detections = darknet.detect_image(
            network, class_names, darknet_image,
            thresh=0.25)  # Detection occurs at this line and return
        # detections, for customize we can change the threshold.
        image = cvDrawBoxes(
            detections, frame_resized
        )  # Call the function cvDrawBoxes() for colored bounding box per class
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        print(1 / (time.time() - prev_time))
        cv2.imshow('Demo', image)  # Display Image window
        cv2.waitKey(3)
        out.write(image)  # Write that frame into output video
    cap.release()  # For releasing cap and out.
    out.release()
    print(":::Video Write Completed")
示例#24
0
    def __init__(self, cam_num, parent=None):
        self.cam_num = cam_num
        #載入資料庫的資料
        self.reload()

        QtWidgets.QMainWindow.__init__(self)
        #self.setWindowTitle("ggez")
        self.ui = uic.loadUi("webcam.ui", self)
        #self.ui.setFixedSize(self.size())
        self.ui.tabWidget.setTabText(0, "Main")
        self.ui.tabWidget.setTabText(1, "Search")
        self.ui.tabWidget.setTabText(2, "Setting")

        self.ui.Open_Button.clicked.connect(self.open_detect)
        self.ui.pushButton.clicked.connect(self.save_image)
        self.ui.Stop_Button.clicked.connect(self.stop)
        self.ui.lineEdit.returnPressed.connect(self.save_image)

        self.ui.Send_Button.clicked.connect(self.search_event)
        self.ui.lineEdit_2.returnPressed.connect(self.search_event)

        #由資料庫抓取資料
        self.ui.reload_image.clicked.connect(self.reload)

        self.ui.Recognition_checkbox.clicked.connect(
            self.Recognition_check_event)

        self.Recognition_checkbox.setStyleSheet(
            "QPushButton{background:black;border-radius:20;}")

        self.widget.setStyleSheet(
            "QWidget{border-width:2px;}"
            "QWidget{border-color:black;}"
            "QWidget{border-style:outset;}"
            "QWidget{height:100;}"
            "QWidget{border-radius:5px;}"
            "QWidget{background-color:qlineargradient(x1 : 0, y1 : 0, x2 : 0, y2 : 1, stop :  0.0 #f5f9ff,stop :   0.5 #c7dfff,stop :   0.55 #afd2ff,stop :   1.0 #c0dbff);}"
        )

        self.ui.close_button.clicked.connect(self.close_camera)
        self.ui.tabWidget.setTabIcon(0, QtGui.QIcon("home.png"))
        self.ui.tabWidget.setIconSize(QtCore.QSize(30, 30))
        self.ui.tabWidget.setTabIcon(1, QtGui.QIcon("search.png"))
        self.ui.tabWidget.setIconSize(QtCore.QSize(30, 30))
        self.ui.tabWidget.setTabIcon(2, QtGui.QIcon("setting.png"))
        self.ui.tabWidget.setIconSize(QtCore.QSize(30, 30))
        self.setWindowIcon(QtGui.QIcon("window_icon.png"))

        tab_shape = QtWidgets.QTabWidget.Triangular
        self.tabWidget.setTabShape(tab_shape)
        self.check = 0
        self.i = 0
        self.in_or_out = 0

        self.Recognition_check = False
        self.label2 = QLabel(self)

        self.label1 = QLabel(self)

        self.label1.setStyleSheet(
            "QLabel{background:0;}"
            "QLabel{color:rgb(300,300,300,120);font-size:30px;font-weight:bold;font-family:宋体;}"
        )
        # 動態顯示時間在label上
        timer = QTimer(self)
        timer.timeout.connect(self.showtime)
        timer.start()
        self.label1.setAlignment(QtCore.Qt.AlignCenter)
        self.label2.setGeometry(self.label.width() + 20, 150, 45, 45)
        #self.label1.resize(self.width(),50)

        # In[]
        #----------------口罩辨識初始化-----------------
        self.frame_queue = Queue()
        self.darknet_image_queue = Queue(maxsize=1)
        self.detections_queue = Queue(maxsize=1)
        self.fps_queue = Queue(maxsize=1)
        #宣告一個放照片的Queue
        self.YOLO_image_queue = Queue(maxsize=1)
        #宣告一個放人臉的Queue
        self.YOLO_face_queue = Queue(maxsize=1)

        self.face = 0

        self.recorded_people = []
        self.clock = 0

        self.args = parser()

        check_arguments_errors(self.args)
        self.network, self.class_names, self.class_colors = darknet.load_network(
            self.args.config_file,
            self.args.data_file,
            self.args.weights,
            batch_size=1)

        # Darknet doesn't accept numpy images.
        # Create one with image we reuse for each detect
        self.d_width = darknet.network_width(self.network)
        self.d_height = darknet.network_height(self.network)
        self.darknet_image = darknet.make_image(self.d_width, self.d_height, 3)

        self.show()
示例#25
0
    h_scale = float(t_h) / s_h
    res = []
    for label, confidence, bbox in detections:
        x, y, w, h = bbox
        x = x * w_scale
        y = y * h_scale
        w = w * w_scale
        h = h * h_scale
        left, top, right, bottom = darknet.bbox2points((x, y, w, h))
        res.append((left, top, right - left, bottom - top, confidence))
    return res


if __name__ == '__main__':
    network, class_names, colors = darknet.load_network(
        "yolo/yolov4-tiny-3l.cfg", "yolo/obj.data",
        "yolo/yolov4-tiny-3l_best.weights")
    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)
    #
    # frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # frame_resized = cv2.resize(frame_rgb, (width, height),
    #                            interpolation=cv2.INTER_LINEAR)
    # darknet.copy_image_from_bytes(darknet_image, frame_resized.tobytes())
    # detections = darknet.detect_image(network, class_names, darknet_image, thresh=0.3)
    # frame = draw_boxes(detections, frame, (width, height))
    val_dir = '/home/khang/Khang/data/wider/val/WIDER_val/images'
    dirs = []
    for dir_name in os.listdir(val_dir):
        if os.path.isdir(os.path.join(val_dir, dir_name)):
def YOLO():

    # global metaMain, netMain, altNames
    configPath = "./cfg/knockknock_cfg.cfg"  # Path to cfg
    weightPath = "./knockknock_cfg_best.weights"  # Path to weights
    metaPath = "./data/obj.data"  # Path to meta data
    if not os.path.exists(
            configPath
    ):  # Checks whether file exists otherwise return ValueError
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    network, class_names, class_colors = darknet.load_network(configPath,
                                                              metaPath,
                                                              weightPath,
                                                              batch_size=1)

    #cap = cv2.VideoCapture(0)                                      # Uncomment to use Webcam
    cap = cv2.VideoCapture(
        "ups02.avi")  # Local Stored video detection - Set input video
    frame_width = int(
        cap.get(3))  # Returns the width and height of capture video
    frame_height = int(cap.get(4))
    # Set out for video writer
    out = cv2.VideoWriter(  # Set the Output path for video writer
        "./output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 10.0,
        (frame_width, frame_height))

    print("Starting the YOLO loop...")

    # Create an image we reuse for each detect
    darknet_image = darknet.make_image(
        frame_width, frame_height,
        3)  # Create image according darknet for compatibility of network
    x = float(0)
    while True:  # Load the input frame and write output frame.
        prev_time = time.time()
        # print("line 107 pass")
        ret, frame_read = cap.read(
        )  # Capture frame and return true if frame present
        # print("line 109 pass")
        # For Assertion Failed Error in OpenCV
        if not ret:  # Check if frame present otherwise he break the while loop
            break

        frame_rgb = cv2.cvtColor(
            frame_read, cv2.COLOR_BGR2RGB
        )  # Convert frame into RGB from BGR and resize accordingly
        #print("line 116 pass")
        frame_resized = cv2.resize(frame_rgb, (frame_width, frame_height),
                                   interpolation=cv2.INTER_LINEAR)
        #print("line 117 pass")
        darknet.copy_image_from_bytes(
            darknet_image,
            frame_resized.tobytes())  # Copy that frame bytes to darknet_image
        #print("line 121 pass")
        # detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=0.5)    # Detection occurs at this line and return detections, for customize we can change the threshold.
        detections = darknet.detect_image(network,
                                          class_names,
                                          darknet_image,
                                          thresh=0.8)
        #print("line 124 pass")
        image = cvDrawBoxes(
            detections, frame_resized
        )  # Call the function cvDrawBoxes() for colored bounding box per class
        #print("line 126 pass")
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        # if detections:
        #   print(detections[0][1])

        if detections:
            if float(detections[0][1]) > x:
                snap = image
                detection = detections
                x = float(detections[0][1])
                # x=x+1
        # print(detections)
        #print("line 128 pass")
        # print(1/(time.time()-prev_time))
        #print("line 130 pass")
        #cv2.imshow('Demo', image)                                    # Display Image window
        #print("line 132 pass")
        cv2.waitKey(3)
        out.write(image)  # Write that frame into output video
    # print("detections[0]: " + str(detections[0][0]))
    cv2.imwrite("snap.jpg", snap)
    cap.release()  # For releasing cap and out.
    out.release()

    print(detection[0][0])
    print(detection[0][1])
    print(":::Video Write Completed")
示例#27
0
from pandas import DataFrame
import darknet
import sys
import itertools
from tqdm import tqdm

sys.path.insert(
    0, '/mekeneocr/myUniverse/darknet'
)  #puth darknet path in first place in sys (this step is very important)

config = "/mekeneocr/tiny/yolov4-tiny-custom.cfg"
data = "/mekeneocr/tiny/letters.data"
weights = "/mekeneocr/tiny/yolov4-tiny-custom_best.weights"

network, class_names, class_colors = darknet.load_network(config,
                                                          data,
                                                          weights,
                                                          batch_size=1)


def image_detection(image_path, network, class_names, class_colors, thresh):
    # Darknet doesn't accept numpy images.
    # Create one with image we reuse for each detect
    width = darknet.network_width(network)
    height = darknet.network_height(network)
    darknet_image = darknet.make_image(width, height, 3)

    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image_resized = cv2.resize(image_rgb, (width, height),
                               interpolation=cv2.INTER_LINEAR)
示例#28
0
    label = sorted(label)
    label = str(label) + get_direction()
    cv.putText(image, str(label), (5, 40), FONT_SIMPLEX, 1, COLOR_B, 2, LINE_AA)
    return image


if __name__ == '__main__':
    # Initialization
    names_path = '../config/forklift.names'
    cfg_path = '../config/forklift.cfg'
    data_path = '../config/forklift.data'
    weighs_path = '../weights/forklift.weights'
    video_path = '../videos/forklift.mp4'
    threshold = 0.5
    # Initialize yolov4 network
    net, names, colors = darknet.load_network(cfg_path, data_path, weighs_path, 1)
    winName = 'Deep learning object detection in YOLO'
    cv.namedWindow(winName, cv.WINDOW_NORMAL)
    cv.resizeWindow(winName, IMAGE_WIDTH, IMAGE_HEIGHT)
    cv.moveWindow(winName, 100, 100)
    while True:
        # Initialization
        Target_Objections = {'forklift': Attributes(), 'cargo': Attributes()}
        cap = cv.VideoCapture(video_path)
        while cv.waitKey(1) < 0:
            state, frame = cap.read()
            if not state:
                break
            # Detect
            detections = image_detection(frame, net, names, threshold)
            # Draw trace
def main():
    # YOLO and darknetconfiguration
    configPath = "./cfg/knockknock_cfg.cfg"  # Path to cfg
    weightPath = "./knockknock_cfg_best.weights"  # Path to weights
    metaPath = "./data/obj.data"  # Path to meta data
    if not os.path.exists(
            configPath
    ):  # Checks whether file exists otherwise return ValueError
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    network, class_names, class_colors = darknet.load_network(configPath,
                                                              metaPath,
                                                              weightPath,
                                                              batch_size=1)

    # rtsp = rtsp://admin:[email protected]:554
    #cap = cv2.VideoCapture(rtsp)                                     To run on camera
    #cap = cv2.VideoCapture(0)                                      # Uncomment to use Webcam
    cap = cv2.VideoCapture(
        videoInput)  # Local Stored video detection - Set input video
    frame_width = int(
        cap.get(3))  # Returns the width and height of capture video
    frame_height = int(cap.get(4))
    # Set out for video writer
    fileName = datetime.now().strftime("%B-%d-%y_%H:%M:%S")
    outputPath = "./results/" + fileName + ".avi"
    out = cv2.VideoWriter(  # Set the Output path for video writer
        outputPath, cv2.VideoWriter_fourcc(*"MJPG"), 10.0,
        (frame_width, frame_height))

    print("Analyze starts..")

    darknet_image = darknet.make_image(
        frame_width, frame_height,
        3)  # Create image according darknet for compatibility of network
    x = float(0)
    while True:  # Load the input frame and write output frame.
        prev_time = time.time()
        # print("line 107 pass")
        ret, frame_read = cap.read(
        )  # Capture frame and return true if frame present
        # print("line 109 pass")
        # For Assertion Failed Error in OpenCV
        if not ret:  # Check if frame present otherwise he break the while loop
            break

        frame_rgb = cv2.cvtColor(
            frame_read, cv2.COLOR_BGR2RGB
        )  # Convert frame into RGB from BGR and resize accordingly
        #print("line 116 pass")
        frame_resized = cv2.resize(frame_rgb, (frame_width, frame_height),
                                   interpolation=cv2.INTER_LINEAR)
        #print("line 117 pass")
        darknet.copy_image_from_bytes(
            darknet_image,
            frame_resized.tobytes())  # Copy that frame bytes to darknet_image
        #print("line 121 pass")
        # detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=0.5)    # Detection occurs at this line and return detections, for customize we can change the threshold.
        detections = darknet.detect_image(network,
                                          class_names,
                                          darknet_image,
                                          thresh=0.8)
        #print("line 124 pass")
        image = drawBoxes(
            detections, frame_resized
        )  # Call the function cvDrawBoxes() for colored bounding box per class
        #print("line 126 pass")
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        if detections:
            if float(detections[0][1]) > x:
                snap = image
                detection = detections
                x = float(detections[0][1])

        # print(1/(time.time()-prev_time))
        #cv2.imshow('Demo', image)                                    # Display Image window
        cv2.waitKey(3)
        out.write(image)  # Write that frame into output video
    # print("detections[0]: " + str(detections[0][0]))
    cap.release()  # For releasing cap and out.
    out.release()
    if x > float(80):
        snapPath = "./results/" + fileName + ".jpg"
        cv2.imwrite(snapPath, snap)
        label = str(detection[0][0])
        confidence = float(detection[0][1])
        logFilePath = logging(label, confidence)
        sendAttachments(snapPath, logFilePath, label, confidence)
    print("Analyze Completed")
import darknet
import time

# Parameters
win_title = 'YOLOv4 CUSTOM DETECTOR'
cfg_file = 'cfg/yolov4-tiny.cfg'
data_file = 'cfg/coco.data'
weight_file = 'yolov4-tiny.weights'
thre = 0.25
show_coordinates = False
show_size = (800, 800)

# Load Network
network, class_names, class_colors = darknet.load_network(
        cfg_file,
        data_file,
        weight_file,
        batch_size=1
    )

# Get Nets Input dimentions
width = darknet.network_width(network)
height = darknet.network_height(network)

# Get Webcam from cv2
cap = cv2.VideoCapture(0)

# Video Stream
while cap.isOpened():
    
    # Get current frame, quit if no frame 
    ret, frame = cap.read()