Advertisement
Guest User

Untitled

a guest
Mar 11th, 2017
798
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.72 KB | None | 0 0
  1. /*****************************
  2. Copyright 2011 Rafael Muñoz Salinas. All rights reserved.
  3.  
  4. Redistribution and use in source and binary forms, with or without modification, are
  5. permitted provided that the following conditions are met:
  6.  
  7.    1. Redistributions of source code must retain the above copyright notice, this list of
  8.       conditions and the following disclaimer.
  9.  
  10.    2. Redistributions in binary form must reproduce the above copyright notice, this list
  11.       of conditions and the following disclaimer in the documentation and/or other materials
  12.       provided with the distribution.
  13.  
  14. THIS SOFTWARE IS PROVIDED BY Rafael Muñoz Salinas ''AS IS'' AND ANY EXPRESS OR IMPLIED
  15. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  16. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Rafael Muñoz Salinas OR
  17. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  18. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  19. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  20. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  22. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23.  
  24. The views and conclusions contained in the software and documentation are those of the
  25. authors and should not be interpreted as representing official policies, either expressed
  26. or implied, of Rafael Muñoz Salinas.
  27. ********************************/
  28.  
  29. #include <iostream>
  30.  
  31. #include "Ogre.h"
  32. #include <OIS/OIS.h>
  33.  
  34. #include "aruco/aruco.h"  
  35. #include "aruco/highlyreliablemarkers.h"
  36.  
  37. #include <opencv2/core/core.hpp>
  38. #include <opencv2/highgui/highgui.hpp>
  39. #include <opencv2/imgproc/imgproc.hpp>
  40.  
  41.  
  42. #define MAX_MARKERS 30 // maximun number of markers we assume they will be detected simultaneously
  43.  
  44. /// Ogre general variables
  45. Ogre::Root* root;
  46. OIS::InputManager* im;
  47. OIS::Keyboard* keyboard;
  48.  
  49. /// Ogre background variables
  50. Ogre::PixelBox mPixelBox;
  51. Ogre::TexturePtr mTexture;
  52.  
  53. /// Ogre scene variables
  54. Ogre::SceneNode* ogreNode[MAX_MARKERS];
  55. Ogre::AnimationState *baseAnim[MAX_MARKERS], *topAnim[MAX_MARKERS];
  56.  
  57. /// ArUco variables
  58. cv::VideoCapture TheVideoCapturer;
  59. cv::Mat TheInputImage, TheInputImageUnd;
  60. aruco::CameraParameters CameraParams, CameraParamsUnd;
  61. float TheMarkerSize=1;
  62. aruco::MarkerDetector TheMarkerDetector;
  63. std::vector<aruco::Marker> TheMarkers;
  64.  
  65. // ArUco Dictionaries
  66. aruco::Dictionary Dictionary;
  67.  
  68. int initOgreAR(aruco::CameraParameters camParams, unsigned char* buffer, std::string resourcePath="");
  69. bool readParameters(int argc, char** argv);
  70.  
  71. void usage()
  72. {
  73.     cout<<" This program test Ogre version of ArUco (single marker version) \n\n";
  74.     cout<<" Usage <video.avi>|live <camera.yml> <markersize>"<<endl;
  75.     cout<<" <video.avi>|live: specifies a input video file. Use 'live' to capture from camera"<<endl;
  76.     cout<<" <camera.yml>: camera calibration file"<<endl;
  77.     cout<<" <markersize>: in meters "<<endl;
  78. }
  79.  
  80.  /**
  81.   *
  82.   */
  83. int main(int argc, char** argv)
  84. {
  85.  
  86.       /// READ PARAMETERS
  87.       if(!readParameters(argc, argv))
  88.     return false;  
  89.  
  90.       /// CREATE UNDISTORTED CAMERA PARAMS
  91.       CameraParamsUnd=CameraParams;
  92.       CameraParamsUnd.Distorsion=cv::Mat::zeros(4,1,CV_32F);      
  93.      
  94.       /// CAPTURE FIRST FRAME
  95.       TheVideoCapturer.grab();
  96.       TheVideoCapturer.retrieve ( TheInputImage );
  97.       cv::undistort( TheInputImage, TheInputImageUnd, CameraParams.CameraMatrix, CameraParams.Distorsion);      
  98.      
  99.       // load dictionary
  100.       std::string dictionaryFile = "reduced-dict-plastic.yml";
  101.       if (Dictionary.fromFile(dictionaryFile) == false) {
  102.           cerr << "Could not open dictionary" << endl;
  103.           Sleep(2000);
  104.           return -1;
  105.       }
  106.       else{
  107.           cout << "Dictionary loaded" << endl;
  108.       }
  109.  
  110.       // load the dictionary to marker detector
  111.       aruco::HighlyReliableMarkers::loadDictionary(Dictionary);
  112.       // set detector params
  113.       TheMarkerDetector.setMakerDetectorFunction(aruco::HighlyReliableMarkers::detect);
  114.       TheMarkerDetector.setWarpSize((Dictionary[0].n() + 2) * 8);
  115.  
  116.       /// INIT OGRE
  117.       //initOgreAR(CameraParamsUnd, TheInputImageUnd.ptr<uchar>(0));
  118.       initOgreAR(CameraParamsUnd, TheInputImageUnd.ptr<uchar>(0));
  119.  
  120.       while (TheVideoCapturer.grab())
  121.       {
  122.           /// READ AND UNDISTORT IMAGE
  123.           TheVideoCapturer.retrieve ( TheInputImage );
  124.  
  125.           cv::undistort(TheInputImage,TheInputImageUnd,CameraParams.CameraMatrix,CameraParams.Distorsion);
  126.          
  127.           /// DETECT MARKERS
  128.           TheMarkerDetector.detect(TheInputImageUnd, TheMarkers, CameraParamsUnd, TheMarkerSize);
  129.          
  130.           /// UPDATE BACKGROUND IMAGE
  131.           mTexture->getBuffer()->blitFromMemory(mPixelBox);      
  132.          
  133.           /// UPDATE SCENE
  134.           int i;
  135.           double position[3], orientation[4];
  136.           //exit(11);
  137.           // show nodes for detected markers
  138.           for (i = 0; i < TheMarkers.size() && i < MAX_MARKERS; i++) {
  139.               TheMarkers[i].OgreGetPoseParameters(position, orientation);
  140.               ogreNode[i]->setPosition(position[0], position[1], position[2]);
  141.               ogreNode[i]->setOrientation(orientation[0], orientation[1], orientation[2], orientation[3]);
  142.               ogreNode[i]->setVisible(true);
  143.           }
  144.  
  145.           // hide rest of nodes
  146.           for( ; i<MAX_MARKERS; i++) ogreNode[i]->setVisible(false);
  147.  
  148.           // Update animation
  149.           double deltaTime = 1.2*root->getTimer()->getMilliseconds()/1000.;
  150.           for(int i=0; i<MAX_MARKERS; i++) {
  151.             baseAnim[i]->addTime(deltaTime);
  152.             topAnim[i]->addTime(deltaTime);
  153.           }
  154.           root->getTimer()->reset();
  155.      
  156.           /// RENDER FRAME
  157.           if(root->renderOneFrame() == false) break;
  158.           Ogre::WindowEventUtilities::messagePump();
  159.  
  160.           /// KEYBOARD INPUT
  161.           keyboard->capture();
  162.           if (keyboard->isKeyDown(OIS::KC_ESCAPE)) break;        
  163.          
  164.          
  165.       }
  166.  
  167.       im->destroyInputObject(keyboard);
  168.       im->destroyInputSystem(im);
  169.       im = 0;
  170.  
  171.       delete root;
  172.       return 0;
  173. }
  174.  
  175.  
  176.  /**
  177.   *
  178.   */
  179. bool readParameters(int argc, char** argv)
  180. {
  181.  
  182.     if (argc < 3) {
  183.         usage();
  184.         return false;
  185.     }
  186.  
  187.     // read input video  
  188.     //if (argv[1]=="live") TheVideoCapturer.open(0);
  189.     //else TheVideoCapturer.open(argv[1]);
  190.  
  191.     // read intrinsic file
  192.     try {
  193.         CameraParams.readFromXMLFile(argv[2]);
  194.     }
  195.     catch (std::exception &ex) {
  196.         cout << ex.what() << endl;
  197.         return false;
  198.     }
  199.  
  200.     TheVideoCapturer.open(0);
  201.     TheVideoCapturer.set(CV_CAP_PROP_FRAME_WIDTH, CameraParams.CamSize.width);
  202.     TheVideoCapturer.set(CV_CAP_PROP_FRAME_HEIGHT, CameraParams.CamSize.height);
  203.  
  204.  
  205.     if (!TheVideoCapturer.isOpened())
  206.     {
  207.         cerr << "Could not open video" << endl;
  208.         return false;
  209.     }
  210.  
  211.  
  212.     if (argc > 3) TheMarkerSize = atof(argv[3]);
  213.     else TheMarkerSize = 1.;
  214. }
  215.  
  216.  
  217.  
  218.   /**
  219.   *
  220.   */
  221. int initOgreAR(aruco::CameraParameters camParams, unsigned char* buffer, std::string resourcePath)
  222. {
  223.  
  224.     /// INIT OGRE FUNCTIONS
  225.     //root = new Ogre::Root(resourcePath + "plugins.cfg", resourcePath + "ogre.cfg");
  226.     root = new Ogre::Root();
  227.     if (!root->showConfigDialog()) return -1;
  228.     Ogre::SceneManager* smgr = root->createSceneManager(Ogre::ST_GENERIC);
  229.    
  230.    
  231.     /// CREATE WINDOW, CAMERA AND VIEWPORT
  232.         Ogre::RenderWindow* window = root->initialise(true);
  233.     Ogre::Camera *camera;
  234.     Ogre::SceneNode* cameraNode;
  235.     camera = smgr->createCamera("camera");
  236.     camera->setNearClipDistance(0.01f);
  237.     camera->setFarClipDistance(10.0f);
  238.     camera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
  239.     camera->setPosition(0, 0, 0);
  240.     camera->lookAt(0, 0, 1);
  241.     double pMatrix[16];
  242.     camParams.OgreGetProjectionMatrix(camParams.CamSize,camParams.CamSize, pMatrix, 0.05,10, false);
  243.     Ogre::Matrix4 PM(pMatrix[0], pMatrix[1], pMatrix[2] , pMatrix[3],
  244.             pMatrix[4], pMatrix[5], pMatrix[6] , pMatrix[7],
  245.             pMatrix[8], pMatrix[9], pMatrix[10], pMatrix[11],
  246.             pMatrix[12], pMatrix[13], pMatrix[14], pMatrix[15]);   
  247.     camera->setCustomProjectionMatrix(true, PM);
  248.     camera->setCustomViewMatrix(true, Ogre::Matrix4::IDENTITY);    
  249.     window->addViewport(camera);
  250.     cameraNode = smgr->getRootSceneNode()->createChildSceneNode("cameraNode");
  251.     cameraNode->attachObject(camera);
  252.        
  253.    
  254.     /// CREATE BACKGROUND FROM CAMERA IMAGE
  255.     int width = camParams.CamSize.width;
  256.     int height = camParams.CamSize.height;
  257.     // create background camera image
  258.     mPixelBox = Ogre::PixelBox(width, height, 1, Ogre::PF_R8G8B8, buffer);
  259.     // Create Texture
  260.     mTexture = Ogre::TextureManager::getSingleton().createManual("CameraTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
  261.               Ogre::TEX_TYPE_2D,width,height,0,Ogre::PF_R8G8B8,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);   
  262.  
  263.     //Create Camera Material
  264.     Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("CameraMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
  265.     Ogre::Technique *technique = material->createTechnique();
  266.     technique->createPass();
  267.     material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
  268.     material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
  269.     material->getTechnique(0)->getPass(0)->createTextureUnitState("CameraTexture");
  270.  
  271.     Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true);
  272.     rect->setCorners(-1.0, 1.0, 1.0, -1.0);
  273.     rect->setMaterial("CameraMaterial");
  274.  
  275.     // Render the background before everything else
  276.     rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND);
  277.  
  278.     // Hacky, but we need to set the bounding box to something big, use infinite AAB to always stay visible
  279.     Ogre::AxisAlignedBox aabInf;
  280.     aabInf.setInfinite();
  281.     rect->setBoundingBox(aabInf);
  282.  
  283.     // Attach background to the scene
  284.     Ogre::SceneNode* node = smgr->getRootSceneNode()->createChildSceneNode("Background");
  285.     node->attachObject(rect);      
  286.    
  287.    
  288.     /// CREATE SIMPLE OGRE SCENE
  289.     // add sinbad.mesh
  290.     Ogre::ResourceGroupManager::getSingleton().addResourceLocation("Sinbad.zip", "Zip", "Popular");
  291.     Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();  
  292.     for(int i=0; i<MAX_MARKERS; i++) {
  293.       Ogre::String entityName = "Marker_" + Ogre::StringConverter::toString(i);
  294.       Ogre::Entity* ogreEntity = smgr->createEntity(entityName, "Sinbad.mesh");
  295.       Ogre::Real offset = ogreEntity->getBoundingBox().getHalfSize().y;  
  296.       ogreNode[i] = smgr->getRootSceneNode()->createChildSceneNode();
  297.       // add entity to a child node to correct position (this way, entity axis is on feet of sinbad)
  298.       Ogre::SceneNode *ogreNodeChild = ogreNode[i]->createChildSceneNode();
  299.       ogreNodeChild->attachObject(ogreEntity);
  300.       // Sinbad is placed along Y axis, we need to rotate to put it along Z axis so it stands up over the marker
  301.       // first rotate along X axis, then add offset in Z dir so it is over the marker and not in the middle of it
  302.       ogreNodeChild->rotate(Ogre::Vector3(1,0,0), Ogre::Radian(Ogre::Degree(90))); 
  303.       ogreNodeChild->translate(0,0,offset,Ogre::Node::TS_PARENT);
  304.       // mesh is too big, rescale!
  305.       const float scale = 0.006675f;
  306.       ogreNode[i]->setScale(scale, scale, scale);    
  307.      
  308.         // Init animation
  309.       ogreEntity->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
  310.       baseAnim[i] = ogreEntity->getAnimationState("RunBase");
  311.       topAnim[i] = ogreEntity->getAnimationState("RunTop");
  312.       baseAnim[i]->setLoop(true);
  313.       topAnim[i]->setLoop(true);
  314.       baseAnim[i]->setEnabled(true);
  315.       topAnim[i]->setEnabled(true);  
  316.     }  
  317.    
  318.    
  319.     // setup some basic lighting for our scene
  320.     smgr->setAmbientLight(Ogre::ColourValue(1, 1, 1));
  321.  
  322.     /// KEYBOARD INPUT READING
  323.     size_t windowHnd = 0;
  324.     window->getCustomAttribute("WINDOW", &windowHnd);
  325.     im = OIS::InputManager::createInputSystem(windowHnd);
  326.     keyboard = static_cast<OIS::Keyboard*>(im->createInputObject(OIS::OISKeyboard, true));
  327.    
  328.     return 1;
  329. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement