Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.31 KB | None | 0 0
  1. cat aruco_test.cpp
  2. /**
  3. Copyright 2017 Rafael Muñoz Salinas. All rights reserved.
  4.  
  5. Redistribution and use in source and binary forms, with or without modification, are
  6. permitted provided that the following conditions are met:
  7.  
  8. 1. Redistributions of source code must retain the above copyright notice, this list of
  9. conditions and the following disclaimer.
  10.  
  11. 2. Redistributions in binary form must reproduce the above copyright notice, this list
  12. of conditions and the following disclaimer in the documentation and/or other materials
  13. provided with the distribution.
  14.  
  15. THIS SOFTWARE IS PROVIDED BY Rafael Muñoz Salinas ''AS IS'' AND ANY EXPRESS OR IMPLIED
  16. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Rafael Muñoz Salinas OR
  18. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  21. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  22. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  23. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24.  
  25. The views and conclusions contained in the software and documentation are those of the
  26. authors and should not be interpreted as representing official policies, either expressed
  27. or implied, of Rafael Muñoz Salinas.
  28. */
  29.  
  30. #include "aruco.h"
  31. #include "cvdrawingutils.h"
  32. #include <fstream>
  33. #include <iostream>
  34. #include <opencv2/highgui/highgui.hpp>
  35. #include <opencv2/imgproc/imgproc.hpp>
  36. #include <sstream>
  37. #include <string>
  38. #include <stdexcept>
  39. #if CV_MAJOR_VERSION >= 4
  40. #define CV_CAP_PROP_FRAME_COUNT cv::CAP_PROP_FRAME_COUNT
  41. #endif
  42. using namespace std;
  43. using namespace cv;
  44. using namespace aruco;
  45.  
  46. MarkerDetector MDetector;
  47. VideoCapture TheVideoCapturer;
  48. vector<Marker> TheMarkers;
  49. Mat TheInputImage,TheInputImageGrey, TheInputImageCopy;
  50. CameraParameters TheCameraParameters;
  51. void cvTackBarEvents(int pos, void*);
  52. string dictionaryString;
  53. int iDetectMode=0,iMinMarkerSize=0,iCorrectionRate=0,iShowAllCandidates=0,iEnclosed=0,iThreshold,iCornerMode,iDictionaryIndex,iTrack=0;
  54.  
  55. int waitTime = 0;
  56. bool showMennu=false,bPrintHelp=false,isVideo=false;
  57. class CmdLineParser{int argc;char** argv;public:CmdLineParser(int _argc, char** _argv): argc(_argc), argv(_argv){} bool operator[](string param) {int idx = -1; for (int i = 0; i < argc && idx == -1; i++)if (string(argv[i]) == param)idx = i;return (idx != -1);} string operator()(string param, string defvalue = "-1") {int idx = -1;for (int i = 0; i < argc && idx == -1; i++)if (string(argv[i]) == param)idx = i;if (idx == -1)return defvalue;else return (argv[idx + 1]);}};
  58. struct TimerAvrg{std::vector<double> times;size_t curr=0,n; std::chrono::high_resolution_clock::time_point begin,end; TimerAvrg(int _n=30){n=_n;times.reserve(n); }inline void start(){begin= std::chrono::high_resolution_clock::now(); }inline void stop(){end= std::chrono::high_resolution_clock::now();double duration=double(std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count())*1e-6;if ( times.size()<n) times.push_back(duration);else{ times[curr]=duration; curr++;if (curr>=times.size()) curr=0;}}double getAvrg(){double sum=0;for(auto t:times) sum+=t;return sum/double(times.size());}};
  59.  
  60. TimerAvrg Fps;
  61.  
  62. cv::Mat resize(const cv::Mat& in, cv::Size s){
  63. if(s.width==-1 || s.height==-1)return in;
  64. cv::Mat im2;
  65. cv::resize(in, im2, s);
  66. return im2;
  67. }
  68.  
  69.  
  70.  
  71. cv::Mat resize(const cv::Mat& in, int width)
  72. {
  73. if (in.size().width <= width)
  74. return in;
  75. float yf = float(width) / float(in.size().width);
  76. cv::Mat im2;
  77. cv::resize(in, im2, cv::Size(width, static_cast<int>(in.size().height * yf)));
  78. return im2;
  79. }
  80. cv::Mat resizeImage(cv::Mat &in,float resizeFactor){
  81. if (fabs(1-resizeFactor)<1e-3 )return in;
  82. float nc=float(in.cols)*resizeFactor;
  83. float nr=float(in.rows)*resizeFactor;
  84. cv::Mat imres;
  85. cv::resize(in,imres,cv::Size(nc,nr));
  86. cout<<"Imagesize="<<imres.size()<<endl;
  87. return imres;
  88. }
  89. /************************************
  90. *
  91. *
  92. *
  93. *
  94. ************************************/
  95. void setParamsFromGlobalVariables(aruco::MarkerDetector &md){
  96.  
  97.  
  98. md.setDetectionMode((DetectionMode)iDetectMode,float(iMinMarkerSize)/1000.);
  99. md.getParameters().setCornerRefinementMethod( (aruco::CornerRefinementMethod) iCornerMode);
  100.  
  101. md.getParameters().detectEnclosedMarkers(iEnclosed);
  102. md.getParameters().ThresHold=iThreshold;
  103. md.getParameters().trackingMinDetections=(iTrack?3:0);
  104. if ( aruco::Dictionary::getTypeFromString( md.getParameters().dictionary)!=Dictionary::CUSTOM)
  105. md.setDictionary((aruco::Dictionary::DICT_TYPES) iDictionaryIndex,float(iCorrectionRate)/10. ); // sets the dictionary to be employed (ARUCO,APRILTAGS,ARTOOLKIT,etc)
  106. }
  107.  
  108. void createMenu(){
  109. cv::createTrackbar("Dictionary", "menu", &iDictionaryIndex, 13, cvTackBarEvents);
  110. cv::createTrackbar("DetectMode", "menu", &iDetectMode, 2, cvTackBarEvents);
  111. cv::createTrackbar("CornerMode", "menu", &iCornerMode, 2, cvTackBarEvents);
  112. cv::createTrackbar("Track", "menu", &iTrack,1, cvTackBarEvents);
  113.  
  114. cv::createTrackbar("MinMarkerSize", "menu", &iMinMarkerSize, 1000, cvTackBarEvents);
  115. cv::createTrackbar("Threshold", "menu", &iThreshold, 40, cvTackBarEvents);
  116. cv::createTrackbar("ErrorRate", "menu", &iCorrectionRate, 10, cvTackBarEvents);
  117. cv::createTrackbar("Enclosed", "menu", &iEnclosed, 1, cvTackBarEvents);
  118. cv::createTrackbar("ShowAll", "menu", &iShowAllCandidates, 1, cvTackBarEvents);
  119. iThreshold=MDetector.getParameters().ThresHold;
  120. iCornerMode= MDetector.getParameters().cornerRefinementM;
  121. }
  122.  
  123. void putText(cv::Mat &im,string text,cv::Point p,float size){
  124. float fact=float(im.cols)/float(640);
  125. if (fact<1) fact=1;
  126.  
  127. cv::putText(im,text,p,FONT_HERSHEY_SIMPLEX, size,cv::Scalar(0,0,0),3*fact);
  128. cv::putText(im,text,p,FONT_HERSHEY_SIMPLEX, size,cv::Scalar(125,255,255),1*fact);
  129.  
  130. }
  131. void printHelp(cv::Mat &im)
  132. {
  133. float fs=float(im.cols)/float(1200);
  134.  
  135. putText(im,"'m': show/hide menu",cv::Point(10,fs*60),fs*0.5f);
  136. putText(im,"'s': start/stop video capture",cv::Point(10,fs*80),fs*0.5f);
  137. putText(im,"'w': write image to file",cv::Point(10,fs*100),fs*0.5f);
  138. putText(im,"'t': do a speed test",cv::Point(10,fs*120),fs*0.5f);
  139. putText(im,"'f': saves current configuration to file 'arucoConfig.yml'",cv::Point(10,fs*140),fs*0.5f);
  140. }
  141.  
  142. void printInfo(cv::Mat &im){
  143. float fs=float(im.cols)/float(1200);
  144. putText(im,"fps="+to_string(1./Fps.getAvrg()),cv::Point(10,fs*20),fs*0.5f);
  145. putText(im,"'h': show/hide help",cv::Point(10,fs*40),fs*0.5f);
  146. if(bPrintHelp) printHelp(im);
  147. }
  148.  
  149. void printMenuInfo(){
  150. cv::Mat image(200,400,CV_8UC3);
  151. image=cv::Scalar::all(255);
  152. string str="Dictionary="+aruco::Dictionary::getTypeString((aruco::Dictionary::DICT_TYPES) iDictionaryIndex) ;
  153.  
  154. cv::putText(image,str,cv::Size(10,20),FONT_HERSHEY_SIMPLEX, 0.35,cv::Scalar(0,0,0),1);
  155.  
  156. str="Detection Mode="+MarkerDetector::Params::toString(MDetector.getParameters().detectMode);
  157. cv::putText(image,str,cv::Size(10,40),FONT_HERSHEY_SIMPLEX, 0.35,cv::Scalar(0,0,0),1);
  158. str="Corner Mode="+MarkerDetector::Params::toString(MDetector.getParameters().cornerRefinementM);;
  159. cv::putText(image,str,cv::Size(10,60),FONT_HERSHEY_SIMPLEX, 0.35,cv::Scalar(0,0,0),1);
  160. cv::imshow("menu",image);
  161. }
  162.  
  163.  
  164. /************************************
  165. *
  166. *
  167. *
  168. *
  169. ************************************/
  170. cv::Size parseSize(const string &strsize ){
  171. if(strsize.size()==0)return cv::Size(-1,-1);
  172. cv::Size s;
  173. string ssaux=strsize;
  174. for(auto &c:ssaux){
  175. if(c==':'){
  176. c=' ';
  177. }
  178. }
  179. stringstream sstr;sstr<<ssaux;
  180. if( sstr>>s.width>>s.height)
  181. return s;
  182. return cv::Size(-1,-1);
  183.  
  184. }
  185. int main(int argc, char** argv)
  186. {
  187. try
  188. {
  189. CmdLineParser cml(argc, argv);
  190. if (argc < 2 || cml["-h"])
  191. {
  192. cerr << "Invalid number of arguments" << endl;
  193. cerr << "Usage: (in.avi|live[:camera_index(e.g 0 or 1)]) [-c camera_params.yml] [-s marker_size_in_meters] [-d "
  194. "dictionary:ALL_DICTS by default] [-h] [-ws w:h] [-skip frames]"
  195. << endl;
  196. cerr << "\tDictionaries: ";
  197. for (auto dict : aruco::Dictionary::getDicTypes())
  198. cerr << dict << " ";
  199. cerr << endl;
  200. cerr << "\t Instead of these, you can directly indicate the path to a file with your own generated "
  201. "dictionary"
  202. << endl;
  203. return false;
  204. }
  205.  
  206. /////////// PARSE ARGUMENTS
  207. string TheInputVideo = argv[1];
  208. // read camera parameters if passed
  209. if (cml["-c"])
  210. TheCameraParameters.readFromXMLFile(cml("-c"));
  211.  
  212. float TheMarkerSize = std::stof(cml("-s", "-1"));
  213. //resize factor
  214. float resizeFactor=stof(cml("-rf","1"));
  215.  
  216. iMinMarkerSize=stof(cml("-mms","0.0"));
  217.  
  218.  
  219. /////////// OPEN VIDEO
  220. // read from camera or from file
  221. if (TheInputVideo.find("live") != string::npos)
  222. {
  223. int vIdx = 0;
  224. // check if the :idx is here
  225. char cad[100];
  226. if (TheInputVideo.find(":") != string::npos)
  227. {
  228. std::replace(TheInputVideo.begin(), TheInputVideo.end(), ':', ' ');
  229. sscanf(TheInputVideo.c_str(), "%s %d", cad, &vIdx);
  230. }
  231. cout << "Opening camera index " << vIdx << endl;
  232. TheVideoCapturer.open(vIdx);
  233. waitTime = 10;
  234. isVideo=true;
  235. }
  236. else{
  237. TheVideoCapturer.open(TheInputVideo);
  238. if ( TheVideoCapturer.get(CV_CAP_PROP_FRAME_COUNT)>=2) isVideo=true;
  239. if(cml["-skip"])
  240. TheVideoCapturer.set(CV_CAP_PROP_POS_FRAMES,stoi(cml("-skip")));
  241.  
  242. }
  243. // check video is open
  244. if (!TheVideoCapturer.isOpened())
  245. throw std::runtime_error("Could not open video");
  246.  
  247.  
  248. //create windows
  249. if(cml["-fs"]){
  250. cv::namedWindow("in", cv::WINDOW_FULLSCREEN);
  251. cv::namedWindow("thres", cv::WINDOW_FULLSCREEN);
  252. }
  253. else if(cml["-ws"])
  254. {
  255. cv::namedWindow("in",cv::WINDOW_NORMAL);
  256. cv::Size s=parseSize(cml("-ws"));
  257. cv::resizeWindow("in",s.width,s.height);
  258. cv::namedWindow("thres",cv::WINDOW_NORMAL);
  259. resizeWindow("thres",s.width,s.height);
  260.  
  261. }
  262.  
  263. else {
  264. cv::namedWindow("in",cv::WINDOW_NORMAL);
  265. cv::resizeWindow("in",640,480);
  266. float w=std::min(int(1920),int(TheInputImage.cols));
  267. float f=w/float(TheInputImage.cols);
  268. resizeWindow("in",w,float(TheInputImage.rows)*f);
  269. }
  270.  
  271. ///// CONFIGURE DATA
  272. // read first image to get the dimensions
  273. TheVideoCapturer >> TheInputImage;
  274. if (TheCameraParameters.isValid())
  275. TheCameraParameters.resize(TheInputImage.size());
  276. dictionaryString=cml("-d", "ALL_DICTS");
  277. iDictionaryIndex=(uint64_t)aruco::Dictionary::getTypeFromString(dictionaryString);
  278. MDetector.setDictionary(dictionaryString,float(iCorrectionRate)/10. ); // sets the dictionary to be employed (ARUCO,APRILTAGS,ARTOOLKIT,etc)
  279. iThreshold=MDetector.getParameters().ThresHold;
  280. iCornerMode= MDetector.getParameters().cornerRefinementM;
  281.  
  282.  
  283. setParamsFromGlobalVariables(MDetector);
  284.  
  285.  
  286. // go!
  287. char key = 0;
  288. int index = 0,indexSave=0;
  289. // capture until press ESC or until the end of the video
  290.  
  291. do
  292. {
  293.  
  294. TheVideoCapturer.retrieve(TheInputImage);
  295. std::cout<<"Frame:"<<TheVideoCapturer.get(CV_CAP_PROP_POS_FRAMES)<<std::endl;
  296. TheInputImage=resizeImage(TheInputImage,resizeFactor);
  297. // copy image
  298. Fps.start();
  299. TheMarkers = MDetector.detect(TheInputImage, TheCameraParameters, TheMarkerSize);
  300. Fps.stop();
  301. // chekc the speed by calculating the mean speed of all iterations
  302. cout << "\rTime detection=" << Fps.getAvrg()*1000 << " milliseconds nmarkers=" << TheMarkers.size() <<" images resolution="<<TheInputImage.size() <<std::endl;
  303.  
  304. // print marker info and draw the markers in image
  305. TheInputImage.copyTo(TheInputImageCopy);
  306.  
  307. if (iShowAllCandidates){
  308. auto candidates=MDetector.getCandidates();
  309. for(auto cand:candidates)
  310. Marker(cand,-1).draw(TheInputImageCopy, Scalar(255, 0, 255));
  311. }
  312.  
  313. for (unsigned int i = 0; i < TheMarkers.size(); i++)
  314. {
  315. cout << TheMarkers[i] << endl;
  316. TheMarkers[i].draw(TheInputImageCopy, Scalar(0, 0, 255),2,true);
  317. }
  318.  
  319. // draw a 3d cube in each marker if there is 3d info
  320. if (TheCameraParameters.isValid() && TheMarkerSize > 0)
  321. for (unsigned int i = 0; i < TheMarkers.size(); i++)
  322. {
  323. CvDrawingUtils::draw3dCube(TheInputImageCopy, TheMarkers[i], TheCameraParameters);
  324. CvDrawingUtils::draw3dAxis(TheInputImageCopy, TheMarkers[i], TheCameraParameters);
  325. }
  326.  
  327. // DONE! Easy, right?
  328. // show input with augmented information and the thresholded image
  329. printInfo(TheInputImageCopy);
  330. if(showMennu)printMenuInfo();
  331.  
  332. cv::imshow("thres", resize(MDetector.getThresholdedImage(), 1024));
  333.  
  334. cv::imshow("in", TheInputImageCopy);
  335.  
  336. key = cv::waitKey(waitTime); // wait for key to be pressed
  337. if (key == 's')
  338. waitTime = waitTime == 0 ? 10 : 0;
  339. if (key == 'w'){//writes current input image
  340. string number=std::to_string(indexSave++);
  341. while(number.size()!=3)number="0"+number;
  342. string imname="arucoimage"+number+".png";
  343. cv::imwrite(imname,TheInputImageCopy);
  344. cout<<"saved "<<imname<<endl;
  345. imname="orgimage"+number+".png";
  346. cv::imwrite(imname,TheInputImage);
  347. cout<<"saved "<<imname<<endl;
  348. imname="thresimage"+number+".png";
  349. cv::imwrite(imname,MDetector.getThresholdedImage());
  350.  
  351. }
  352. if (key=='m') {
  353. if (showMennu) cv::destroyWindow("menu");
  354. else {
  355. cv::namedWindow("menu",cv::WINDOW_NORMAL);
  356. cv::resizeWindow("menu",640,480);
  357. createMenu();
  358. printMenuInfo();
  359. }
  360. showMennu=!showMennu;
  361. }
  362. if (key=='h')bPrintHelp=!bPrintHelp;
  363.  
  364. if (key=='t'){//run a deeper speed test
  365.  
  366. for(int t=0;t<30;t++){
  367. // Detection of markers in the image passed
  368. Fps.start();
  369. TheMarkers = MDetector.detect(TheInputImage, TheCameraParameters, TheMarkerSize);
  370. Fps.stop();
  371. // chekc the speed by calculating the mean speed of all iterations
  372. }
  373. printInfo(TheInputImageCopy);
  374. }
  375. if(key=='f'){
  376. cerr<<"Configuration saved to arucoConfig.yml"<<endl;
  377. MDetector.saveParamsToFile("arucoConfig.yml");
  378. }
  379. index++; // number of images captured
  380.  
  381. if (isVideo)
  382. if ( TheVideoCapturer.grab()==false) key=27;
  383. } while (key != 27 );
  384. }
  385. catch (std::exception& ex)
  386.  
  387. {
  388. cout << "Exception :" << ex.what() << endl;
  389. }
  390. }
  391.  
  392.  
  393. void cvTackBarEvents(int pos, void*)
  394. {
  395. (void)(pos);
  396.  
  397.  
  398. setParamsFromGlobalVariables(MDetector);
  399.  
  400. // recompute
  401. Fps.start();
  402. MDetector.detect(TheInputImage, TheMarkers, TheCameraParameters);
  403. Fps.stop();
  404. // chekc the speed by calculating the mean speed of all iterations
  405. TheInputImage.copyTo(TheInputImageCopy);
  406. if (iShowAllCandidates){
  407. auto candidates=MDetector.getCandidates();
  408. for(auto cand:candidates)
  409. Marker(cand,-1).draw(TheInputImageCopy, Scalar(255, 0, 255),1);
  410. }
  411.  
  412. for (unsigned int i = 0; i < TheMarkers.size(); i++){
  413. cout << TheMarkers[i] << endl;
  414. TheMarkers[i].draw(TheInputImageCopy, Scalar(0, 0, 255),2);
  415. }
  416.  
  417. // draw a 3d cube in each marker if there is 3d info
  418. if (TheCameraParameters.isValid())
  419. for (unsigned int i = 0; i < TheMarkers.size(); i++)
  420. CvDrawingUtils::draw3dCube(TheInputImageCopy, TheMarkers[i], TheCameraParameters);
  421. cv::putText(TheInputImageCopy,"fps="+to_string(1./Fps.getAvrg() ),cv::Point(10,20),FONT_HERSHEY_SIMPLEX, 0.5f,cv::Scalar(125,255,255),2);
  422.  
  423. cv::imshow("in", TheInputImageCopy );
  424. cv::imshow("thres", resize(MDetector.getThresholdedImage(), 1024));
  425. if(showMennu)printMenuInfo();
  426.  
  427. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement