예제 #1
0
def show():

    dn.set_gpu(0)
    net = dn.load_net("/home/spurs/darknet/cfg/yolov3.cfg".encode('ascii'),
                      "/home/spurs/darknet/yolov3.weights".encode('ascii'), 0)
    meta = dn.load_meta("/home/spurs/darknet/cfg/coco.data".encode('ascii'))

    src = '/home/spurs/camera/camera.jpg'
    while True:
        cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
        try:
            frame = cv2.imread(src)
            cv2.imshow('frame', frame)
        except:
            continue

        cv2.imwrite('/home/spurs/camera/camera_1.jpg', frame)
        r = dn.detect(net, meta,
                      "/home/spurs/camera/camera_1.jpg".encode('ascii'))
        for bb in r:
            x, y, w, h = bb[2]
            x_max = int(round((2 * x + w) / 2))
            x_min = int(round((2 * x - w) / 2))
            y_min = int(round((2 * y - h) / 2))
            y_max = int(round((2 * y + h) / 2))
            cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), (255, 255, 0),
                          2)
            cv2.putText(frame, bb[0].decode('utf-8'), (x_min, y_min - 10), 2,
                        1, (255, 0, 255), 2)
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
예제 #2
0
    def __init__(self):

        dn.set_gpu(0)
        self._net = dn.load_net("cfg/yolov3.cfg", "weights/yolov3.weights", 0)
        #self._net = dn.load_net("cfg/yolov3.cfg", "weights/yolov3.weights", 0)
        self._meta = dn.load_meta("cfg/coco.data")
        self.__tmpFile="tmp/tmp.jpg"
    def __init__(self, classes, confidence=0.5, size=416):

        self.classes = classes

        base_path = os.getcwd()
        dn.set_gpu(0)
        if size == 416:

            self.net = dn.load_net(
                os.path.join(base_path, "darknet/cfg/yolov3_416.cfg").encode(),
                os.path.join(base_path, "weights/yolov3_416.weights").encode(),
                0)
            self.detection_dim = (416, 416)

        else:
            self.net = dn.load_net(
                os.path.join(base_path, "darknet/cfg/yolov3.cfg").encode(),
                os.path.join(base_path, "weights/yolov3.weights").encode(), 0)
            self.detection_dim = (608, 608)

        self.meta = dn.load_meta(
            os.path.join(base_path, "darknet/cfg/coco.data").encode())

        self.confidence = confidence

        return
예제 #4
0
def simpson_person_classify(input_path):
    dn.set_gpu(0)
    net = dn.load_net(
        b"/home/sannysjtu/google/google-ml-camp/backend/darknet_yolo/simpsons_test.cfg",
        b"/home/sannysjtu/google/google-ml-camp/backend/darknet_yolo/simpsons_final.weights",
        0)
    meta = dn.load_meta(
        b"/home/sannysjtu/google/google-ml-camp/backend/darknet_yolo/simpsons.data"
    )
    files = os.listdir(input_path)

    # res in the r is the detection result of the model
    # the classname is the only required result of our application

    person_class_list = []

    for imgfile in files:
        imgfilepath = os.path.join(input_path, imgfile)
        r = dn.detect(net, meta, imgfilepath.encode('utf-8'))
        current_class_list, current_scores = [], []
        for res in r:
            classname, score, bbox = res
            classname = classname.decode()
            current_class_list.append(classname)
            current_scores.append(current_scores)
        best_classname = current_class_list[current_scores.index(
            max(current_scores))]

        person_class_list.append(best_classname)
    return person_class_list
예제 #5
0
 def __init__(self,
              cfgPath=cfgDefault,
              weightPath=weightDefault,
              dataPath=dataDefault):
     dn.set_gpu(0)
     self.net = dn.load_net(cfgPath, weightPath, 0)
     self.meta = dn.load_meta(dataPath)
예제 #6
0
def init():
    ''' Initializing function
        Input:
                None
        return:
                None
    '''
    yolo_logger.info('Initializing')
    # get darkent parameters
    global dn, net, meta
    dn_path, mdl_cfg, weights, meta = common.get_yolo_config()
    # check darknet path
    common.path_check(dn_path, yolo_logger, 'darknet path NOT set!', 8)
    common.file_check(mdl_cfg, yolo_logger, 'yolo cfg file set wrong!', 9)
    common.file_check(weights, yolo_logger, 'yolo weight file set wrong!', 9)
    common.file_check(meta, yolo_logger, 'yolo meta file set wrong!', 9)
    yolo_logger.info('Yolo parameters get successfully')
    # import darknet
    sys.path.append(dn_path)
    print(dn_path)
    import darknet as dn
    yolo_logger.info('Darknet import successfully')

    # initialize darknet network
    meta = dn.load_meta(meta.encode('utf-8'))
    yolo_logger.info('Darknet meta load successfully')
    net = dn.load_net(mdl_cfg.encode('utf-8'), weights.encode('utf-8'), 0)
    yolo_logger.info('Darknet network load successfully')
    dn.set_gpu(gpu_idx)
    yolo_logger.info('GPU set to {0}'.format(gpu_idx))
예제 #7
0
def main():
    # Declare network
    darknet.set_gpu(0)
    net = darknet.load_net(b"cfg/yolov3.cfg", b"weights/yolov3.weights", 0)
    meta = darknet.load_meta(b"cfg/coco.data")

    test_detect_data_structure(net, meta)
예제 #8
0
def init_net(weights):
    dn.set_gpu(args.gpu)
    net = dn.load_net(args.model.encode(), weights, 0)

    dn.set_batch_network(net, 1)
    dn.resize_network(net, args.imsize, args.imsize)
    sys.stderr.write('Resized to %d x %d\n' %
                     (dn.network_width(net), dn.network_height(net)))
    return net
 def __init__(self, source):
     self.DetectedImage = None
     dn.set_gpu(0)
     self.net = dn.load_net(
         bytes(path + "cfg/yolov3-tiny.cfg", encoding='utf-8'),
         bytes(path + "/yolov3-tiny.weights", encoding='utf-8'), 0)
     self.meta = dn.load_meta(
         bytes(path + "cfg/coco.data", encoding='utf-8'))
     self.cap = cv2.VideoCapture(source)
예제 #10
0
def _main_(args):

    ###############################
    #   Prepare data to be detected
    ###############################

    # data_folder = "/home/peng/data/good_rolo_data/"
    data_folder = "/home/peng/data/sort_data/images/"
    # data_folder = "/home/peng/data/sort_data/images/"
    video_folders_list = sorted(glob.glob(data_folder + '*'))
    sort_nicely(video_folders_list)

    ###############################
    #   Make the model and Load trained weights
    ###############################

    dn.set_gpu(0)
    # Original YOLOv3 weights
    net = dn.load_net("cfg/yolov3.cfg", "yolov3.weights", 0)
    meta = dn.load_meta("cfg/coco.data")
    # Aerial YOLOv3 weights
    # net = dn.load_net("cfg/yolov3.cfg", "yolov3-aerial.weights", 0)
    # meta = dn.load_meta("cfg/voc.data")
    ###############################
    #   Predict bounding boxes
    ###############################

    for video_folder in video_folders_list:
        video_name = basename(video_folder)

        #if video_name != "person14_3":
        #    continue

        print("Processing %s." % video_name)
        image_paths = sorted(glob.glob(os.path.join(video_folder, '*jpg')))
        sort_nicely(image_paths)
        """ Remember to modify the following path """
        with open('det_mot(before_ft)/' + video_name + '.txt',
                  'w') as out_file:
            for i in tqdm(range(len(image_paths))):
                # image = cv2.imread(image_paths[i])
                results = dn.detect(net,
                                    meta,
                                    image_paths[i],
                                    thresh=0.45,
                                    nms=0.5)

                for r in results:
                    if r[0] == 'person' and r[1] > 0.88:
                        box = BoundBox(r[2][0], r[2][1], r[2][2], r[2][3],
                                       r[1], r[0])
                        x1 = (box.x - box.w / 2)
                        y1 = (box.y - box.h / 2)
                        print('%d,-1,%.2f,%.2f,%.2f,%.2f,%.6f,-1,-1,-1' %
                              (i + 1, x1, y1, box.w, box.h, box.c),
                              file=out_file)
예제 #11
0
 def __init__(self):
     RUN_DIR = "../darknet"
     os.chdir(RUN_DIR)
     dn.set_gpu(0)
     self.net = dn.load_net(options['model'].encode('utf8'), options['load'].encode('utf8'), 0)
     self.meta = dn.load_meta(options['data'].encode('utf8'))
     self.threshold = options['threshold']
     os.chdir(APP_ROOT)
     print("INIT DONE ========================")
     print("Back to: ", os.getcwd())
예제 #12
0
    def __init__(self, detector_num=0):
        import darknet as dn
        dn.set_gpu(int(constants.DARKNET_GPU))
        self.detector_num = detector_num
        self.net = dn.load_net(
            py_util.encode(WEIGHT_PATH + 'yolov3-thor.cfg'),
            py_util.encode(WEIGHT_PATH + 'yolov3-thor_final.weights'), 0)
        self.meta = dn.load_meta(py_util.encode(WEIGHT_PATH + 'thor.data'))

        self.count = 0
예제 #13
0
def detect(cfg_file, weight_file, video_file):

    dn.set_gpu(0)
    net = dn.load_net(cfg_file, weight_file, 0)
    meta = dn.load_meta("cfg/coco.data")

    print("video: %s" % video_file)
    cap = cv2.VideoCapture(video_file)
    video_len = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    terminate, is_paused = False, False

    idx = 0
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    video_writer = cv2.VideoWriter("gray_processed.mp4", fourcc, fps, (width, height))


    while not terminate and cap.isOpened():
        idx += 1
        print("processing: %.4f%%" % (idx * 100.0 / video_len))
        #print("debug")

        if not is_paused:
            ret, frame = cap.read()
            if not ret:
                break
            boxes = dn.detect_np(net, meta, frame)

        new_frame = my_plot(frame.copy(), boxes)
        video_writer.write(new_frame)

        """
        cv2.imshow('image', new_frame)
        key = cv2.waitKey(1)

        if key & 255 == 27:  # ESC
            print("terminating")
            terminate = True
        elif key & 255 == 32:  # ' '
            print("toggeling pause: " + str(not is_paused))
            is_paused = not is_paused
        elif key & 255 == 115:  # 's'
            print("stepping")
            ret, frame = cap.read()
            if not ret:
                break
            boxes = dn.detect_np(net, meta, frame)
            is_paused = True
        """

    cap.release()
    video_writer.release()
예제 #14
0
파일: tracker.py 프로젝트: Bhargee/fmot
def main(gpu_ind, data_path, output_path):
    # setup GPU and load model
    dn.set_gpu(gpu_ind)
    net = dn.load_net(b"darknet/cfg/yolov3.cfg", b"darknet/yolov3.weights", 0)
    meta = dn.load_meta(b"darknet/cfg/coco.data")

    # delete old files and get data filenames
    _prep_output_path(output_path)
    data = _get_data_raw(data_path)  # `data` is a generator

    #_test_detector(net, meta, data, output_path)
    _track(net, meta, data, output_path)
예제 #15
0
 def __init__(self, args):
     dn.set_gpu(0)
     if args.object:
         self.conf = .25
         model = OBJECT
     else:
         self.conf = .8
         model = HELMET
     self.net = dn.load_net(model['cfg'].encode("ascii"),
                            model['weights'].encode("ascii"), 0, 1)
     self.meta = dn.load_meta(model['data'].encode("ascii"))
     self.dark_image = dn.make_image(dn.network_width(self.net),
                                     dn.network_height(self.net), 3)
예제 #16
0
    def __init__(self):
        threading.Thread.__init__(self)
        print("[Threade] DARKNET")
        sys.path.append(os.path.join(os.getcwd(), 'python/'))
        import darknet as dn
        import pdb
        print("Import successfully...")

        dn.set_gpu(0)
        self.net = dn.load_net("cfg/yolov3.cfg".encode('utf-8'),
                               "backup/yolov3_3300.weights".encode('utf-8'), 0)
        self.meta = dn.load_meta("cfg/coco.data".encode('utf-8'))
        print(
            "========================== WAITING... ============================"
        )
예제 #17
0
    def __init__(self,
                 configPath="cfg/yolo-obj.cfg",
                 weightPath="weights/yolo-obj_final.weights",
                 metaPath="cfg/obj.data",
                 gpu_id=1):

        self.metaMain, self.netMain, self.altNames, self.dark = None, None, None, darknet
        # self.logger = setup_logger(log_level=logging.CRITICAL)
        if HAS_GPU:
            set_gpu(gpu_id)
        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 self.netMain is None:
            self.netMain = darknet.load_net_custom(configPath.encode("ascii"),
                                                   weightPath.encode("ascii"),
                                                   0, 1)  # batch size = 1
        if self.metaMain is None:
            self.metaMain = darknet.load_meta(metaPath.encode("ascii"))
        if self.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")
                                self.altNames = [x.strip() for x in namesList]
                    except TypeError:
                        pass
            except Exception:
                pass
        self.size = (self.dark.network_width(self.netMain),
                     self.dark.network_height(self.netMain))
        self._seconds = 0
예제 #18
0
def main():
    dn.set_gpu(0)
    net = dn.load_net("model_data/yolov3.cfg".encode('utf-8'),
                      "model_data/yolov3.weights".encode('utf-8'), 0)
    meta = dn.load_meta("model_data/coco.data".encode('utf-8'))

    # Configure depth and color streams
    pipeline = rs.pipeline()
    config = rs.config()
    config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
    config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)

    # Start streaming
    pipeline.start(config)

    # try:
    #     while True:
    # Wait for a coherent pair of frames: depth and color
    frames = pipeline.wait_for_frames()
    depth_frame = frames.get_depth_frame()
    color_frame = frames.get_color_frame()
    if not depth_frame or not color_frame:
        # continue
        pass

    # Convert images to numpy arrays
    depth_image = np.asanyarray(depth_frame.get_data())
    color_image = np.asanyarray(color_frame.get_data())

    image = Image.fromarray(color_image)
    r = dn.detect(net, meta, image)
    # print(r)

    # Show images
    cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
    cv2.imshow('RealSense', depth_image)
    cv2.imshow('color_image', color_image)

    cv2.waitKey(0)
    #         if cv2.waitKey(1) == 27:
    #             break

    #     cv2.destroyAllWindows()

    # finally:

    # Stop streaming
    pipeline.stop()
예제 #19
0
 def __init__(self, metaPath, configPath, weightPath, gpu_id=2, batch=1):
     '''
     :param metaPath:   ***.data 存储各种参数
     :param configPath: ***.cfg  网络结构文件
     :param weightPath: ***.weights yolo的权重
     :param batch:      ########此类只支持batch=1############
     '''
     assert batch == 1, "batch必须为1"
     # 设置gpu_id
     darknet.set_gpu(gpu_id)
     # 网络
     network, class_names, class_colors = darknet.load_network(
         configPath, metaPath, weightPath, batch_size=batch)
     self.network = network
     self.class_names = class_names
     self.class_colors = class_colors
    def __init__(
        self,
        config_path: str = str(DEF_CONF, encoding="ascii"),
        weights_path: str = str(DEF_W, encoding="ascii"),
        data_path: str = str(DEF_DATA, encoding="ascii"),
        gpu_enabled: bool = True,
    ):

        self._config_path = config_path.encode("ascii")
        self._weights_path = weights_path.encode("ascii")
        self._data_path = data_path.encode("ascii")
        self._gpu_enabled = 0 if gpu_enabled else 1
        dn.set_gpu(self._gpu_enabled)
        self._net = dn.load_net(self._config_path, self._weights_path, 0)
        self._metadata = dn.load_meta(self._data_path)
        self._darknet_image = dn.make_image(dn.network_width(self._net),
                                            dn.network_height(self._net), 3)
예제 #21
0
    def __init__(self, detector_num=0):
        import darknet as dn
        dn.set_gpu(int(constants.DARKNET_GPU))
        self.detector_num = detector_num
        #self.net = dn.load_net(py_util.encode(WEIGHT_PATH + 'yolov3-thor.cfg'),
        #                       py_util.encode(WEIGHT_PATH + 'yolov3-thor_final.weights'), 0)
        #self.meta = dn.load_meta(py_util.encode(WEIGHT_PATH + 'thor.data'))
        #self.net_custom = dn.load_net(py_util.encode(WEIGHT_PATH + 'yolov4-custom.cfg'),
        #                       py_util.encode(WEIGHT_PATH + 'yolov4-custom_4000.weights'), 0)
        #self.meta_custom = dn.load_meta(py_util.encode(WEIGHT_PATH + 'obj_less.data'))
        self.net_origin = dn.load_net(
            py_util.encode(WEIGHT_PATH + 'yolov4.cfg', 'ascii'),
            py_util.encode(WEIGHT_PATH + 'yolov4.weights', 'ascii'), 0)
        self.meta_origin = dn.load_meta(
            py_util.encode(WEIGHT_PATH + 'coco.data', 'ascii'))

        self.count = 0
예제 #22
0
 def __init__(self, metaPath, configPath, weightPath, namesPath, gpu_id=2):
     '''
     :param metaPath:   ***.data 存储各种参数
     :param configPath: ***.cfg  网络结构文件
     :param weightPath: ***.weights yolo的权重
     :param namesPath:  ***.data中的names路径,这里是便于读取使用
     :param gpu_id:     gpu id
     '''
     # 设置gpu
     darknet.set_gpu(gpu_id)
     # 网络
     self.netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch=1
     # 各种参数
     self.metaMain = darknet.load_meta(metaPath.encode("ascii"))
     # 读取标签类别名称列表
     self.names = self.read_names(namesPath)
     # 每类颜色肯定一致,但是每次执行不一定都一样
     self.colors = self.color()
예제 #23
0
    def __init__(self):
        self.image_pub = rospy.Publisher("/camera/detection/out",
                                         CameraObjects)

        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber(
            "/carla/ego_vehicle/camera/rgb/front/image_color",
            Image,
            self.callback,
            buff_size=150,
            queue_size=1)
        # Give the configuration and weight files for the model and load the network using them.
        modelConfiguration = b"/home/dieter/darknet/cfg/yolov2-tiny.cfg"
        modelWeights = b"/home/dieter/darknet/data/yolov2-tiny.weights"

        dn.set_gpu(0)

        self.net = dn.load_net(modelConfiguration, modelWeights, 0)
        self.meta = dn.load_meta(b"/home/dieter/darknet/cfg/coco.data")
예제 #24
0
    def __init__(self):

        self.dataFile = "/media/sub_data/data/7_2.data"
        self.weightFile = "/media/sub_data/weights/7_9_v2.weights"
        self.cfgFile = "/media/sub_data/cfg/7_9_v2.cfg"

        self.useVideo = False
        self.videoPath = "/media/sub_data/example3.mp4"

        self.usePicture = True
        self.picturePath = "../../0.png"

        self.activeCamera = None

        #Top left hole, TR hole, Bottom Hole, cherry, banana, grape, TLH TRC, TLH BRC, TLH BLC, TLH TLC, ....
        self.torpedoSrcPoints = [(0, 0, 0), (12, 0, 0), (5.5, -35.5, 0),
                                 (-.25, -.5, 0), (.5, -.5, 0), (1, -.5, 0)]
        self.cornerLocations = [(3, -5, 0), (3, 5, 0), (-3, 5, 0), (-3, 5, 0),
                                (12, -3, 0), (12, 3, 0), (9, 3, 0), (9, -3, 0),
                                (9, -32, 0), (9, -39, 0), (2, -39, 0),
                                (2, -32, 0)]
        self.torpedoSrcPoints = self.torpedoSrcPoints + self.cornerLocations

        self.torpedoDictionary = {
            "Top Left Hole": 0,
            "Top Right Hole": 1,
            "Bottom Hole": 2
        }  #, "Cherry":3, "Banana":4, "Grape":5, "TLHTRC":5,"TLHBRC":6,"TLHBLC":7,"TLHTLC":8 }
        self.srcPoints = []
        self.imgPoints = []

        self.torpedoBoardOrientation = []

        self.camMat = [[808, 0, 408], [0, 608, 304], [0, 0, 1]]

        dn.set_gpu(0)

        self.detectionDictionary = {}

        self.getList = []
        self.running = True
예제 #25
0
 def __init__(self, tiny=False):
     try:  # keep only one instance design to avoid "out of memory"
         self.meta = QuickDarknet.meta
         self.net = QuickDarknet.net
         return
     except:  # if no instance then go ahead
         pass
     dn.set_gpu(0)
     if tiny:  # tiny-weights would be faster but not precise enough
         self.net = dn.load_net(
             str.encode(os.path.join(dir, "cfg/yolov3-tiny.cfg")),
             str.encode(os.path.join(dir, "weights/yolov3-tiny.weights")),
             0)
     else:
         self.net = dn.load_net(
             str.encode(os.path.join(dir, "cfg/yolov3.cfg")),
             str.encode(os.path.join(dir, "weights/yolov3.weights")), 0)
     self.meta = dn.load_meta(str.encode(os.path.join(dir,
                                                      "cfg/coco.data")))
     QuickDarknet.meta = self.meta  # save the instance to class static member
     QuickDarknet.net = self.net
예제 #26
0
def init_network(cfg_file=bytes(os.path.join(ROOT_DIR, "cfg/yolov3.cfg"),
                                encoding='utf-8'),
                 weights_file=b"yolov3.weights",
                 data_cfg=bytes(os.path.join(ROOT_DIR, "cfg/coco.data"),
                                encoding='utf-8'),
                 use_gpu=False):

    # Check if files exist
    if not os.path.exists(cfg_file):
        raise ValueError("ERROR: cfg_file does not exist! Given:", cfg_file)

    if not os.path.exists(weights_file):
        raise ValueError("ERROR: weights_file does not exist! Given:",
                         weights_file)

    if not os.path.exists(data_cfg):
        raise ValueError("ERROR: data_cfg does not exist! Given:", data_cfg)

    if type(weights_file) is str:
        weights_file = bytes(os.path.realpath(weights_file), encoding='utf-8')

    if type(cfg_file) is str:
        cfg_file = bytes(os.path.realpath(cfg_file), encoding='utf-8')

    if type(data_cfg) is str:
        data_cfg = bytes(os.path.realpath(data_cfg), encoding='utf-8')

    # Don't use GPU?
    if use_gpu:
        dn.set_gpu(1)
    else:
        dn.set_gpu(0)

    # Load the network
    net = dn.load_net(cfg_file, weights_file, 0)

    # Load metadata for labels
    meta = dn.load_meta(data_cfg)

    return net, meta
def predict_608(q_res, q_img, i):
    dn.set_gpu(i)
    net = dn.load_net(cfg, weights, 0)
    meta = dn.load_meta(data)
    while True:
        (cell, x, y) = q_img.get()
        if x == None:
            break
        det = detect3(net, meta, cell)
        if len(det) == 0:
            continue
        for d in det:
            p = d[1]
            x_ = d[2][0] + x - 304
            y_ = d[2][1] + y - 304
            w = d[2][2]
            h = d[2][3]
            if w * h < 500:
                continue

            # q_res.put({"x":x_, "y":y_, "w":w, "h":h, "p":p})

            # save image.
            l = int(d[2][0] - w / 2 + 0.5)
            r = int(l + w + 0.5)
            hi = int(d[2][1] - h / 2 + 0.5)
            lo = int(hi + h + 0.5)
            tmp = cell[l:r, hi:lo, :]
            var = np.var(tmp)

            if var < 1250:
                continue

            q_res.put({"x": x_, "y": y_, "w": w, "h": h, "p": p})

            # cv2.imwrite("./result/pos/"+str(w)+"_"+str(h)+".bmp", cell[l:r,hi:lo,:])

    for i in range(1):
        q_res.put(None)
예제 #28
0
	def __init__(self):
		QtCore.QThread.__init__(self)
		self.getList = []

		self.dataFile = "/media/sub_data/data/8_1.data"
		self.weightFile = "/media/sub_data/weights/8_1.weights"
		self.cfgFile = "/media/sub_data/cfg/8_1.cfg"

		self.frontCamera = None
		self.botCamera = None


		self.useVideo = False
		self.videoPath = "/media/sub_data/example3.mp4"

		self.srcPoints = [(0,0,0), (1,0,0), (2,0,0), (1, -.5, 0)]
		#Top left hole, TR hole, Bottom Hole, cherry, banana, grape, TLH TRC, TLH BRC, TLH BLC, TLH TLC, ....
		self.torpedoSrcPoints = [(0,0,0), (12,0,0), (5.5, -35.5, 0), (-.25, -.5, 0), (.5, -.5, 0), (1, -.5, 0)] 
		self.cornerLocations = [(3, -5, 0), (3, 5, 0), (-3, 5, 0), (-3, 5, 0), (12, -3, 0), (12, 3, 0), (9, 3, 0), (9, -3,0), (9, -32, 0), (9, -39,0), (2, -39, 0), (2, -32,0)]
		self.torpedoSrcPoints = self.torpedoSrcPoints + self.cornerLocations

		self.torpedoDictionary = {"Top Left Hole":0, "Top Right Hole":1, "Bottom Hole":2, "Cherry":3, "Banana":5, "Grape":4, "TLHTRC":5,"TLHBRC":6,"TLHBLC":7,"TLHTLC":8 } 
		self.srcPoints = []
		self.imgPoints = []


		self.activeCamera = None
		self.camMat = [[808, 0, 408],
			       [0, 608, 304],
			       [0,   0, 1]]
		if not onLinux:
			return

		dn.set_gpu(0)

		self.detectionDictionary = {}

		self.running = True
def init_cellphone():
    ''' Initializing function
        Input:
                None
        return:
                None
    '''
    yolo_logger.info('Initializing')
    # get darkent parameters
    global dn, net, meta
    dn_path, mdl_cfg, weights, meta_f = common.get_yolo_config()

    cellphone_weights = './yolov3_32095000.weights'
    #cellphone_weights = './yolov3_32025000.weights'
    cellphone_cfg = './lyc_cellphone.cfg'
    cellphone_meta = './lyc_cellphone_coco.data'

    # check darknet path
    common.file_check(dn_path + os_sep + 'darknet.py', yolo_logger,
                      'darknet.py NOT found!', 8)
    common.file_check(mdl_cfg, yolo_logger, 'yolo cfg file set wrong!', 9)
    common.file_check(weights, yolo_logger, 'yolo weight file set wrong!', 9)
    common.file_check(meta_f, yolo_logger, 'yolo meta file set wrong!', 9)
    yolo_logger.info('Yolo parameters get successfully')
    # import darknet
    sys.path.append(dn_path)
    print(dn_path)
    import darknet as dn
    dn.set_gpu(0)
    yolo_logger.info('GPU set to {0}'.format(gpu_idx))
    yolo_logger.info('Darknet import successfully')

    # initialize darknet network
    meta = dn.load_meta(cellphone_meta.encode('utf-8'))
    yolo_logger.info('Darknet meta load successfully')
    net = dn.load_net(cellphone_cfg.encode('utf-8'),
                      cellphone_weights.encode('utf-8'), 0)
    yolo_logger.info('Darknet network load successfully')
예제 #30
0
    def run(self):
        import darknet as dn
        dn.set_gpu(0)
        net = dn.load_net("cfg/yolo.cfg", "yolo.weights", 0)
        meta = dn.load_meta("cfg/coco.data")
        # r = dn.detect(net, meta, "data/bedroom.jpg")
        while True:
            global task_queue

            if len(task_queue) != 0:
                with lock:
                    if len(task_queue) >= MAX_BATCH_SIZE:
                        new_batch = task_queue[:MAX_BATCH_SIZE]
                        task_queue = task_queue[MAX_BATCH_SIZE:]
                    else:
                        new_batch = task_queue
                        for i in range(MAX_BATCH_SIZE - len(task_queue)):
                            new_batch.append(
                                new_batch[0]
                            )  # maskRCNN要求图片数量与BATCH_SIZE相等,不足时使用第一张图片填充
                        task_queue = []
                identities = [item[0] for item in new_batch]
                msgs = [item[1] for item in new_batch]
                '''
                多张图片处理
                '''
                msgs = [json.loads(msg) for msg in msgs]
                img_paths = [msg['img_path'] for msg in msgs]
                results = []
                for img_path in img_paths:
                    result = dn.detect(net, meta, img_path)
                    results.append(result)

                for i, identity in enumerate(identities):
                    result = results[i]
                    socket.send_multipart([identity, json.dumps(result)])
예제 #31
0
# Stupid python path shit.
# Instead just add darknet.py to somewhere in your python path
# OK actually that might not be a great idea, idk, work in progress
# Use at your own risk. or don't, i don't care

import sys, os
sys.path.append(os.path.join(os.getcwd(),'python/'))

import darknet as dn
import pdb

dn.set_gpu(0)
net = dn.load_net("cfg/yolo-thor.cfg", "/home/pjreddie/backup/yolo-thor_final.weights", 0)
meta = dn.load_meta("cfg/thor.data")
r = dn.detect(net, meta, "data/bedroom.jpg")
print r

# And then down here you could detect a lot more images like:
r = dn.detect(net, meta, "data/eagle.jpg")
print r
r = dn.detect(net, meta, "data/giraffe.jpg")
print r
r = dn.detect(net, meta, "data/horses.jpg")
print r
r = dn.detect(net, meta, "data/person.jpg")
print r