Coder Social home page Coder Social logo

leonlok / deep-sort-yolov4 Goto Github PK

View Code? Open in Web Editor NEW
496.0 23.0 172.0 119.13 MB

People detection and optional tracking with Tensorflow backend.

License: GNU General Public License v3.0

Python 100.00%
yolov4 deep-sort deep-sort-tracking people-tracker people-tracking asynchronous asynchronous-io yolo tensorflow asynchronous-processing

deep-sort-yolov4's Introduction

Introduction

This project was inspired by:

I swapped out YOLO v3 for YOLO v4 and added the option for asynchronous processing, which significantly improves the FPS. However, FPS monitoring is disabled when asynchronous processing is used since it isn't accurate.

In addition, I took the algorithm from this paper and implemented it into deep_sort/track.py. The original method for confirming tracks was based simply on the number of times an object has been detected without considering detection confidence, leading to high tracking false positive rates when unreliable detections occur (i.e. low confidence true positives or high confidence false positives). The track filtering algorithm reduces this significantly by calculating the average detection confidence over a set number of detections before confirming a track.

See the comparison video below.

Low confidence track filtering

Comparison Video Link

Navigate to the appropriate folder to use low confidence track filtering. The above video demonstrates the difference.

See the settings section for parameter instructions.

YOLO v3 and YOLO v4 comparison video with Deep SORT

Comparison Video Link

With asynchronous processing

As you can see in the gif, asynchronous processing has better FPS but causes stuttering.

This code only detects and tracks people, but can be changed to detect other objects by changing lines 103 in yolo.py. For example, to detect people and cars, change

if predicted_class != 'person':
    continue

to

if predicted_class not in ('person', 'car'):
    continue

Performance

Real-time FPS with video writing:

  • ~4.3fps with YOLO v3
  • ~10.6fps with YOLO v4

Turning off tracking gave ~12.5fps with YOLO v4.

YOLO v4 performs much faster and appears to be more stable than YOLO v3. All tests were done using an Nvidia GTX 1070 8gb GPU and an i7-8700k CPU.

Quick start

Download and convert the Darknet YOLO v4 model to a Keras model by modifying convert.py accordingly and run:

python convert.py

Then run demo.py:

python demo.py

Settings

Normal Deep SORT

By default, tracking and video writing is on and asynchronous processing is off. These can be edited in demo.py by changing:

tracking = True
writeVideo_flag = True
asyncVideo_flag = False

To change target file in demo.py:

file_path = 'video.webm'

To change output settings in demo.py:

out = cv2.VideoWriter('output_yolov4.avi', fourcc, 30, (w, h))

Deep SORT with low confidence track filtering

This version has the option to hide object detections instead of tracking. The settings in demo.py are

show_detections = True
writeVideo_flag = True
asyncVideo_flag = False

Setting show_detections = False will hide object detections and show the average detection confidence and the most commonly detected class for each track.

To modify the average detection threshold, go to deep_sort/tracker.py and change the adc_threshold argument on line 40. You can also change the number of steps that the detection confidence will be averaged over by changing n_init here.

Training your own models

YOLO v4

See https://github.com/Ma-Dan/keras-yolo4.

Deep SORT

Please note that the tracking model used here is only trained on tracking people, so you'd need to train a model yourself for tracking other objects.

See https://github.com/nwojke/cosine_metric_learning for more details on training your own tracking model.

For those that want to train their own vehicle tracking model, I've created a tool for converting the DETRAC dataset into a trainable format for cosine metric learning and can be found in my object tracking repository here. The tool was created using the earlier mentioned paper as reference with the same parameters.

Dependencies

  • Tensorflow GPU 1.14
  • Keras 2.3.1
  • opencv-python 4.2.0
  • imutils 0.5.3
  • numpy 1.18.2
  • sklearn

Running with Tensorflow 1.14 vs 2.0

Navigate to the appropriate folder and run python scripts.

Conda environment used for Tensorflow 2.0

(see requirements.txt)

  • imutils 0.5.3
  • keras 2.3.1
  • matplotlib 3.2.1
  • numpy 1.18.4
  • opencv-python 4.2.0.34
  • pillow 7.1.2
  • python 3.6.10
  • scikit-learn 0.23.1
  • scipy 1.4.1
  • sklearn 0.19
  • tensorboard 2.2.1
  • tensorflow 2.0.0
  • tensorflow-estimator 2.1.0
  • tensorflow-gpu 2.2.0

deep-sort-yolov4's People

Contributors

cindyweng avatar leonlok avatar neutrinoxy avatar sorgina13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

deep-sort-yolov4's Issues

Support Multi-gpu?

Hi,
Thanks for your great work, I want to know if your repo support multi-gpu(It seems to be not). Can you add multi-gpu code?

Track's box considerably different from detection's bounding box

image
I trained yolov4 for vehicle include : 4 classs ( truck, car,bus,motorbike) and cosine-softmax for Deep SORT
The trained-model indicate a good trainning process. But, when i have pipeline DeepSORT and Yolov4 , Track's BOX is not fit to detected-object. Its is constantly changed

Someone explain the sess.run in yolo.py?

I don't really understand the [self.boxes, self.scores, self.classes] in self.generate().
My purpose is to use yolo4.pb to do some prediction just in tensorflow, but here [self.boxes, self.scores, self.classes] do some tricks in keras and I don't know how to do this exchange using yolo4.pb.

out_boxes, out_scores, out_classes = self.sess.run(
            [self.boxes, self.scores, self.classes],
            feed_dict={
                self.yolo_model.input: image_data,
                self.input_image_shape: [image.size[1], image.size[0]]
                # K.learning_phase(): 0
            })

Thanks for the coming help!

I use amir-abdi/keras_to_tensorflow convert the yolo4.h5 to yolo4.pb. The format of outputs are different compared to using yolo4.h5.

Can't convert my own trained model (Yolov4-csp)

Hi
I have a problem when converting my model to a .h5 file using the convert file. I had no problems converting from a model trained with yolov4 so I'm guessing there's some value that i need to change in order to be able to convert my file. I'm using the corresponding .txt and weights files for each model so I'm sure that's not the issue. BTW I'm getting this error with the csp model:
.
.
.

Converting 104
Traceback (most recent call last):
File "convert.py", line 171, in
yolo4_model = Yolo4(score, iou, anchors_path, classes_path, model_path, weights_path)
File "convert.py", line 157, in init
self.load_yolo()
File "convert.py", line 130, in load_yolo
buffer=weights_file.read(weights_size * 4))
TypeError: buffer is too small for requested array

Thanks and regards!

getting error when converting yolo-obj.weights to yolo-obj.h5

Hi,
I have worked on training yolo-custom.weights with my own dataset. I took the mode(yolo-obj_1000.weights) when it finished 1000 iterations and tried to convert it to yolo-obj_1000.h5.
But I am getting the following error:

File "convert.py", line 171, in <module>
    yolo4_model = Yolo4(score, iou, anchors_path, classes_path, model_path, weights_path)
  File "convert.py", line 157, in __init__
    self.load_yolo()
  File "convert.py", line 98, in load_yolo
    buffer=weights_file.read(weights_size * 4))
TypeError: buffer is too small for requested array

also while testing my custom model yolo-obj_1000.weights, I am getting good results for images and videos

Generating anchors my custom keras model

When I am running yolo.py for tracking with my custom keras model, I am getting following error:

main(YOLO())
 File "/home/unizen/Deep-SORT-YOLOv4/tensorflow1.14/yolo.py", line 30, in __init__
   self.boxes, self.scores, self.classes = self.generate()
 File "/home/unizen/Deep-SORT-YOLOv4/tensorflow1.14/yolo.py", line 51, in generate
   self.yolo_model = load_model(model_path, custom_objects={'Mish': Mish}, compile=False)
 File "/home/unizen/anaconda3/lib/python3.7/site-packages/keras/engine/saving.py", line 419, in load_model
   model = _deserialize_model(f, custom_objects, compile)
 File "/home/unizen/anaconda3/lib/python3.7/site-packages/keras/engine/saving.py", line 221, in _deserialize_model
   model_config = f['model_config']
 File "/home/unizen/anaconda3/lib/python3.7/site-packages/keras/utils/io_utils.py", line 302, in __getitem__
   raise ValueError('Cannot create group in read only mode.')
ValueError: Cannot create group in read only mode.

This might be due to the different yolo_anchors.txt for my model. Do you have any idea of generating anchors for custom yolo model

Getting tracking output for an undetected object

Hi Leon!

Thank you for the great work. I couldn't find a way to extract tracking output if YOLO didn't detect the object.
In other words, I want to get bounding box output from DeepSort where if there isn't any detection output for that specific frame, Deepsort didn't output a b-box for that frame.

Is there a way to do this, interfere with the tracking process, and get a predicted bounding box output?

Thanks in advance.

Tiny_yolov4 conversion and demo

Hi,
1-There is an error while converting tiny_yolov4.weights to tiny_yolov4.h5. Do we need to make some changes? i have tried to change convert.py for anchors etc but still not working.
2- If we got tiny_yolov4.h5, can we run using the same settings or we still need to make changes?
3-The speed for yolov4 is very slow, it's 0.62 FPS on GTX 1080 Ti. what is the reason?

The script detected nothing.

Good afternoon, I did everything step by step and did not change anything in Google Colab through your notepad. But absolutely nothing was detected. I can't figure out what the problem is.
Thank you in advance for your response.
Снимок экрана 2021-04-29 в 21 54 17
Снимок экрана 2021-04-29 в 21 54 25

Deep-Sort-yolov3

Hi,
I have trained new dataset with 3 labels and obtained custom yolov3 keras model. Do u Know how to apply it for tracking?.

Kindly do reply @LeonLok

Error in convert

convert.py, line 128, in load_yolo
conv_weights = np.ndarray(
TypeError: buffer is too small for requested array

Only using CPU?

Hi I am testing you project and everything seems to work fine.
My question is that I only see CPU usage (around 75%) and almost nothing GPU (4%) is that correct?
My HW
Ubuntu 20.04
Intel i5
Nvidia GTX 2060 8 GB

Only get 1 FPS

Thanks in advance

convert.py problems and no detections

Hi.
I'm using Tensorflow 2.0.0 version and I had some problems with convert.py
At every line with np.ndarray(shape=(1,), dtype='int32') #buffer=weights_file.read(4) I obtained the following error:
TypeError: buffer is too small for requested array.
So I removed the buffer option in every nd.array line and it worked.
Now if I run demo.py I have no detections.

detect nothing

I send a traffic video, and change class to car, but nothing is detected.

Versions problems

Hello, dear contributers. I installed all dependencies from your requirments.txr manually(because I have windows), but I have got I lot of version incompatibilities (with keras, tensorflow). Please, could you send me all actual versions of your dependencies you use today.
Best regards, Yurii Vavrynchuk

How to get asynchronous mode working?

So why does videocaptureasync.py have NoneType? And how to fix this error? While running asynchronous mode it kind of works and goes through while loop in demo.py . From the image below demo.py goes through while loop 42 times and then has an error. I found a link that talked about this error but unable to fix the error currently.
https://github.com/alievk/avatarify/issues/67

VideoAsync

Works very slow

Hey I was testing your code and its weird but it seems to run with half of the speed of other implementation witch uses YOLOv3 with tensorflow. I don't know if I am doing something wrong but YOLOv3 manages to run 1.4FPS on CPU and 7FPS on GPU but this implementation runs around 0.6FPS on CPU and 3 FPS on GPU. I value boost in accuracy but damn, it works so slow.

Demo.py showing error after weight file conversion

Hello i changed my custom trained weight file inti .h5 file and then run the python demo.py - i get this error. anybody having any idea about this ?

InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 81120 values, but the requested shape requires a multiple of 689520
[[node Reshape_15 (defined at /home/tubo/anaconda3/envs/yolo/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:2440) ]]
[[node boolean_mask_147/GatherV2 (defined at /home/tubo/YOLOv4/tensorflow2.0/deep-sort-yolov4/yolo4/model.py:279) ]]

linear_assignment error

platforrm:tensorflow1.14
from sklearn.utils.linear_assignment_ import linear_assignment causes no linear_assignment error,
using from scipy.optimize import linear_sum_assignment as linear_assignment insteads,but new error occurs:

Traceback (most recent call last):
File "demo.py", line 144, in
main(YOLO())
File "demo.py", line 103, in main
tracker.update(detections)
File "D:\Deep-SORT-YOLOv4-master\tensorflow1.14\deep-sort-yolov4\deep_sort\tracker.py", line 69, in update
self._match(detections)
File "D:\Deep-SORT-YOLOv4-master\tensorflow1.14\deep-sort-yolov4\deep_sort\tracker.py", line 127, in _match
detections, iou_track_candidates, unmatched_detections)
File "D:\Deep-SORT-YOLOv4-master\tensorflow1.14\deep-sort-yolov4\deep_sort\linear_assignment.py", line 64, in min_cost_matching
if col not in indices[:, 1]:
TypeError: tuple indices must be integers or slices, not tuple

WARNING:tensorflow:From D:\Documents\Downloads\Compressed\Deep-SORT-YOLOv4-master\tools\generate_detections.py:80: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. Traceback (most recent call last): File "demo.py", line 143, in <module> main(YOLO()) File "demo.py", line 73, in main boxes, confidence, classes = yolo.detect_image(image) File "D:\Documents\Downloads\Compressed\Deep-SORT-YOLOv4-master\yolo.py", line 96, in detect_image K.learning_phase(): 0 File "D:\ProgramData\Anaconda3\envs\tf14_gpu\lib\site-packages\tensorflow\python\client\session.py", line 950, in run run_metadata_ptr) File "D:\ProgramData\Anaconda3\envs\tf14_gpu\lib\site-packages\tensorflow\python\client\session.py", line 1149, in _run str(subfeed_t.get_shape()))) ValueError: Cannot feed value of shape (1, 416, 416, 3) for Tensor 'input_1:0', which has shape '(?, 608, 608, 3)' (tf14_gpu) PS D:\Documents\Downloads\Compressed\Deep-SORT-YOLOv4-master>

WARNING:tensorflow:From D:\Documents\Downloads\Compressed\Deep-SORT-YOLOv4-master\tools\generate_detections.py:80: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.

Traceback (most recent call last):
File "demo.py", line 143, in
main(YOLO())
File "demo.py", line 73, in main
boxes, confidence, classes = yolo.detect_image(image)
File "D:\Documents\Downloads\Compressed\Deep-SORT-YOLOv4-master\yolo.py", line 96, in detect_image
K.learning_phase(): 0
File "D:\ProgramData\Anaconda3\envs\tf14_gpu\lib\site-packages\tensorflow\python\client\session.py", line 950, in run
run_metadata_ptr)
File "D:\ProgramData\Anaconda3\envs\tf14_gpu\lib\site-packages\tensorflow\python\client\session.py", line 1149, in _run
str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1, 416, 416, 3) for Tensor 'input_1:0', which has shape '(?, 608, 608, 3)'
(tf14_gpu) PS D:\Documents\Downloads\Compressed\Deep-SORT-YOLOv4-master>

last location tracked object

Hi, I'm trying to find last location of tracked object on IP Camera with adding object id and tracked loc taked from to_tlbr() function than grouped locations according to id's and access last location of the object according to the id. Because its leave and last loc always updated I do not handle with this problem. Could you guide me please, I'm lost :)
Thanks for your time..

python convert.py is no fonctionning

mon problème moyen est cette erreur si j'exécute python convert.py. aide moi s'il te plait

Traceback (dernier appel le plus récent):
Fichier "convert.py", ligne 172, dans
yolo4_model = Yolo4 (score, iou, anchors_path, classes_path, model_path, weights_path)
Fichier "convert.py", ligne 158, dans init
self.load_yolo ()
Fichier "convert.py", ligne 128, dans load_yolo
conv_weights = np.ndarray (
TypeError: le tampon est trop petit pour le tableau demandé

# sklearn version

when you run the problem may hapeen 'No module named ´sklearn.utils.linear_assignment'.you should change your sklearn version with command 'pip install scikit-learn==0.19'. the 'Dependencies' should add the 'sklearn' version informaintion

Question about the deep sort model

The README of your code, it shows thatby changing the detection for person and car, I want to ask that is it need to retrain the deepsort model for tracking both person and car? or it just work on both classes?

Unable to track with custom keras model

@LeonLok
Hi,
Since, I am getting error when I am converting yolo custom model(trained with my dataset) to keras model like this:

File "convert.py", line 173, in <module>
    yolo4_model = Yolo4(score, iou, anchors_path, classes_path, model_path, weights_path)
  File "convert.py", line 157, in __init__
    self.load_yolo()
  File "convert.py", line 98, in load_yolo
    buffer=weights_file.read(weights_size * 4))
TypeError: buffer is too small for requested array

I tried converting using this code:
https://github.com/Runist/YOLOv4/blob/master/utils/convert.py

It is successful, But I am unable to track with that keras-model when I am using demo.py .

If you don't mind, Could you go through the both codes and check where it is wrong

Layer weight shape not compatible

Hi,

I've tried to use your convert.py to convert my ownl model to a h5 model but i get:

ValueError: Layer weight shape (3, 3, 32, 64) not compatible with provided weight shape (3, 3, 32, 32)

Any ideas?

I've set my cfg file, my own trained weights file and my classes file correctly in convert.py.

I've trained my model with alexeyab/darknet v4 in 608 size (which i've also set correctly in convert.py)

convert.py, demo.py not work

When i edit gpus=4 in convert.py, line 169 it occurs error like this.

Traceback (most recent call last):
File "convert.py", line 172, in
yolo4_model = Yolo4(score, iou, anchors_path, classes_path, model_path, weights_path, gpus)

File "convert.py", line 157, in init
self.load_yolo()

File "convert.py", line 142, in load_yolo
self.yolo4_model = multi_gpu_model(self.yolo4_model, gpus=self.gpu_num)

NameError: name 'multi_gpu_model' is not defined

I can't find "multi_gpu_model" everywhere..
How can i solved?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.