Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create tensorflowDetection2D app #93

Merged
merged 60 commits into from
Sep 23, 2019
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
87c6673
Detector tensorflow 2D c++ API VGG16 con envío yarp fuente de video p…
Feb 8, 2019
5e99747
.pbtxt 90 labels mscoco model added
Feb 12, 2019
da0a431
Spanish inlines, comments, variables name ... -> English
Feb 14, 2019
40cf3fc
TENSORFLOWDETECTOR Missing Header Guard added
Feb 14, 2019
27143bc
Diretive <cstdlib> missing added and system->std::system
Feb 14, 2019
5df5546
std:: system minor fixes
Feb 14, 2019
b82368f
Minor fixes std: system and tensorflow:: added
Feb 14, 2019
7ec7c31
Without using tensorflow::
Feb 14, 2019
122355b
Minor fixes using tensorflow:: -> removed
Feb 14, 2019
15f470c
using tensorflow:: -> removed
Feb 14, 2019
8f4a558
Namespaces removed and workinggit add -A!
Feb 14, 2019
ec18814
C++ requirements added
Feb 14, 2019
74292e8
CMakeLists.txt fix format
Feb 18, 2019
5de346c
Map library added
Feb 18, 2019
63397b6
Maybe fix use omnibus
Feb 18, 2019
567e50f
Maybe fix use omnibus last fix Network.h
Feb 18, 2019
fdc732a
tensorflow_cc find_package moved from vision/program/tensorflowDetect…
Feb 18, 2019
38b6875
Maybw fix cmake
Feb 19, 2019
6455f7f
Line duplicated removed
Feb 19, 2019
ade7c0f
Install software dependences tensorflow_cc entry added
Feb 19, 2019
007680d
Fix Install software dependences tensorflow_cc entry added
Feb 19, 2019
f01931b
vision/programs/CMakeLists.txt new entry added
Feb 19, 2019
74eb52c
Install tensorflow_cc link updated -> roboticslab-uc3m installation g…
Apr 2, 2019
5d411ab
Tensorflow session test removed -> start tensorflow session directy
Apr 2, 2019
e7c376f
tensorflowDetector2D read directy from yarp port
Apr 2, 2019
50561a4
Labels and pre-trained model added as recourses to use resource finder
Apr 3, 2019
45c9257
Index new entry tensorflowDetection 2D recourses added
Apr 3, 2019
aeb6aa2
path removed -> use resource finder
Apr 3, 2019
ce99c59
System call removed
Apr 3, 2019
05a7388
Get prop image from yarp source
Apr 3, 2019
bd2c319
delay ->removed
Apr 3, 2019
2274e12
yarp port pre -> removed redundance
Apr 3, 2019
36f50d2
Fix extra functions not used -> removed
Apr 3, 2019
4ebcb7e
Send result via yarp port && minor fixes
Apr 4, 2019
a048c8d
Removed redundant libraries
Apr 4, 2019
012ffcb
Minor fixes, clean, opening result port init program
Apr 8, 2019
4280c9b
Score result added
Apr 8, 2019
99f5c48
removed resource finder to frozen_inference_graph.pb -> use path inst…
Apr 9, 2019
591d80c
OpenCV imshow removed
Apr 9, 2019
3205d84
Fix image detection BGR->RGB
Apr 10, 2019
5b69025
Description port added
Apr 11, 2019
132601b
Yarpmanager xml added
Apr 11, 2019
4eabe26
Use relative path to execute tensorflowDetection2D -> with installati…
Apr 11, 2019
7b47177
Relative path fixed
Apr 11, 2019
f3881d8
Fix format, now similar to haarDetection2D
Apr 26, 2019
b7bf5ab
Fix , improve speed change RT 20->100
Apr 26, 2019
8a88000
Fix format
Apr 29, 2019
2872773
Improve speed fix rt time
Apr 29, 2019
55256a4
tensorflowDetection2D models link added
Jul 2, 2019
54891dd
Readme moved
Jul 8, 2019
0cc064e
Fix port name
Jul 16, 2019
4d3b1f7
remove rgb intrinsic parameters
Jul 25, 2019
e148a95
.pbtxt removed from CMakeLists.txt
Jul 25, 2019
17fa21b
.pbtxt removed from PR
Jul 25, 2019
6ed8465
[README] Remove empty lines
jgvictores Jul 25, 2019
5d39a06
Some info added
Jul 26, 2019
41ba5e4
Picture added
Jul 26, 2019
bfa9fe9
Fix language
Jul 26, 2019
93450fc
Fix size
Jul 26, 2019
f742577
Fix size
Jul 26, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ find_package(COLOR_DEBUG REQUIRED)
# Soft dependencies.
find_package(OpenCV QUIET)
find_package(PCL 1.6 QUIET)
find_package(TensorflowCC 1.12 QUIET)

# Always build YARP devices as MODULE libraries.
set(YARP_FORCE_DYNAMIC_PLUGINS TRUE CACHE INTERNAL "Force dynamic plugins")
Expand Down
1 change: 1 addition & 0 deletions doc/vision-install.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- [Install YARP 2.3.70+ and OpenNI2DeviceServer](https://github.com/roboticslab-uc3m/installation-guides/blob/master/install-yarp.md)
- [Install OpenCV](https://github.com/roboticslab-uc3m/installation-guides/blob/master/install-opencv.md)
- [Install color-debug](https://github.com/roboticslab-uc3m/color-debug)
- [Install tensorflow_cc 1.12+](https://github.com/FloopCZ/tensorflow_cc)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done at 74eb52c.


### Install the Software on Ubuntu (working on all tested versions)

Expand Down
46 changes: 46 additions & 0 deletions programs/tensorflowDetection2D/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@

PeterBowman marked this conversation as resolved.
Show resolved Hide resolved
if(NOT OpenCV_FOUND AND (NOT DEFINED ENABLE_tensorflowDetection2D OR ENABLE_tensorflowDetection2D))
message(WARNING "OpenCV package not found, disabling tensorflowDetection2D program")
endif()

if(NOT TensorflowCC_FOUND AND (NOT DEFINED ENABLE_tensorflowDetection2D OR ENABLE_tensorflowDetection2D))
message(WARNING "TensorflowCC package not found, disabling tensorflowDetection2D program")
endif()

cmake_dependent_option(ENABLE_tensorflowDetection2D "Enable/disable tensorflowDetection2D program" ON
"OpenCV_FOUND;TensorflowCC_FOUND" OFF)


if(ENABLE_tensorflowDetection2D)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(tensorflowDetection2D main.cpp
TensorflowDetection2D.hpp
TensorflowDetection2D.cpp
TensorflowSessionTest.h
TensorflowSessionTest.cpp
TensorflowDetector.hpp
TensorflowDetector.cpp
MainDetector.hpp
MainDetector.cpp
)

target_link_libraries(tensorflowDetection2D YARP::YARP_OS
YARP::YARP_init
YARP::YARP_dev
YARP::YARP_sig
${OpenCV_LIBS}
TensorflowCC::Shared)


install(TARGETS tensorflowDetection2D
DESTINATION ${CMAKE_INSTALL_BINDIR})

else()

set(ENABLE_tensorflowDetection2D OFF CACHE BOOL "Enable/disable tensorflowDetection2D program" FORCE)

endif()
215 changes: 215 additions & 0 deletions programs/tensorflowDetection2D/MainDetector.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@

// Libraries

#include <fstream>
#include <utility>
#include <vector>
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <yarp/os/Bottle.h>
#include <yarp/os/BufferedPort.h>
#include <yarp/os/ConnectionReader.h>
#include <yarp/os/Port.h>
#include <yarp/os/PortReader.h>
#include <yarp/sig/Image.h>
#include <yarp/os/Time.h>
#include <opencv2/core/mat.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cv.hpp>
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "TensorflowDetector.hpp"
#include "MainDetector.hpp"
PeterBowman marked this conversation as resolved.
Show resolved Hide resolved
#include <map>


int maindetector::detect(std::string labels, std::string graph, std::string video_source, yarp::os::Port sender_port_pre, yarp::os::Port sender_port_post) {


std::system("clear");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we remove all the system calls?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course, it´s just to clean terminal.

Copy link
Author

@davidvelascogarcia davidvelascogarcia Apr 3, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

system calls removed at ce99c59 (with a fix opening BufferedPort at the start of the program. I forgot to separate in two commits, sorry)

std::cout<<std::endl;
std::cout<<std::endl;

// Path
std::string ROOTDIR = "../";
std::string LABELS = labels;
std::string GRAPH = graph;
std::string source_video=video_source;

// Set nombres nodos entrada y salida
tensorflow::string inputLayer = "image_tensor:0";
std::vector<std::string> outputLayer = {"detection_boxes:0", "detection_scores:0", "detection_classes:0", "num_detections:0"};

// Load .pb frozen model
std::unique_ptr<tensorflow::Session> session;
tensorflow::string graphPath = tensorflow::io::JoinPath(ROOTDIR, GRAPH);
std::cout<<"The graph it´s going to be loaded:" << graphPath<<"."<<std::endl;
std::cout<<"Loading graph..."<<std::endl;
yarp::os::Time::delay(1);
//LOG(INFO) << "Loading graph:" << graphPath<<" ...";

tensorflow::Status loadGraphStatus = loadGraph(graphPath, &session);
if (!loadGraphStatus.ok()) {
std::system("clear");
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Fail loading graph "<<graphPath<<"."<<std::endl;
//LOG(ERROR) << "Loading graph: FAIL" << loadGraphStatus;
yarp::os::Time::delay(1);
return -1;
} else
std::system("clear");
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Graph "<<graphPath<<" loaded correctly."<<std::endl;
//LOG(INFO) << "Loading graph: OK" << std::endl;
yarp::os::Time::delay(1);


// Cargar etiquetas
std::map<int, std::string> labelsMap = std::map<int,std::string>();
std::system("clear");
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Labels "<<LABELS<<" are going to be loaded."<<std::endl;
yarp::os::Time::delay(1);
tensorflow::Status readLabelsMapStatus = readLabelsMapFile(tensorflow::io::JoinPath(ROOTDIR, LABELS), labelsMap);
if (!readLabelsMapStatus.ok()) {
//LOG(ERROR) << "readLabelsMapFile(): ERROR" << loadGraphStatus;
std::cout<<"Fail loading labels "<<LABELS<<"."<<std::endl;
//LOG(INFO) << "Carga del graph: OK" << std::endl;
yarp::os::Time::delay(1);
return -1;
} else
//LOG(INFO) << "readLabelsMapFile(): labels map loaded with " << labelsMap.size() << " label(s)" << std::endl;
std::cout<<"Labels "<<LABELS<<" loaded correctly."<<std::endl;
std::cout<<labelsMap.size()<<" labels have been loaded."<<std::endl;
yarp::os::Time::delay(1);

std::system("clear");
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Video source frames are going to be taken."<<std::endl;
yarp::os::Time::delay(1);
cv::Mat frame;
tensorflow::Tensor tensor;
std::vector<tensorflow::Tensor> outputs;
double thresholdScore = 0.5;
double thresholdIOU = 0.8;

// Cuenta FPS
int nFrames = 25;
int iFrame = 0;
double fps = 0.;
time_t start, end;
time(&start);

// Adquiere imagen de la fuente de video
cv::VideoCapture cap(source_video);

tensorflow::TensorShape shape = tensorflow::TensorShape();
shape.AddDim(1);
shape.AddDim((tensorflow::int64)cap.get(cv::CAP_PROP_FRAME_HEIGHT));
shape.AddDim((tensorflow::int64)cap.get(cv::CAP_PROP_FRAME_WIDTH));
shape.AddDim(3);
std::system("clear");
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Taking frames..."<<std::endl;
yarp::os::Time::delay(1);
//tensorflowDetection2D yarp_sender;
while (cap.isOpened()) {
cap >> frame;

// Enviar imagen preprocesada por yarp
//yarp_sender.send_post(frame, puerto_pre);
// A mano
yarp::sig::ImageOf<yarp::sig::PixelBgr> B;
B.setExternal(frame.data,frame.size[1],frame.size[0]);
sender_port_pre.write(B);

cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
std::cout << "Frame: " << iFrame << std::endl;

if (nFrames % (iFrame + 1) == 0) {
time(&end);
fps = 1. * nFrames / difftime(end, start);
time(&start);
}
iFrame++;

// Pasar Mat a Tensor
tensor = tensorflow::Tensor(tensorflow::DT_FLOAT, shape);
tensorflow::Status readTensorStatus = readTensorFromMat(frame, tensor);
if (!readTensorStatus.ok()) {
//LOG(ERROR) << "Mat->Tensor conversion failed: " << readTensorStatus;
std::system("clear");
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Mat OpenCV -> Tensor : FAIL"<<std::endl;
yarp::os::Time::delay(1);
return -1;
}

// Ejecutar graph
outputs.clear();
tensorflow::Status runStatus = session->Run({{inputLayer, tensor}}, outputLayer, {}, &outputs);
if (!runStatus.ok()) {
//LOG(ERROR) << "Running model failed: " << runStatus;
std::system("clear");
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Running model status: FAIL"<<std::endl;
yarp::os::Time::delay(1);
return -1;
}

// Extraer resultados del vector
tensorflow::TTypes<float>::Flat scores = outputs[1].flat<float>();
tensorflow::TTypes<float>::Flat classes = outputs[2].flat<float>();
tensorflow::TTypes<float>::Flat numDetections = outputs[3].flat<float>();
tensorflow::TTypes<float, 3>::Tensor boxes = outputs[0].flat_outer_dims<float,3>();

std::vector<size_t> goodIdxs = filterBoxes(scores, boxes, thresholdIOU, thresholdScore);
for (size_t i = 0; i < goodIdxs.size(); i++){
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Detection: "<<labelsMap[classes(goodIdxs.at(i))]<< " -> Score: "<<scores(goodIdxs.at(i))<<std::endl;

/* LOG(INFO) << "score:" << scores(goodIdxs.at(i)) << ",class:" << labelsMap[classes(goodIdxs.at(i))]
<< " (" << classes(goodIdxs.at(i)) << "), box:" << "," << boxes(0, goodIdxs.at(i), 0) << ","
<< boxes(0, goodIdxs.at(i), 1) << "," << boxes(0, goodIdxs.at(i), 2) << ","
<< boxes(0, goodIdxs.at(i), 3);*/


std::cout<<std::endl;

cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
drawBoundingBoxesOnImage(frame, scores, classes, boxes, labelsMap, goodIdxs);

cv::putText(frame, std::to_string(fps).substr(0, 5), cv::Point(0, frame.rows), cv::FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(255, 255, 255));
//yarp_sender.send_post(frame, puerto_post);
// A mano
yarp::sig::ImageOf<yarp::sig::PixelBgr> C;
C.setExternal(frame.data,frame.size[1],frame.size[0]);
sender_port_post.write(C);
cv::imshow("Video source: Processed", frame);
cv::waitKey(5);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we remove all traces of OpenCV?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now, not all, i´m trying to remove OpenCV and use YARP instead, but cv::imshow it´s going to be removed. I´m using it for testing.

}}
cv::destroyAllWindows();

return 0;
}
42 changes: 42 additions & 0 deletions programs/tensorflowDetection2D/MainDetector.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#ifndef MAINDETECTOR_HPP
#define MAINDETECTOR_HPP

#include <fstream>
#include <utility>
#include <vector>
#include <iostream>
#include <time.h>
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
#include <yarp/os/Bottle.h>
#include <yarp/os/BufferedPort.h>
#include <yarp/os/ConnectionReader.h>
#include <yarp/os/Port.h>
#include <yarp/os/PortReader.h>
#include <yarp/sig/Image.h>
#include <yarp/os/Time.h>
#include <opencv2/core/mat.hpp>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also remove opencv headers if possible

#include <opencv2/videoio.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cv.hpp>
#include "TensorflowDetector.hpp"


class maindetector
{
public:
int detect(std::string labels, std::string graph, std::string video_source, yarp::os::Port sender_port_preyarp, yarp::os::Port sender_port_post);

};
#endif //MAINDETECTOR_HPP
Loading