pjreddie / darknet

Convolutional Neural Networks
http://pjreddie.com/darknet/
Other
25.84k stars 21.33k forks source link

How do you give a json output for multiple video frames? #1281

Open GauranshMathur opened 5 years ago

GauranshMathur commented 5 years ago

I am trying to get an output as json to post in darknet.py because trying to change it in image.c or detector.c didn't seem to be a viable option. But darknet.py also gives problems trying to use video's which could be solved using openCV. So is there a way to use opencv and have a constant json output stream by using a video / webcam to post to a local api.

eesaeedkarimi commented 5 years ago

You can add these lines at the end of darknet.py to write output of detecting images of coco dataset on a json file:

coco_categories = [1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90]

def detect_json(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45): im = load_image(image, 0, 0) num = c_int(0) pnum = pointer(num) predict_image(net, im) dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, None, 0, pnum) num = pnum[0] if (nms): do_nms_obj(dets, num, meta.classes, nms);

res = []
for j in range(num):
    for i in range(meta.classes):
        if dets[j].prob[i] > 0:
            b = dets[j].bbox
            # res.append((coco_categories[i], dets[j].prob[i], (b.x, b.y, b.w, b.h)))
            res.append((coco_categories[i], dets[j].prob[i], (b.x - b.w / 2.0, b.y - b.h / 2.0, b.w, b.h)))
res = sorted(res, key=lambda x: -x[1])
free_image(im)
free_detections(dets, num)
return res

if name == "main":

im = load_image("data/wolf.jpg", 0, 0)

img_path = '/DataBase/Coco/images/val2017'
img_paths = []

for img_path in glob.glob(os.path.join(img_path, '*.jpg')):
    img_paths.append(img_path)

net = load_net("./cfg/yolov3.cfg", "./yolov3.weights", 0)
meta = load_meta("./cfg/coco.data")

data = []

for i_img in range(len(img_paths)):
    img_name = img_paths[i_img]
    print 'i_img', i_img
    print img_name
    r = detect_json(net, meta, img_name)
    print r
    ## For saving output to JSON file
    for i_dt in range(len(r)):
        data_dt = {
            "image_id": int(img_name[img_name.rfind('/') + 1:img_name.rfind('.')]),
            "category_id": r[i_dt][0],
            "bbox": list(r[i_dt][2]),
            "score": float(r[i_dt][1])}
        data.append(data_dt)

## For saving output to JSON file
with open('/DataBase/Coco/results/instances_val2017_results.json', 'w') as outfile:
    json.dump(data, outfile)
    outfile.close()

you can change this code and use it for your purpose.