<commit_before>/*
 * Copyright (c) 2017 Darren Smith
 *
 * wampcc is free software; you can redistribute it and/or modify
 * it under the terms of the MIT license. See LICENSE for details.
 */

#include "wampcc/kernel.h"

#include "wampcc/io_loop.h"
#include "wampcc/event_loop.h"
#include "wampcc/ssl.h"
#include "wampcc/platform.h"

#include "config.h"

#include <iostream>

namespace wampcc
{

const char* package_name() { return WAMPCC_PACKAGE_NAME; }
const char* package_version() { return WAMPCC_PACKAGE_VERSION; }
const char* package_string() { return WAMPCC_PACKAGE_STRING; }
int major_version() { return WAMPCC_MAJOR_VERSION; }
int minor_version() { return WAMPCC_MINOR_VERSION; }
int micro_version() { return WAMPCC_MICRO_VERSION; }

static const char* level_str(logger::Level l);

std::mutex logger::lockable_console::stream_mutex ;
logger::lockable_console logger::lockable_cout;

config::config()
  : socket_buffer_max_size_bytes(65536), socket_max_pending_write_bytes(65536),
    ssl(false)
{
}

/* Constructor */
kernel::kernel(config conf, logger nlog)
  : m_config(conf),
    __logger(nlog)
{
  // SSL initialisation can fail, so we start the loops only after it has been
  // set up
  if (conf.ssl.enable)
    m_ssl.reset(new ssl_context(__logger, conf.ssl));

  m_io_loop.reset(new io_loop(*this));
  m_evl.reset(new event_loop(this));
}

/* Destructor */
kernel::~kernel()
{
  /* stop IO loop first, which will include closing all outstanding socket
   * resources, and as that happens, events are pushed onto the event queue
   * which is still operational */
  m_io_loop->sync_stop();
  m_evl->sync_stop();
}

io_loop* kernel::get_io() { return m_io_loop.get(); }

event_loop* kernel::get_event_loop() { return m_evl.get(); }

ssl_context* kernel::get_ssl() { return m_ssl.get(); }

int logger::levels_upto(Level l)
{
  int r(0);
  for (int i = 1; i <= l; i <<= 1)
    r |= i;
  return r;
}

logger logger::stream(lockable_stream& ostr, int level_mask, bool inc_src)
{
  logger my_logger;

  my_logger.wants_level =
    [level_mask](logger::Level l) { return (l & level_mask) != 0; };

  my_logger.write = [&ostr, level_mask, inc_src](logger::Level level,
                                                 const std::string& msg,
                                                 const char* file, int ln) {
    std::ostringstream oss;
    oss << wampcc::local_timestamp()
        << wampcc::thread_id() << " "
        << level_str(level) << " "
    << msg;
    if (inc_src && file)
      oss << " (" << file << ":" << ln << ") ";

    ostr.lock();
     try {
       // std:endl should act directly on the stream object, so that stream can
       // detect it and trigger stream sync.
       ostr.stream() << oss.str() << std::endl;
     } catch (...) {}
    ostr.unlock();
  };

  return my_logger;
}

static const char* level_str(logger::Level l)
{
  switch (l) {
    case logger::eError:
      return "ERROR";
    case logger::eWarn:
      return " WARN";
    case logger::eInfo:
      return " INFO";
    case logger::eDebug:
      return "DEBUG";
    case logger::eTrace:
      return "TRACE";
  }

  return "UNKNOWN";
}

logger logger::nolog()
{
  logger my_logger;

  my_logger.wants_level = [](logger::Level) { return false; };

  my_logger.write = [](logger::Level, const std::string&, const char*, int) {};

  return my_logger;
}

std::ostream& logger::lockable_console::stream()
{
  return std::cout;
}

} // namespace wampcc
<commit_msg>fix log line format issue<commit_after>/*
 * Copyright (c) 2017 Darren Smith
 *
 * wampcc is free software; you can redistribute it and/or modify
 * it under the terms of the MIT license. See LICENSE for details.
 */

#include "wampcc/kernel.h"

#include "wampcc/io_loop.h"
#include "wampcc/event_loop.h"
#include "wampcc/ssl.h"
#include "wampcc/platform.h"

#include "config.h"

#include <iostream>

namespace wampcc
{

const char* package_name() { return WAMPCC_PACKAGE_NAME; }
const char* package_version() { return WAMPCC_PACKAGE_VERSION; }
const char* package_string() { return WAMPCC_PACKAGE_STRING; }
int major_version() { return WAMPCC_MAJOR_VERSION; }
int minor_version() { return WAMPCC_MINOR_VERSION; }
int micro_version() { return WAMPCC_MICRO_VERSION; }

static const char* level_str(logger::Level l);

std::mutex logger::lockable_console::stream_mutex ;
logger::lockable_console logger::lockable_cout;

config::config()
  : socket_buffer_max_size_bytes(65536), socket_max_pending_write_bytes(65536),
    ssl(false)
{
}

/* Constructor */
kernel::kernel(config conf, logger nlog)
  : m_config(conf),
    __logger(nlog)
{
  // SSL initialisation can fail, so we start the loops only after it has been
  // set up
  if (conf.ssl.enable)
    m_ssl.reset(new ssl_context(__logger, conf.ssl));

  m_io_loop.reset(new io_loop(*this));
  m_evl.reset(new event_loop(this));
}

/* Destructor */
kernel::~kernel()
{
  /* stop IO loop first, which will include closing all outstanding socket
   * resources, and as that happens, events are pushed onto the event queue
   * which is still operational */
  m_io_loop->sync_stop();
  m_evl->sync_stop();
}

io_loop* kernel::get_io() { return m_io_loop.get(); }

event_loop* kernel::get_event_loop() { return m_evl.get(); }

ssl_context* kernel::get_ssl() { return m_ssl.get(); }

int logger::levels_upto(Level l)
{
  int r(0);
  for (int i = 1; i <= l; i <<= 1)
    r |= i;
  return r;
}

logger logger::stream(lockable_stream& ostr, int level_mask, bool inc_src)
{
  logger my_logger;

  my_logger.wants_level =
    [level_mask](logger::Level l) { return (l & level_mask) != 0; };

  my_logger.write = [&ostr, level_mask, inc_src](logger::Level level,
                                                 const std::string& msg,
                                                 const char* file, int ln) {
    std::ostringstream oss;
    oss << wampcc::local_timestamp() << " "
        << wampcc::thread_id() << " "
        << level_str(level) << " "
    << msg;
    if (inc_src && file)
      oss << " (" << file << ":" << ln << ") ";

    ostr.lock();
     try {
       // std:endl should act directly on the stream object, so that stream can
       // detect it and trigger stream sync.
       ostr.stream() << oss.str() << std::endl;
     } catch (...) {}
    ostr.unlock();
  };

  return my_logger;
}

static const char* level_str(logger::Level l)
{
  switch (l) {
    case logger::eError:
      return "ERROR";
    case logger::eWarn:
      return " WARN";
    case logger::eInfo:
      return " INFO";
    case logger::eDebug:
      return "DEBUG";
    case logger::eTrace:
      return "TRACE";
  }

  return "UNKNOWN";
}

logger logger::nolog()
{
  logger my_logger;

  my_logger.wants_level = [](logger::Level) { return false; };

  my_logger.write = [](logger::Level, const std::string&, const char*, int) {};

  return my_logger;
}

std::ostream& logger::lockable_console::stream()
{
  return std::cout;
}

} // namespace wampcc
<|endoftext|>


<commit_before>#include "./nodes.h"
#include <QDebug>
#include <string>
#include <vector>
#include "./utils/persister.h"
#include "./importer.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./obb_node.h"
#include "./camera_node.h"
#include "./coordinate_system_node.h"

Nodes::Nodes()
{
  addNode(std::make_shared<CoordinateSystemNode>());
}

Nodes::~Nodes()
{
  qInfo() << "Destructor of Nodes";
}

std::vector<std::shared_ptr<LabelNode>> Nodes::getLabelNodes()
{
  std::vector<std::shared_ptr<LabelNode>> result;
  for (auto &node : nodes)
  {
    std::shared_ptr<LabelNode> labelNode =
        std::dynamic_pointer_cast<LabelNode>(node);
    if (labelNode.get())
      result.push_back(labelNode);
  }

  return result;
}

void Nodes::addNode(std::shared_ptr<Node> node)
{
  nodes.push_back(node);

  emit nodesChanged(node);
}

void Nodes::removeNode(std::shared_ptr<Node> node)
{
  nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
}

std::vector<std::shared_ptr<Node>> Nodes::getNodes()
{
  return nodes;
}

std::shared_ptr<CameraNode> Nodes::getCameraNode()
{
  return cameraNode;
}

void Nodes::addSceneNodesFrom(QUrl url)
{
  addSceneNodesFrom(url.path().toStdString());
}

void Nodes::addSceneNodesFrom(std::string filename)
{
  qDebug() << "Nodes::addSceneNodesFrom" << filename.c_str();
  auto loadedNodes =
      Persister::load<std::vector<std::shared_ptr<Node>>>(filename);

  for (auto &node : loadedNodes)
  {
    std::shared_ptr<CameraNode> camera =
        std::dynamic_pointer_cast<CameraNode>(node);
    if (camera.get())
      cameraNode = camera;

    addNode(node);
  }
}

void Nodes::importFrom(std::string filename)
{
  Importer importer;

  auto meshes = importer.importAll(filename);

  for (size_t i = 0; i < meshes.size(); ++i)
  {
    auto transformation = importer.getTransformationFor(filename, i);
    addNode(std::make_shared<MeshNode>(filename, i, meshes[i], transformation));
  }
}

void Nodes::importFrom(QUrl url)
{
  importFrom(url.path().toStdString());
}

void Nodes::render(Graphics::Gl *gl,
                   std::shared_ptr<Graphics::Managers> managers,
                   RenderData renderData)
{
  for (auto &node : nodes)
    node->render(gl, managers, renderData);

  if (showBoundingVolumes)
  {
    for (auto &node : obbNodes)
      node->render(gl, managers, renderData);
  }
}

void Nodes::renderLabels(Graphics::Gl *gl,
                         std::shared_ptr<Graphics::Managers> managers,
                         RenderData renderData)
{
  for (auto labelNode : getLabelNodes())
  {
    labelNode->renderLabelAndConnector(gl, managers, renderData);
  }
}

void Nodes::saveSceneTo(QUrl url)
{
  saveSceneTo(url.path().toStdString());
}

void Nodes::saveSceneTo(std::string filename)
{
  std::vector<std::shared_ptr<Node>> persistableNodes;
  for (auto node : nodes)
    if (node->isPersistable())
      persistableNodes.push_back(node);

  Persister::save(persistableNodes, filename);
}

void Nodes::clear()
{
  nodes.clear();
  obbNodes.clear();
}

void Nodes::toggleBoundingVolumes()
{
  showBoundingVolumes = !showBoundingVolumes;

  if (showBoundingVolumes)
  {
    obbNodes.clear();
    for (auto &node : nodes)
    {
      if (node->getObb().isInitialized())
      {
        obbNodes.push_back(std::make_shared<ObbNode>(node->getObb()));
      }
    }
  }
}

void Nodes::addForcesVisualizerNode(std::shared_ptr<Node> node)
{
  addNode(node);
  forcesVisualizerNode = node;
}

void Nodes::removeForcesVisualizerNode()
{
  removeNode(forcesVisualizerNode);
}

<commit_msg>Create default CameraNode in Nodes constructor.<commit_after>#include "./nodes.h"
#include <QDebug>
#include <string>
#include <vector>
#include "./utils/persister.h"
#include "./importer.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./obb_node.h"
#include "./camera_node.h"
#include "./coordinate_system_node.h"

Nodes::Nodes()
{
  addNode(std::make_shared<CoordinateSystemNode>());
  cameraNode = std::make_shared<CameraNode>();
  addNode(cameraNode);
}

Nodes::~Nodes()
{
  qInfo() << "Destructor of Nodes";
}

std::vector<std::shared_ptr<LabelNode>> Nodes::getLabelNodes()
{
  std::vector<std::shared_ptr<LabelNode>> result;
  for (auto &node : nodes)
  {
    std::shared_ptr<LabelNode> labelNode =
        std::dynamic_pointer_cast<LabelNode>(node);
    if (labelNode.get())
      result.push_back(labelNode);
  }

  return result;
}

void Nodes::addNode(std::shared_ptr<Node> node)
{
  nodes.push_back(node);

  emit nodesChanged(node);
}

void Nodes::removeNode(std::shared_ptr<Node> node)
{
  nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
}

std::vector<std::shared_ptr<Node>> Nodes::getNodes()
{
  return nodes;
}

std::shared_ptr<CameraNode> Nodes::getCameraNode()
{
  return cameraNode;
}

void Nodes::addSceneNodesFrom(QUrl url)
{
  addSceneNodesFrom(url.path().toStdString());
}

void Nodes::addSceneNodesFrom(std::string filename)
{
  qDebug() << "Nodes::addSceneNodesFrom" << filename.c_str();
  auto loadedNodes =
      Persister::load<std::vector<std::shared_ptr<Node>>>(filename);

  for (auto &node : loadedNodes)
  {
    std::shared_ptr<CameraNode> camera =
        std::dynamic_pointer_cast<CameraNode>(node);
    if (camera.get())
      cameraNode = camera;

    addNode(node);
  }
}

void Nodes::importFrom(std::string filename)
{
  Importer importer;

  auto meshes = importer.importAll(filename);

  for (size_t i = 0; i < meshes.size(); ++i)
  {
    auto transformation = importer.getTransformationFor(filename, i);
    addNode(std::make_shared<MeshNode>(filename, i, meshes[i], transformation));
  }
}

void Nodes::importFrom(QUrl url)
{
  importFrom(url.path().toStdString());
}

void Nodes::render(Graphics::Gl *gl,
                   std::shared_ptr<Graphics::Managers> managers,
                   RenderData renderData)
{
  for (auto &node : nodes)
    node->render(gl, managers, renderData);

  if (showBoundingVolumes)
  {
    for (auto &node : obbNodes)
      node->render(gl, managers, renderData);
  }
}

void Nodes::renderLabels(Graphics::Gl *gl,
                         std::shared_ptr<Graphics::Managers> managers,
                         RenderData renderData)
{
  for (auto labelNode : getLabelNodes())
  {
    labelNode->renderLabelAndConnector(gl, managers, renderData);
  }
}

void Nodes::saveSceneTo(QUrl url)
{
  saveSceneTo(url.path().toStdString());
}

void Nodes::saveSceneTo(std::string filename)
{
  std::vector<std::shared_ptr<Node>> persistableNodes;
  for (auto node : nodes)
    if (node->isPersistable())
      persistableNodes.push_back(node);

  Persister::save(persistableNodes, filename);
}

void Nodes::clear()
{
  nodes.clear();
  obbNodes.clear();
}

void Nodes::toggleBoundingVolumes()
{
  showBoundingVolumes = !showBoundingVolumes;

  if (showBoundingVolumes)
  {
    obbNodes.clear();
    for (auto &node : nodes)
    {
      if (node->getObb().isInitialized())
      {
        obbNodes.push_back(std::make_shared<ObbNode>(node->getObb()));
      }
    }
  }
}

void Nodes::addForcesVisualizerNode(std::shared_ptr<Node> node)
{
  addNode(node);
  forcesVisualizerNode = node;
}

void Nodes::removeForcesVisualizerNode()
{
  removeNode(forcesVisualizerNode);
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkObjectMorphologyImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <stdlib.h>
#include <time.h>

#include <itkImage.h>
#include <itkIndex.h>
#include "itkDilateObjectMorphologyImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkErodeObjectMorphologyImageFilter.h"
#include <itkBinaryBallStructuringElement.h>
#include <itkImageRegionIterator.h>
#include <itkExceptionObject.h>

int itkObjectMorphologyImageFilterTest(int, char* [] )
{
  // Define the dimension of the images
  const unsigned int myDimension = 3;

  // Define the values of the input images
  const unsigned short fgValue = 1;
  const unsigned short bgValue = 0;

  // Declare the types of the images
  typedef itk::Image<unsigned short, myDimension>  myImageType;

  // Declare the type of the index to access images
  typedef itk::Index<myDimension>         myIndexType;

  // Declare the type of the size
  typedef itk::Size<myDimension>          mySizeType;

  // Declare the type of the Region
  typedef itk::ImageRegion<myDimension>        myRegionType;

  // Create an image
  myImageType::Pointer inputImage  = myImageType::New();

  // Define their size, and start index
  mySizeType size;
  size[0] = 20;
  size[1] = 20;
  size[2] = 20;

  myIndexType index;
  index[0] = 0;
  index[1] = 0;
  index[2] = 0;

  myRegionType region;
  region.SetIndex( index );
  region.SetSize( size );

  // Initialize Image
  inputImage->SetRegions( region );
  inputImage->Allocate();

  // Declare Iterator types apropriated for each image
  typedef itk::ImageRegionIterator<myImageType>  myIteratorType;

  // Initialize the content of Image
  inputImage->FillBuffer(bgValue);

  myImageType::IndexType ind;
  ind[0] = 10;
  ind[1] = 10;
  ind[2] = 10;
  inputImage->SetPixel(ind, fgValue);
  ind[0] = 2;
  ind[1] = 2;
  ind[2] = 8;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 9;
  ind[1] = 10;
  ind[2] = 5;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 9;
  ind[1] = 0;
  ind[2] = 15;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 9;
  ind[1] = 9;
  ind[2] = 7;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 0;
  ind[1] = 4;
  ind[2] = 17;
  inputImage->SetPixel(ind, fgValue);

  // Declare the type for the structuring element
  typedef itk::BinaryBallStructuringElement<unsigned short, myDimension>
    myKernelType;

  // Declare the type for the morphology Filter
  typedef itk::DilateObjectMorphologyImageFilter<myImageType, myImageType,
                                                 myKernelType>
    myDilateFilterType;
  typedef itk::BinaryDilateImageFilter<myImageType, myImageType,
                                                 myKernelType>
    binDilateFilterType;

  typedef itk::ErodeObjectMorphologyImageFilter<myImageType, myImageType,
                                                 myKernelType>
    myErodeFilterType;

  typedef itk::BinaryErodeImageFilter<myImageType, myImageType,
                                                 myKernelType>
    binErodeFilterType;

  // Create the filter
  myDilateFilterType::Pointer dilateFilter = myDilateFilterType::New();
  myErodeFilterType::Pointer erodeFilter = myErodeFilterType::New();
  binDilateFilterType::Pointer binDilateFilter = binDilateFilterType::New();
  binErodeFilterType::Pointer binErodeFilter = binErodeFilterType::New();

  // Create the structuring element
  myKernelType ball;
  myKernelType::SizeType ballSize;
  ballSize[0] = 5;
  ballSize[1] = 4;
  ballSize[2] = 3;
  ball.SetRadius(ballSize);
  ball.CreateStructuringElement();

  // Connect the input image
  dilateFilter->SetInput( inputImage );
  dilateFilter->SetKernel( ball );
  dilateFilter->SetObjectValue( fgValue );
  myImageType::Pointer outputImage = dilateFilter->GetOutput();

  clock_t start, end;
  double elapsedTime;

  // Execute the filter
  try
    {
    std::cout << "Object Dilate..." << std::endl;
    start = clock();
    dilateFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during dilate filter Update\n"  << e;
    return -1;
    }

  binDilateFilter->SetInput( inputImage );
  binDilateFilter->SetKernel( ball );
  binDilateFilter->SetDilateValue( fgValue );
  myImageType::Pointer outputBinImage = binDilateFilter->GetOutput();
  try
    {
    std::cout << "Binary Dilate..." << std::endl;

    start = clock();
    binDilateFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during dilate filter Update\n"  << e;
    return -1;
    }

  // Create an iterator for going through the image output
  myIteratorType itObj(outputImage, outputImage->GetBufferedRegion());
  myIteratorType itBin(outputBinImage, outputBinImage->GetBufferedRegion());
  std::cout << "Test for Dilate equality..." << std::endl;
  start = clock();
  itObj.GoToBegin();
  itBin.GoToBegin();
  int count = 0;
  while( !itObj.IsAtEnd() && !itBin.IsAtEnd() )
    {
    if(itObj.Get() != itBin.Get())
      {
      std::cerr << "Error: Dilated images differ!" << std::endl;
      std::cerr << "   Slice = " << count/(size[1]*size[0]) << std::endl;
      int x, y;
      itk::Index<3> i;
      i[2] = count/(size[1]*size[0]);
      for(y=0; y<size[1]; y++)
        {
        i[1] = y;
        for(x=0; x<size[0]; x++)
          {
          i[0] = x;
          std::cerr << outputImage->GetPixel(i)
                    << outputBinImage->GetPixel(i) << " ";
          }
        std::cerr << std::endl;
        }
      return -1;
      }
    ++itObj;
    ++itBin;
    ++count;
    }
  end = clock();
  elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
  std::cout << "  Success: " << std::endl;
  std::cout << "    Time = " << elapsedTime << std::endl;

  ballSize[0] = 2;
  ballSize[1] = 2;
  ballSize[2] = 2;
  ball.SetRadius(ballSize);
  ball.CreateStructuringElement();

  // Connect the input image
  erodeFilter->SetInput( outputImage );
  erodeFilter->SetKernel( ball );
  erodeFilter->SetObjectValue( fgValue );
  erodeFilter->SetBackgroundValue( bgValue );
  myImageType::Pointer output2Image = erodeFilter->GetOutput();

  // Execute the filter
  try
    {
    std::cout << "Object Erode..." << std::endl;
    start = clock();
    erodeFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during erode filter Update\n"  << e;
    return -1;
    }

  binErodeFilter->SetInput( outputImage );
  binErodeFilter->SetKernel( ball );
  binErodeFilter->SetErodeValue( fgValue );
  myImageType::Pointer outputBin2Image = binErodeFilter->GetOutput();

  // Execute the filter
  try
    {
    std::cout << "Binary Erode..." << std::endl;
    start = clock();
    binErodeFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during erode filter Update\n"  << e;
    return -1;
    }

  // Create an iterator for going through the image output
  myIteratorType it2Obj(output2Image, output2Image->GetBufferedRegion());
  myIteratorType it2Bin(outputBin2Image, outputBin2Image->GetBufferedRegion());
  std::cout << "Test for Erode equality..." << std::endl;
  start = clock();
  count = 0;
  while( !it2Obj.IsAtEnd() )
    {
    if(it2Obj.Get() != it2Bin.Get())
      {
      std::cout << "As expected: Error: Eroded images differ!" << std::endl;
      std::cout << "  Please see documentation - ErodeObject and BinaryErode";
      std::cout << std::endl << "    produce different results" << std::endl;
      std::cout << "   Slice = " << count/(size[1]*size[0]) << std::endl;
      int x, y;
      itk::Index<3> i;
      i[2] = count/(size[1]*size[0]);
      for(y=0; y<size[1]; y++)
        {
        i[1] = y;
        for(x=0; x<size[0]; x++)
          {
          i[0] = x;
          std::cout << output2Image->GetPixel(i)
                    << outputBin2Image->GetPixel(i) << " ";
          }
        std::cout << std::endl;
        }
      break;
      }
    ++it2Obj;
    ++it2Bin;
    ++count;
    }
  end = clock();
  elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
  std::cout << "  Success: " << std::endl;
  std::cout << "    Time = " << elapsedTime << std::endl;

  // All objects should be automatically destroyed at this point
  return 0;

}

<commit_msg>FIX: Resolved signed/unsigned warnings<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkObjectMorphologyImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <stdlib.h>
#include <time.h>

#include <itkImage.h>
#include <itkIndex.h>
#include "itkDilateObjectMorphologyImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkErodeObjectMorphologyImageFilter.h"
#include <itkBinaryBallStructuringElement.h>
#include <itkImageRegionIterator.h>
#include <itkExceptionObject.h>

int itkObjectMorphologyImageFilterTest(int, char* [] )
{
  // Define the dimension of the images
  const unsigned int myDimension = 3;

  // Define the values of the input images
  const unsigned short fgValue = 1;
  const unsigned short bgValue = 0;

  // Declare the types of the images
  typedef itk::Image<unsigned short, myDimension>  myImageType;

  // Declare the type of the index to access images
  typedef itk::Index<myDimension>         myIndexType;

  // Declare the type of the size
  typedef itk::Size<myDimension>          mySizeType;

  // Declare the type of the Region
  typedef itk::ImageRegion<myDimension>        myRegionType;

  // Create an image
  myImageType::Pointer inputImage  = myImageType::New();

  // Define their size, and start index
  mySizeType size;
  size[0] = 20;
  size[1] = 20;
  size[2] = 20;

  myIndexType index;
  index[0] = 0;
  index[1] = 0;
  index[2] = 0;

  myRegionType region;
  region.SetIndex( index );
  region.SetSize( size );

  // Initialize Image
  inputImage->SetRegions( region );
  inputImage->Allocate();

  // Declare Iterator types apropriated for each image
  typedef itk::ImageRegionIterator<myImageType>  myIteratorType;

  // Initialize the content of Image
  inputImage->FillBuffer(bgValue);

  myImageType::IndexType ind;
  ind[0] = 10;
  ind[1] = 10;
  ind[2] = 10;
  inputImage->SetPixel(ind, fgValue);
  ind[0] = 2;
  ind[1] = 2;
  ind[2] = 8;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 9;
  ind[1] = 10;
  ind[2] = 5;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 9;
  ind[1] = 0;
  ind[2] = 15;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 9;
  ind[1] = 9;
  ind[2] = 7;
  inputImage->SetPixel(ind, fgValue);

  ind[0] = 0;
  ind[1] = 4;
  ind[2] = 17;
  inputImage->SetPixel(ind, fgValue);

  // Declare the type for the structuring element
  typedef itk::BinaryBallStructuringElement<unsigned short, myDimension>
    myKernelType;

  // Declare the type for the morphology Filter
  typedef itk::DilateObjectMorphologyImageFilter<myImageType, myImageType,
                                                 myKernelType>
    myDilateFilterType;
  typedef itk::BinaryDilateImageFilter<myImageType, myImageType,
                                                 myKernelType>
    binDilateFilterType;

  typedef itk::ErodeObjectMorphologyImageFilter<myImageType, myImageType,
                                                 myKernelType>
    myErodeFilterType;

  typedef itk::BinaryErodeImageFilter<myImageType, myImageType,
                                                 myKernelType>
    binErodeFilterType;

  // Create the filter
  myDilateFilterType::Pointer dilateFilter = myDilateFilterType::New();
  myErodeFilterType::Pointer erodeFilter = myErodeFilterType::New();
  binDilateFilterType::Pointer binDilateFilter = binDilateFilterType::New();
  binErodeFilterType::Pointer binErodeFilter = binErodeFilterType::New();

  // Create the structuring element
  myKernelType ball;
  myKernelType::SizeType ballSize;
  ballSize[0] = 5;
  ballSize[1] = 4;
  ballSize[2] = 3;
  ball.SetRadius(ballSize);
  ball.CreateStructuringElement();

  // Connect the input image
  dilateFilter->SetInput( inputImage );
  dilateFilter->SetKernel( ball );
  dilateFilter->SetObjectValue( fgValue );
  myImageType::Pointer outputImage = dilateFilter->GetOutput();

  clock_t start, end;
  double elapsedTime;

  // Execute the filter
  try
    {
    std::cout << "Object Dilate..." << std::endl;
    start = clock();
    dilateFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during dilate filter Update\n"  << e;
    return -1;
    }

  binDilateFilter->SetInput( inputImage );
  binDilateFilter->SetKernel( ball );
  binDilateFilter->SetDilateValue( fgValue );
  myImageType::Pointer outputBinImage = binDilateFilter->GetOutput();
  try
    {
    std::cout << "Binary Dilate..." << std::endl;

    start = clock();
    binDilateFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during dilate filter Update\n"  << e;
    return -1;
    }

  // Create an iterator for going through the image output
  myIteratorType itObj(outputImage, outputImage->GetBufferedRegion());
  myIteratorType itBin(outputBinImage, outputBinImage->GetBufferedRegion());
  std::cout << "Test for Dilate equality..." << std::endl;
  start = clock();
  itObj.GoToBegin();
  itBin.GoToBegin();
  int count = 0;
  while( !itObj.IsAtEnd() && !itBin.IsAtEnd() )
    {
    if(itObj.Get() != itBin.Get())
      {
      std::cerr << "Error: Dilated images differ!" << std::endl;
      std::cerr << "   Slice = " << count/(size[1]*size[0]) << std::endl;
      unsigned int x, y;
      itk::Index<3> i;
      i[2] = count/(size[1]*size[0]);
      for(y=0; y<size[1]; y++)
        {
        i[1] = y;
        for(x=0; x<size[0]; x++)
          {
          i[0] = x;
          std::cerr << outputImage->GetPixel(i)
                    << outputBinImage->GetPixel(i) << " ";
          }
        std::cerr << std::endl;
        }
      return -1;
      }
    ++itObj;
    ++itBin;
    ++count;
    }
  end = clock();
  elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
  std::cout << "  Success: " << std::endl;
  std::cout << "    Time = " << elapsedTime << std::endl;

  ballSize[0] = 2;
  ballSize[1] = 2;
  ballSize[2] = 2;
  ball.SetRadius(ballSize);
  ball.CreateStructuringElement();

  // Connect the input image
  erodeFilter->SetInput( outputImage );
  erodeFilter->SetKernel( ball );
  erodeFilter->SetObjectValue( fgValue );
  erodeFilter->SetBackgroundValue( bgValue );
  myImageType::Pointer output2Image = erodeFilter->GetOutput();

  // Execute the filter
  try
    {
    std::cout << "Object Erode..." << std::endl;
    start = clock();
    erodeFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during erode filter Update\n"  << e;
    return -1;
    }

  binErodeFilter->SetInput( outputImage );
  binErodeFilter->SetKernel( ball );
  binErodeFilter->SetErodeValue( fgValue );
  myImageType::Pointer outputBin2Image = binErodeFilter->GetOutput();

  // Execute the filter
  try
    {
    std::cout << "Binary Erode..." << std::endl;
    start = clock();
    binErodeFilter->Update();
    end = clock();

    elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;

    //  Print the content of the result image
    std::cout << "  Success: " << std::endl;
    std::cout << "    Time = " << elapsedTime << std::endl;
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception caught during erode filter Update\n"  << e;
    return -1;
    }

  // Create an iterator for going through the image output
  myIteratorType it2Obj(output2Image, output2Image->GetBufferedRegion());
  myIteratorType it2Bin(outputBin2Image, outputBin2Image->GetBufferedRegion());
  std::cout << "Test for Erode equality..." << std::endl;
  start = clock();
  count = 0;
  while( !it2Obj.IsAtEnd() )
    {
    if(it2Obj.Get() != it2Bin.Get())
      {
      std::cout << "As expected: Error: Eroded images differ!" << std::endl;
      std::cout << "  Please see documentation - ErodeObject and BinaryErode";
      std::cout << std::endl << "    produce different results" << std::endl;
      std::cout << "   Slice = " << count/(size[1]*size[0]) << std::endl;
      unsigned int x, y;
      itk::Index<3> i;
      i[2] = count/(size[1]*size[0]);
      for(y=0; y<size[1]; y++)
        {
        i[1] = y;
        for(x=0; x<size[0]; x++)
          {
          i[0] = x;
          std::cout << output2Image->GetPixel(i)
                    << outputBin2Image->GetPixel(i) << " ";
          }
        std::cout << std::endl;
        }
      break;
      }
    ++it2Obj;
    ++it2Bin;
    ++count;
    }
  end = clock();
  elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
  std::cout << "  Success: " << std::endl;
  std::cout << "    Time = " << elapsedTime << std::endl;

  // All objects should be automatically destroyed at this point
  return 0;

}

<|endoftext|>


<commit_before>/*
 * IceWM
 *
 * Copyright (C) 1999-2002 Marko Macek
 */
#include "config.h"

#ifndef NO_CONFIGURE_MENUS
#include "objmenu.h"
#endif

#ifdef CONFIG_TASKBAR
#include "objbar.h"
#include "objbutton.h"
#include "ybutton.h"
#include "prefs.h"
#include "wmtaskbar.h"
#include "wmapp.h"
#include "wpixmaps.h"
#include "yrect.h"
#include "yicon.h"

YColor * ObjectBar::bgColor(NULL);

ref<YFont> ObjectButton::font;
YColor * ObjectButton::bgColor(NULL);
YColor * ObjectButton::fgColor(NULL);

ObjectBar::ObjectBar(YWindow *parent): YWindow(parent) {
    if (bgColor == 0)
        bgColor = new YColor(clrDefaultTaskBar);
    setSize(1, 1);
}

ObjectBar::~ObjectBar() {
}

void ObjectBar::addButton(const ustring &name, ref<YIcon> icon, YButton *button) {
    button->setToolTip(name);
#ifndef LITE
    if (icon != null) {
        button->setIcon(icon, YIcon::smallSize());
        button->setSize(button->width() + 4, button->width() + 4);
    } else
#endif
        button->setText(name);

    button->setPosition(width(), 0);
    int h = button->height();
    if (h < height())
        h = height();

    if (h < height())
        h = height();

    button->setSize(button->width(), h);
    setSize(width() + button->width(), h);
    button->show();

    objects.append(button);
}

void ObjectBar::paint(Graphics &g, const YRect &/*r*/) {
#ifdef CONFIG_GRADIENTS
    ref<YImage> gradient(parent()->getGradient());

    if (gradient != null)
        g.drawImage(gradient, this->x(), this->y(), width(), height(), 0, 0);
    else
#endif
        if (taskbackPixmap != null)
            g.fillPixmap(taskbackPixmap, 0, 0, width(), height());
        else {
            g.setColor(bgColor);
            g.fillRect(0, 0, width(), height());
        }
}

void ObjectBar::addObject(DObject *object) {
    YButton *button = new ObjectButton(this, object);
    addButton(object->getName(), object->getIcon(), button);
}

void ObjectBar::addSeparator() {
    setSize(width() + 4, height());
    objects.append(0);
}

void ObjectBar::addContainer(const ustring &name, ref<YIcon> icon, ObjectContainer *container) {
    if (container) {
        YButton *button = new ObjectButton(this, (YMenu*) container);
        addButton(name, icon, button);
    }
}

void ObjectBar::configure(const YRect &r) {
    YWindow::configure(r);

    int left = 0;
    for (int i = 0; i < objects.getCount(); i++) {
        YButton *obj = objects[i];
        if (obj) {
            obj->setGeometry(YRect(left, 0, obj->width(), height()));
            left += obj->width();
        } else
            left += 4;
    }
}

ref<YFont> ObjectButton::getFont() {
    return font != null ? font : font =
        (*toolButtonFontName ? YFont::getFont(XFA(toolButtonFontName))
         : YButton::getFont());
}

YColor * ObjectButton::getColor() {
    return *clrToolButtonText
        ? fgColor ? fgColor : fgColor = new YColor(clrToolButtonText)
        : YButton::getColor();
}

YSurface ObjectButton::getSurface() {
    if (bgColor == 0)
        bgColor = new YColor(*clrToolButton ? clrToolButton : clrNormalButton);

#ifdef CONFIG_GRADIENTS
    return YSurface(bgColor, toolbuttonPixmap, toolbuttonPixbuf);
#else
    return YSurface(bgColor, toolbuttonPixmap);
#endif
}

void ObjectButton::actionPerformed(YAction * action, unsigned modifiers) {
#ifdef CONFIG_GUIEVENTS
    wmapp->signalGuiEvent(geLaunchApp);
#endif
    if (fObject) fObject->open();
    else YButton::actionPerformed(action, modifiers);
}

#endif /* CONFIG_TASKBAR */

#ifndef NO_CONFIGURE_MENUS
ObjectMenu *rootMenu(NULL);
#endif
<commit_msg>use getTaskBarBg().<commit_after>/*
 * IceWM
 *
 * Copyright (C) 1999-2002 Marko Macek
 */
#include "config.h"

#ifndef NO_CONFIGURE_MENUS
#include "objmenu.h"
#endif

#ifdef CONFIG_TASKBAR
#include "objbar.h"
#include "objbutton.h"
#include "ybutton.h"
#include "prefs.h"
#include "wmtaskbar.h"
#include "wmapp.h"
#include "wpixmaps.h"
#include "yrect.h"
#include "yicon.h"

ref<YFont> ObjectButton::font;
YColor * ObjectButton::bgColor(NULL);
YColor * ObjectButton::fgColor(NULL);

ObjectBar::ObjectBar(YWindow *parent): YWindow(parent) {
    setSize(1, 1);
}

ObjectBar::~ObjectBar() {
}

void ObjectBar::addButton(const ustring &name, ref<YIcon> icon, YButton *button) {
    button->setToolTip(name);
#ifndef LITE
    if (icon != null) {
        button->setIcon(icon, YIcon::smallSize());
        button->setSize(button->width() + 4, button->width() + 4);
    } else
#endif
        button->setText(name);

    button->setPosition(width(), 0);
    int h = button->height();
    if (h < height())
        h = height();

    if (h < height())
        h = height();

    button->setSize(button->width(), h);
    setSize(width() + button->width(), h);
    button->show();

    objects.append(button);
}

void ObjectBar::paint(Graphics &g, const YRect &/*r*/) {
#ifdef CONFIG_GRADIENTS
    ref<YImage> gradient(parent()->getGradient());

    if (gradient != null)
        g.drawImage(gradient, this->x(), this->y(), width(), height(), 0, 0);
    else
#endif
        if (taskbackPixmap != null)
            g.fillPixmap(taskbackPixmap, 0, 0, width(), height());
        else {
            g.setColor(getTaskBarBg());
            g.fillRect(0, 0, width(), height());
        }
}

void ObjectBar::addObject(DObject *object) {
    YButton *button = new ObjectButton(this, object);
    addButton(object->getName(), object->getIcon(), button);
}

void ObjectBar::addSeparator() {
    setSize(width() + 4, height());
    objects.append(0);
}

void ObjectBar::addContainer(const ustring &name, ref<YIcon> icon, ObjectContainer *container) {
    if (container) {
        YButton *button = new ObjectButton(this, (YMenu*) container);
        addButton(name, icon, button);
    }
}

void ObjectBar::configure(const YRect &r) {
    YWindow::configure(r);

    int left = 0;
    for (int i = 0; i < objects.getCount(); i++) {
        YButton *obj = objects[i];
        if (obj) {
            obj->setGeometry(YRect(left, 0, obj->width(), height()));
            left += obj->width();
        } else
            left += 4;
    }
}

ref<YFont> ObjectButton::getFont() {
    return font != null ? font : font =
        (*toolButtonFontName ? YFont::getFont(XFA(toolButtonFontName))
         : YButton::getFont());
}

YColor * ObjectButton::getColor() {
    return *clrToolButtonText
        ? fgColor ? fgColor : fgColor = new YColor(clrToolButtonText)
        : YButton::getColor();
}

YSurface ObjectButton::getSurface() {
    if (bgColor == 0)
        bgColor = new YColor(*clrToolButton ? clrToolButton : clrNormalButton);

#ifdef CONFIG_GRADIENTS
    return YSurface(bgColor, toolbuttonPixmap, toolbuttonPixbuf);
#else
    return YSurface(bgColor, toolbuttonPixmap);
#endif
}

void ObjectButton::actionPerformed(YAction * action, unsigned modifiers) {
#ifdef CONFIG_GUIEVENTS
    wmapp->signalGuiEvent(geLaunchApp);
#endif
    if (fObject) fObject->open();
    else YButton::actionPerformed(action, modifiers);
}

#endif /* CONFIG_TASKBAR */

#ifndef NO_CONFIGURE_MENUS
ObjectMenu *rootMenu(NULL);
#endif
<|endoftext|>


<commit_before>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup()
{
	ofSetLogLevel(OF_LOG_VERBOSE);
	ofSetLogLevel("ofThread", OF_LOG_ERROR);

	ofEnableAlphaBlending();

	doDrawInfo = true;

	targetWidth = 640;
	targetHeight = 480;
#if defined(TARGET_OPENGLES)
	consoleListener.setup(this);
	omxCameraSettings.width = targetWidth;
	omxCameraSettings.height = targetHeight;
	omxCameraSettings.framerate = 15;
	omxCameraSettings.enableTexture = true;

	videoGrabber.setup(omxCameraSettings);
	filterCollection.setup();
	ofSetVerticalSync(false);
	shader.load("shaderRpi");
#else
	videoGrabber.setDeviceID(0);
	videoGrabber.setDesiredFrameRate(30);
	videoGrabber.setup(targetWidth, targetHeight);
	ofSetVerticalSync(true);
	shader.load("shaderDesktop");
#endif
	doShader = true;
	iEffect = 2;

	fbo.allocate(targetWidth, targetHeight);
	fbo.begin();
	ofClear(0, 0, 0, 0);
	fbo.end();
	// selfberry
	colorGifEncoder.setup(targetWidth, targetHeight, .2, 256);
	ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved);

	videoTexture.allocate(targetWidth, targetHeight, GL_RGB);

	bufferDir = "buffer";

	timeZero = ofGetElapsedTimeMicros();
	frameNumber = 0;
	slotRecording = 255;
	slotAmount = 4;
	if (dirSRC.doesDirectoryExist(bufferDir)) {
		dirSRC.removeDirectory(bufferDir, true);
	}
	if (!dirSRC.doesDirectoryExist("slot1")) {
		dirSRC.createDirectory("slot1");
	}
	if (!dirSRC.doesDirectoryExist("slot2")) {
		dirSRC.createDirectory("slot2");
	}
	if (!dirSRC.doesDirectoryExist("slot3")) {
		dirSRC.createDirectory("slot3");
	}
	if (!dirSRC.doesDirectoryExist("slot4")) {
		dirSRC.createDirectory("slot4");
	}
	if (!dirSRC.doesDirectoryExist("tmp")) {
		dirSRC.createDirectory("tmp");
	}
	if (!dirSRC.doesDirectoryExist("gif")) {
		dirSRC.createDirectory("gif");
	}
	dirSRC.createDirectory(bufferDir);
	indexSavedPhoto = 0;
	isRecording = false;
	amountOfFrames = 10;
	maxFrames = 10;
	if (settings.loadFile("settings.xml") == false) {
		ofLog() << "XML ERROR, possibly quit";
	}
	settings.pushTag("settings");

	slotDir = "slot";
	for (int i = 0; i < settings.getNumTags("slot"); i++) {
		settings.pushTag("slot", i);
		videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0));
		settings.popTag();
	}
	lastSpot = 0;
	currentDisplaySlot = 1;
	bkgLayer.loadImage("ui.png");
	sourisitepajoli.loadImage("sourisitepajoli.png");
	trois.loadImage("trois.png");
	deux.loadImage("deux.png");
	un.loadImage("un.png");
}

//--------------------------------------------------------------
void ofApp::update()
{
#if defined(TARGET_OPENGLES)

#else
	videoGrabber.update();
#endif
	if (!doShader || !videoGrabber.isFrameNew())
	{
		//ofLogNotice("update() !videoGrabber.isFrameNew return");
		return;
	}
	//ofLogNotice("update() fbo begin");
	fbo.begin();
	ofClear(1, 1, 0, 0);
	shader.begin();
	shader.setUniform1f("time", ofGetElapsedTimef());
	shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight());
	shader.setUniform3f("iResolution", ofGetWidth(), ofGetHeight(), 0);
	shader.setUniform2f("iMouse", indexSavedPhoto, indexSavedPhoto);
	shader.setUniform1f("iGlobalTime", ofGetElapsedTimef());
	shader.setUniform4f("iDate", ofGetYear(), ofGetMonth(), ofGetDay(), ofGetSeconds());
	shader.setUniform1i("iEffect", iEffect);// floor(ofRandom(0, 4.9)));
	shader.setUniform1f("iChromatic", ofRandom(-1, 1));
	shader.setUniform1f("iShift", ofRandom(-1.0, 1.0));
	shader.setUniform1f("iGlitch", ofRandom(0.0, 1.0));
	shader.setUniform1f("iPixelate", ofRandom(0.7, 1.0));
#if defined(TARGET_OPENGLES)
	shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID());
	videoGrabber.draw();
#else
	shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0);// 0 or 1?
	videoGrabber.draw(0, 0);
#endif
	shader.end();
	fbo.end();
	//ofLogNotice("update() fbo end");

	if (isRecording == true) {
		ofLogNotice("update() rec");
		finalCountdown = ofGetSeconds() - currentSecond;
		if (finalCountdown > 2) {

			dirSRC.createDirectory(bufferDir);
			dirSRC.listDir(bufferDir);
			recordedFramesAmount = dirSRC.size();
			ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));
			if (recordedFramesAmount == maxFrames) {
				isRecording = false;
				indexSavedPhoto = 0;
				ofLogNotice("update() stop recording");
			}
			else {
				if (videoGrabber.isFrameNew()) {
					ofLogNotice("update() isFrameNew");

					string filename;
					if (indexSavedPhoto < 10) filename = "slot" + ofToString(currentDisplaySlot) + "//seq00" + ofToString(indexSavedPhoto) + ".tga";
					if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "slot" + ofToString(currentDisplaySlot) + "//seq0" + ofToString(indexSavedPhoto) + ".tga";
					if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "slot" + ofToString(currentDisplaySlot) + "//seq" + ofToString(indexSavedPhoto) + ".tga";
					// fbo to pixels
					fbo.readToPixels(pix);
					fbo.draw(0, 0, targetWidth, targetHeight);
					ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));

					//pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR);
					savedImage.setFromPixels(pix);
					savedImage.setImageType(OF_IMAGE_COLOR);
					savedImage.saveImage(filename);

					ofLogNotice("update() currentDisplaySlot " + ofToString(currentDisplaySlot));

					savedImage.saveImage(bufferDir + "//" + filename + ".tga");
					//omxCameraSettings.width, omxCameraSettings.height
					// add frame to gif encoder
					colorGifEncoder.addFrame(
						pix.getPixels(),
						targetWidth,
						targetHeight,
						pix.getBitsPerPixel()/*,
											 .1f duration */
					);

					recordedFramesAmount++;
					pix.clear();
					savedImage.clear();
					indexSavedPhoto++;
					if (indexSavedPhoto == amountOfFrames) {
						ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames));
						isRecording = false;
						indexSavedPhoto = 0;
						saveGif();
					}
				}
			}
		}

	}
	for (i = 1; i < slotAmount; i++) {
		videoGrid[i].loadFrameNumber(frameNumber);
	}
	frameNumber++;
	if (frameNumber == maxFrames) {
		frameNumber = 0;
	}
}
void ofApp::saveGif()
{
	string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
	ofLogNotice("saveGif: " + fileName);
	colorGifEncoder.save("gif//" + fileName + ".gif");
	ofLogNotice("saveGif end");
}
void ofApp::onGifSaved(string & fileName) {
	cout << "gif saved as " << fileName << endl;
	ofLogNotice("onGifSaved: " + fileName);
	colorGifEncoder.reset();
	ofLogNotice("onGifSaved reset");
}
//--------------------------------------------------------------
void ofApp::draw() {

	ofClear(0, 0, 0, 0);
	stringstream info;
	info << "APP FPS: " << ofGetFrameRate() << "\n";
	info << "SHADER ENABLED: " << doShader << "\n";

	if (doShader)
	{
#if defined(TARGET_OPENGLES)
		fbo.draw(330, 13);
#else
		videoGrabber.draw(330, 13);
#endif
}
	else
	{
#if defined(TARGET_OPENGLES)
		videoGrabber.draw();
#else
		videoGrabber.draw(330, 13);
#endif
	}
	for (int i = 1; i < slotAmount; i++) {
		videoGrid[i].draw();
	}
#if defined(TARGET_OPENGLES)
	info << "Resolution Camera: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n";
	info << "FILTRE: " << filterCollection.getCurrentFilterName() << "\n";
#endif

	info << "\n";
	info << "VERT: changement de filtre" << "\n";
	info << "ROUGE: enregistrer" << "\n";
	bkgLayer.draw(0, 0);
	if (isRecording) {
		sourisitepajoli.draw(400, 0);
		switch (finalCountdown) {
		case 0:
			trois.draw(400, 0);
			break;
		case 1:
			deux.draw(400, 0);
			break;
		case 2:
			un.draw(400, 0);
			break;
		}
	}
	if (doDrawInfo) {
		ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow);
	}
	}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
	//ofLog(OF_LOG_VERBOSE, "%c keyPressed", key);
	ofLogNotice("PRESSED KEY: " + ofToString(key));
	/*RED 13 10
		WHITE 127 126
		YELLOW 54
		GREEN 357 65
		BLUE 50*/
	switch (key) {
	case 65:
	case 357:
#if defined(TARGET_OPENGLES)
		videoGrabber.setImageFilter(filterCollection.getNextFilter());
#endif
		break;
	case 10:
	case 13:
		if (!isRecording) {
			isRecording = true;
			indexSavedPhoto = 0;
			currentDisplaySlot++;
			if (currentDisplaySlot > 4) currentDisplaySlot = 1;
			bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
			currentSecond = ofGetSeconds();
		}
		break;
	case 126:
		doDrawInfo = !doDrawInfo;
		iEffect = 3;
		currentDisplaySlot++;
		if (currentDisplaySlot > 4) currentDisplaySlot = 1;
		break;
	case 67: // jaune
		iEffect = 1;
	case 66: // bleu
		iEffect = 2;
	case 50:
	case 359:
		currentDisplaySlot = 1;
		//doShader = !doShader;
		break;
	}
}
#if defined(TARGET_OPENGLES)
void ofApp::onCharacterReceived(KeyListenerEventData& e)
{
	keyPressed((int)e.character);
	}
#endif
<commit_msg>TODO inutile?<commit_after>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup()
{
	ofSetLogLevel(OF_LOG_VERBOSE);
	ofSetLogLevel("ofThread", OF_LOG_ERROR);

	ofEnableAlphaBlending();

	doDrawInfo = true;

	targetWidth = 640;
	targetHeight = 480;
#if defined(TARGET_OPENGLES)
	consoleListener.setup(this);
	omxCameraSettings.width = targetWidth;
	omxCameraSettings.height = targetHeight;
	omxCameraSettings.framerate = 15;
	omxCameraSettings.enableTexture = true;

	videoGrabber.setup(omxCameraSettings);
	filterCollection.setup();
	ofSetVerticalSync(false);
	shader.load("shaderRpi");
#else
	videoGrabber.setDeviceID(0);
	videoGrabber.setDesiredFrameRate(30);
	videoGrabber.setup(targetWidth, targetHeight);
	ofSetVerticalSync(true);
	shader.load("shaderDesktop");
#endif
	doShader = true;
	iEffect = 2;

	fbo.allocate(targetWidth, targetHeight);
	fbo.begin();
	ofClear(0, 0, 0, 0);
	fbo.end();
	// selfberry
	colorGifEncoder.setup(targetWidth, targetHeight, .2, 256);
	ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved);

	videoTexture.allocate(targetWidth, targetHeight, GL_RGB);

	bufferDir = "buffer";

	timeZero = ofGetElapsedTimeMicros();
	frameNumber = 0;
	slotRecording = 255;
	slotAmount = 4;
	if (dirSRC.doesDirectoryExist(bufferDir)) {
		dirSRC.removeDirectory(bufferDir, true);
	}
	if (!dirSRC.doesDirectoryExist("slot1")) {
		dirSRC.createDirectory("slot1");
	}
	if (!dirSRC.doesDirectoryExist("slot2")) {
		dirSRC.createDirectory("slot2");
	}
	if (!dirSRC.doesDirectoryExist("slot3")) {
		dirSRC.createDirectory("slot3");
	}
	if (!dirSRC.doesDirectoryExist("slot4")) {
		dirSRC.createDirectory("slot4");
	}
	if (!dirSRC.doesDirectoryExist("tmp")) {
		dirSRC.createDirectory("tmp");
	}
	if (!dirSRC.doesDirectoryExist("gif")) {
		dirSRC.createDirectory("gif");
	}
	dirSRC.createDirectory(bufferDir);
	indexSavedPhoto = 0;
	isRecording = false;
	amountOfFrames = 10;
	maxFrames = 10;
	if (settings.loadFile("settings.xml") == false) {
		ofLog() << "XML ERROR, possibly quit";
	}
	settings.pushTag("settings");

	slotDir = "slot";
	for (int i = 0; i < settings.getNumTags("slot"); i++) {
		settings.pushTag("slot", i);
		videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0));
		settings.popTag();
	}
	lastSpot = 0;
	currentDisplaySlot = 1;
	bkgLayer.loadImage("ui.png");
	sourisitepajoli.loadImage("sourisitepajoli.png");
	trois.loadImage("trois.png");
	deux.loadImage("deux.png");
	un.loadImage("un.png");
}

//--------------------------------------------------------------
void ofApp::update()
{
#if defined(TARGET_OPENGLES)

#else
	videoGrabber.update();
#endif
	if (!doShader || !videoGrabber.isFrameNew())
	{
		//ofLogNotice("update() !videoGrabber.isFrameNew return");
		return;
	}
	//ofLogNotice("update() fbo begin");
	fbo.begin();
	ofClear(1, 1, 0, 0);
	shader.begin();
	shader.setUniform1f("time", ofGetElapsedTimef());
	shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight());
	shader.setUniform3f("iResolution", ofGetWidth(), ofGetHeight(), 0);
	shader.setUniform2f("iMouse", indexSavedPhoto, indexSavedPhoto);
	shader.setUniform1f("iGlobalTime", ofGetElapsedTimef());
	shader.setUniform4f("iDate", ofGetYear(), ofGetMonth(), ofGetDay(), ofGetSeconds());
	shader.setUniform1i("iEffect", iEffect);// floor(ofRandom(0, 4.9)));
	shader.setUniform1f("iChromatic", ofRandom(-1, 1));
	shader.setUniform1f("iShift", ofRandom(-1.0, 1.0));
	shader.setUniform1f("iGlitch", ofRandom(0.0, 1.0));
	shader.setUniform1f("iPixelate", ofRandom(0.7, 1.0));
#if defined(TARGET_OPENGLES)
	shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID());
	videoGrabber.draw();
#else
	shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0);// 0 or 1?
	videoGrabber.draw(0, 0);
#endif
	shader.end();
	fbo.end();
	//ofLogNotice("update() fbo end");

	if (isRecording == true) {
		ofLogNotice("update() rec");
		finalCountdown = ofGetSeconds() - currentSecond;
		if (finalCountdown > 2) {

			dirSRC.createDirectory(bufferDir);
			dirSRC.listDir(bufferDir);
			recordedFramesAmount = dirSRC.size();
			ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));
			if (recordedFramesAmount == maxFrames) {
				isRecording = false;
				indexSavedPhoto = 0;
				ofLogNotice("update() stop recording");
			}
			else {
				if (videoGrabber.isFrameNew()) {
					ofLogNotice("update() isFrameNew");

					string filename;
					if (indexSavedPhoto < 10) filename = "slot" + ofToString(currentDisplaySlot) + "//seq00" + ofToString(indexSavedPhoto) + ".tga";
					if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "slot" + ofToString(currentDisplaySlot) + "//seq0" + ofToString(indexSavedPhoto) + ".tga";
					if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "slot" + ofToString(currentDisplaySlot) + "//seq" + ofToString(indexSavedPhoto) + ".tga";
					// fbo to pixels
					fbo.readToPixels(pix);
					fbo.draw(0, 0, targetWidth, targetHeight);
					ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));

					//pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR);
					savedImage.setFromPixels(pix);
					savedImage.setImageType(OF_IMAGE_COLOR);
					savedImage.saveImage(filename);

					ofLogNotice("update() currentDisplaySlot " + ofToString(currentDisplaySlot));

					// TODO verif chemin + fichier savedImage.saveImage(bufferDir + "//" + filename + ".tga");
					//omxCameraSettings.width, omxCameraSettings.height
					// add frame to gif encoder
					colorGifEncoder.addFrame(
						pix.getPixels(),
						targetWidth,
						targetHeight,
						pix.getBitsPerPixel()/*,
											 .1f duration */
					);

					recordedFramesAmount++;
					pix.clear();
					savedImage.clear();
					indexSavedPhoto++;
					if (indexSavedPhoto == amountOfFrames) {
						ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames));
						isRecording = false;
						indexSavedPhoto = 0;
						saveGif();
					}
				}
			}
		}

	}
	for (i = 1; i < slotAmount; i++) {
		videoGrid[i].loadFrameNumber(frameNumber);
	}
	frameNumber++;
	if (frameNumber == maxFrames) {
		frameNumber = 0;
	}
}
void ofApp::saveGif()
{
	string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
	ofLogNotice("saveGif: " + fileName);
	colorGifEncoder.save("gif//" + fileName + ".gif");
	ofLogNotice("saveGif end");
}
void ofApp::onGifSaved(string & fileName) {
	cout << "gif saved as " << fileName << endl;
	ofLogNotice("onGifSaved: " + fileName);
	colorGifEncoder.reset();
	ofLogNotice("onGifSaved reset");
}
//--------------------------------------------------------------
void ofApp::draw() {

	ofClear(0, 0, 0, 0);
	stringstream info;
	info << "APP FPS: " << ofGetFrameRate() << "\n";
	info << "SHADER ENABLED: " << doShader << "\n";

	if (doShader)
	{
#if defined(TARGET_OPENGLES)
		fbo.draw(330, 13);
#else
		videoGrabber.draw(330, 13);
#endif
}
	else
	{
#if defined(TARGET_OPENGLES)
		videoGrabber.draw();
#else
		videoGrabber.draw(330, 13);
#endif
	}
	for (int i = 1; i < slotAmount; i++) {
		videoGrid[i].draw();
	}
#if defined(TARGET_OPENGLES)
	info << "Resolution Camera: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n";
	info << "FILTRE: " << filterCollection.getCurrentFilterName() << "\n";
#endif

	info << "\n";
	info << "VERT: changement de filtre" << "\n";
	info << "ROUGE: enregistrer" << "\n";
	bkgLayer.draw(0, 0);
	if (isRecording) {
		sourisitepajoli.draw(400, 0);
		switch (finalCountdown) {
		case 0:
			trois.draw(400, 0);
			break;
		case 1:
			deux.draw(400, 0);
			break;
		case 2:
			un.draw(400, 0);
			break;
		}
	}
	if (doDrawInfo) {
		ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow);
	}
	}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
	//ofLog(OF_LOG_VERBOSE, "%c keyPressed", key);
	ofLogNotice("PRESSED KEY: " + ofToString(key));
	/*RED 13 10
		WHITE 127 126
		YELLOW 54
		GREEN 357 65
		BLUE 50*/
	switch (key) {
	case 65:
	case 357:
#if defined(TARGET_OPENGLES)
		videoGrabber.setImageFilter(filterCollection.getNextFilter());
#endif
		break;
	case 10:
	case 13:
		if (!isRecording) {
			isRecording = true;
			indexSavedPhoto = 0;
			currentDisplaySlot++;
			if (currentDisplaySlot > 4) currentDisplaySlot = 1;
			bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
			currentSecond = ofGetSeconds();
		}
		break;
	case 126:
		doDrawInfo = !doDrawInfo;
		iEffect = 3;
		currentDisplaySlot++;
		if (currentDisplaySlot > 4) currentDisplaySlot = 1;
		break;
	case 67: // jaune
		iEffect = 1;
	case 66: // bleu
		iEffect = 2;
	case 50:
	case 359:
		currentDisplaySlot = 1;
		//doShader = !doShader;
		break;
	}
}
#if defined(TARGET_OPENGLES)
void ofApp::onCharacterReceived(KeyListenerEventData& e)
{
	keyPressed((int)e.character);
	}
#endif
<|endoftext|>


<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
#include <stdio.h>
#include <sstream>
#include <string>

using namespace std;
//using namespace cv;

int H_MIN = 0;
int H_MAX = 256;
int S_MIN = 0;
int S_MAX = 256;
int V_MIN = 0;
int V_MAX = 256;

//Things I want to do:
//Make a window for the HSV trackbars
//Make a window for the position in the video with button for play/pause

void on_HSV_trackbar( int position, void* ){

}

void createTrackbarsWindow(){
	string trackbarWindowName = "Adjust me!";
	cv::namedWindow(trackbarWindowName,0);

	char TrackbarName[50];

	cv::createTrackbar( "H_MIN", trackbarWindowName, &H_MIN, H_MAX, on_HSV_trackbar);
	cv::createTrackbar( "H_MAX", trackbarWindowName, &H_MAX, H_MAX, on_HSV_trackbar);
	cv::createTrackbar( "S_MIN", trackbarWindowName, &S_MIN, S_MAX, on_HSV_trackbar);
	cv::createTrackbar( "S_MAX", trackbarWindowName, &S_MAX, S_MAX, on_HSV_trackbar);
	cv::createTrackbar( "V_MIN", trackbarWindowName, &V_MIN, V_MAX, on_HSV_trackbar);
	cv::createTrackbar( "V_MAX", trackbarWindowName, &V_MAX, V_MAX, on_HSV_trackbar);
}

int main(int argc, char* argv[]){
	//Declaring local variables for the main function
	string videoFileName = "juggle.mov";

	//Opening the video file
	cv::VideoCapture video(videoFileName);
	if(!video.isOpened()){
		cout << "Cannot open the file" << endl;
		return -1;
	}

	//Creating the other windows
	createTrackbarsWindow();

  while(1){
		//Declaring the local variables for the video loop
    cv::Mat frame, out, temp, gray;

		//Reads a new frame from the video and verifies it
    bool readVideoSuccess = video.read(frame);
    if (!readVideoSuccess){
      cout << "Cannot read from file" << endl;
      break;
    }

		//Where the image manipulation happens

				//cv::GaussianBlur( frame, out, Size(5,5), 3, 3);
				cv::pyrDown(frame, temp);
				cv::cvtColor(temp, gray, CV_BGR2HSV);
        //imshow("MyVideo", frame); //show the frame in "MyVideo" window

				cv::inRange(gray, cv::Scalar(H_MIN,S_MIN,V_MIN),cv::Scalar(H_MAX,S_MAX,V_MAX),out);
				cv::inRange(gray, cv::Scalar(165,105,170),cv::Scalar(230,256,205),out);
				//morphOps(out);

				cv::vector<cv::Vec3f> circles;

				cv::HoughCircles(out, circles, CV_HOUGH_GRADIENT, 1, out.rows/2, 20, 10, 0, 0 );

				for( size_t i = 0; i < circles.size(); i++ )
				{
					cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
					int radius = cvRound(circles[i][2]);
					// draw the circle center
					circle( temp, center, 3, cv::Scalar(0,255,0), -1, 8, 0 );
					// draw the circle outline
					circle( temp, center, radius, cv::Scalar(0,0,255), 3, 8, 0 );
				}

        cv::imshow("output", out); //show the frame in "MyVideo" window

				if(cv::waitKey(30) == 27) //wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
       {
                cout << "esc key is pressed by user" << endl;
                break;
       }
    }

    return 0;

}
<commit_msg>Update juggle.cpp<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
#include <stdio.h>
#include <sstream>
#include <string>

using namespace std;
//using namespace cv;

int H_MIN = 0;
int H_MAX = 256;
int S_MIN = 0;
int S_MAX = 256;
int V_MIN = 0;
int V_MAX = 256;

//Things I want to do:
//Make a window for the HSV trackbars
//Make a window for the position in the video with button for play/pause

void onHSVTrackbarSlide(int position, void*){

}

void createHSVTrackbarsWindow(){
	string trackbarWindowName = "Adjust me!";
	cv::namedWindow(trackbarWindowName,0);

	char TrackbarName[50];

	cv::createTrackbar( "H_MIN", trackbarWindowName, &H_MIN, H_MAX, onHSVTrackbarSlide);
	cv::createTrackbar( "H_MAX", trackbarWindowName, &H_MAX, H_MAX, onHSVTrackbarSlide);
	cv::createTrackbar( "S_MIN", trackbarWindowName, &S_MIN, S_MAX, onHSVTrackbarSlide);
	cv::createTrackbar( "S_MAX", trackbarWindowName, &S_MAX, S_MAX, onHSVTrackbarSlide);
	cv::createTrackbar( "V_MIN", trackbarWindowName, &V_MIN, V_MAX, onHSVTrackbarSlide);
	cv::createTrackbar( "V_MAX", trackbarWindowName, &V_MAX, V_MAX, onHSVTrackbarSlide);
}

void onPositionTrackbarSlide(int position, void*){

}

void createPositionTrackbarWindow(){

}

void manipulateImage(){

}

int main(int argc, char* argv[]){
	//Declaring local variables for the main function
	string videoFileName = "juggle.mov";

	//Opening the video file
	cv::VideoCapture video(videoFileName);
	if(!video.isOpened()){
		cout << "Cannot open the file" << endl;
		return -1;
	}

	//Creating the other windows
	createHSVTrackbarsWindow();

  while(1){
		//Declaring the local variables for the video loop
    cv::Mat frame, out, temp, gray;

		//Reads a new frame from the video and verifies it
    bool readVideoSuccess = video.read(frame);
    if (!readVideoSuccess){
      cout << "Cannot read from file" << endl;
      break;
    }

		//Where the image manipulation happens

		//wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
		if(cv::waitKey(30) == 27){
			cout << "esc key is pressed by user" << endl;
			break;
    }

				//cv::GaussianBlur( frame, out, Size(5,5), 3, 3);
				cv::pyrDown(frame, temp);
				cv::cvtColor(temp, gray, CV_BGR2HSV);
        //imshow("MyVideo", frame); //show the frame in "MyVideo" window

				cv::inRange(gray, cv::Scalar(H_MIN,S_MIN,V_MIN),cv::Scalar(H_MAX,S_MAX,V_MAX),out);
				cv::inRange(gray, cv::Scalar(165,105,170),cv::Scalar(230,256,205),out);
				//morphOps(out);

				cv::vector<cv::Vec3f> circles;

				cv::HoughCircles(out, circles, CV_HOUGH_GRADIENT, 1, out.rows/2, 20, 10, 0, 0 );

				for( size_t i = 0; i < circles.size(); i++ )
				{
					cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
					int radius = cvRound(circles[i][2]);
					// draw the circle center
					circle( temp, center, 3, cv::Scalar(0,255,0), -1, 8, 0 );
					// draw the circle outline
					circle( temp, center, radius, cv::Scalar(0,0,255), 3, 8, 0 );
				}

        cv::imshow("output", out); //show the frame in "MyVideo" window

    }
    return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////

#ifdef _WIN32
#include "Basics/win-utils.h"
#endif

#include "Scheduler.h"

#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>

#include "Basics/MutexLocker.h"
#include "Basics/StringUtils.h"
#include "Basics/Thread.h"
#include "Logger/Logger.h"
#include "Rest/GeneralResponse.h"
#include "Scheduler/JobQueue.h"
#include "Scheduler/Task.h"

using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;

// -----------------------------------------------------------------------------
// --SECTION--                                            SchedulerManagerThread
// -----------------------------------------------------------------------------

namespace {
class SchedulerManagerThread : public Thread {
 public:
  SchedulerManagerThread(Scheduler* scheduler, boost::asio::io_service* service)
      : Thread("SchedulerManager"), _scheduler(scheduler), _service(service) {}

  ~SchedulerManagerThread() { shutdown(); }

 public:
  void run() {
    while (!_scheduler->isStopping()) {
      try {
        _service->run_one();
        _scheduler->deleteOldThreads();
      } catch (...) {
        LOG_TOPIC(ERR, Logger::THREADS)
            << "manager loop caught an error, restarting";
      }
    }

    _scheduler->threadDone(this);
  }

 private:
  Scheduler* _scheduler;
  boost::asio::io_service* _service;
};
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   SchedulerThread
// -----------------------------------------------------------------------------

namespace {
class SchedulerThread : public Thread {
 public:
  SchedulerThread(Scheduler* scheduler, boost::asio::io_service* service)
      : Thread("Scheduler"), _scheduler(scheduler), _service(service) {}

  ~SchedulerThread() { shutdown(); }

 public:
  void run() {
    _scheduler->incRunning();
    LOG_TOPIC(DEBUG, Logger::THREADS) << "running (" << _scheduler->infoStatus()
                                      << ")";

    auto start = std::chrono::steady_clock::now();

    try {
      static size_t EVERY_LOOP = 1000;
      static double MIN_SECONDS = 30;

      size_t counter = 0;
      while (!_scheduler->isStopping()) {
        _service->run_one();

        if (++counter > EVERY_LOOP) {
          auto now = std::chrono::steady_clock::now();
          std::chrono::duration<double> diff = now - start;

          if (diff.count() > MIN_SECONDS) {
            if (_scheduler->stopThread()) {
              auto n = _scheduler->decRunning();

              if (n <= 2) {
                _scheduler->incRunning();
              } else {
                break;
              }
            }

            start = std::chrono::steady_clock::now();
          }
        }
      }

      LOG_TOPIC(DEBUG, Logger::THREADS) << "stopped ("
                                        << _scheduler->infoStatus() << ")";
    } catch (...) {
      LOG_TOPIC(ERR, Logger::THREADS)
          << "scheduler loop caught an error, restarting";
      _scheduler->decRunning();
      _scheduler->startNewThread();
    }

    _scheduler->threadDone(this);
  }

 private:
  Scheduler* _scheduler;
  boost::asio::io_service* _service;
};
}

// -----------------------------------------------------------------------------
// --SECTION--                                                         Scheduler
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

Scheduler::Scheduler(size_t nrThreads, size_t maxQueueSize)
    : _nrThreads(nrThreads),
      _maxQueueSize(maxQueueSize),
      _stopping(false),
      _nrBusy(0),
      _nrWorking(0),
      _nrBlocked(0),
      _nrRunning(0),
      _nrMinimal(0),
      _nrMaximal(0),
      _nrRealMaximum(0),
      _lastThreadWarning(0) {
  // setup signal handlers
  initializeSignalHandlers();
}

Scheduler::~Scheduler() {
  if (_threadManager != nullptr) {
    _threadManager->cancel();
  }
  deleteOldThreads();
}

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

bool Scheduler::start(ConditionVariable* cv) {
  // start the I/O
  startIoService();

  // initialize thread handling
  if (_nrMaximal <= 0) {
    _nrMaximal = _nrThreads;
  }

  if (_nrRealMaximum <= 0) {
    _nrRealMaximum = 4 * _nrMaximal;
  }

  for (size_t i = 0; i < 2; ++i) {
    startNewThread();
  }

  startManagerThread();
  startRebalancer();

  // initialize the queue handling
  _jobQueue.reset(new JobQueue(_maxQueueSize, _ioService.get()));
  _jobQueue->start();

  // done
  LOG(TRACE) << "all scheduler threads are up and running";
  return true;
}

void Scheduler::startIoService() {
  _ioService.reset(new boost::asio::io_service());
  _serviceGuard.reset(new boost::asio::io_service::work(*_ioService));

  _managerService.reset(new boost::asio::io_service());
  _managerGuard.reset(new boost::asio::io_service::work(*_managerService));
}

void Scheduler::startRebalancer() {
  std::chrono::milliseconds interval(500);
  _threadManager.reset(new boost::asio::steady_timer(*_managerService));

  _threadHandler = [this, interval](const boost::system::error_code& error) {
    if (error || isStopping()) {
      return;
    }

    rebalanceThreads();

    _threadManager->expires_from_now(interval);
    _threadManager->async_wait(_threadHandler);
  };

  _threadManager->expires_from_now(interval);
  _threadManager->async_wait(_threadHandler);

  _lastThreadWarning.store(TRI_microtime());
}

void Scheduler::startManagerThread() {
  MUTEX_LOCKER(guard, _threadsLock);

  auto thread = new SchedulerManagerThread(this, _managerService.get());

  _threads.emplace(thread);
  thread->start();
}

void Scheduler::startNewThread() {
  MUTEX_LOCKER(guard, _threadsLock);

  auto thread = new SchedulerThread(this, _ioService.get());

  _threads.emplace(thread);
  thread->start();
}

bool Scheduler::stopThread() {
  if (_nrRunning <= _nrMinimal) {
    return false;
  }

  if (_nrRunning >= 3) {
    int64_t low = ((_nrRunning <= 4) ? 0 : (_nrRunning * 1 / 4)) - _nrBlocked;

    if (_nrBusy <= low && _nrWorking <= low) {
      return true;
    }
  }

  return false;
}

void Scheduler::threadDone(Thread* thread) {
  MUTEX_LOCKER(guard, _threadsLock);

  _threads.erase(thread);
  _deadThreads.insert(thread);
}

void Scheduler::deleteOldThreads() {
  // delete old thread objects
  std::unordered_set<Thread*> deadThreads;

  {
    MUTEX_LOCKER(guard, _threadsLock);

    if (_deadThreads.empty()) {
      return;
    }

    deadThreads.swap(_deadThreads);
  }

  for (auto thread : deadThreads) {
    try {
      delete thread;
    } catch (...) {
      LOG_TOPIC(ERR, Logger::THREADS) << "cannot delete thread";
    }
  }
}

void Scheduler::rebalanceThreads() {
  static double const MIN_WARN_INTERVAL = 10;
  static double const MIN_ERR_INTERVAL = 300;

  int64_t high = (_nrRunning <= 4) ? 1 : (_nrRunning * 11 / 16);
  int64_t working = (_nrBusy > _nrWorking) ? _nrBusy : _nrWorking;

  LOG_TOPIC(DEBUG, Logger::THREADS) << "rebalancing threads, high: " << high
                                    << ", working: " << working << " ("
                                    << infoStatus() << ")";

  if (working >= high) {
    if (_nrRunning < _nrMaximal + _nrBlocked &&
        _nrRunning < _nrRealMaximum) {   // added by Max 22.12.2016
      // otherwise we exceed the total maximum
      startNewThread();
      return;
    }
  }

  if (working >= _nrMaximal + _nrBlocked || _nrRunning < _nrMinimal) {
    double ltw = _lastThreadWarning.load();
    double now = TRI_microtime();

    if (_nrRunning >= _nrRealMaximum) {
      if (ltw - now > MIN_ERR_INTERVAL) {
        LOG_TOPIC(ERR, Logger::THREADS) << "too many threads (" << infoStatus()
                                        << ")";
        _lastThreadWarning.store(now);
      }
    } else {
      if (_nrRunning >= _nrRealMaximum * 3 / 4) {
        if (ltw - now > MIN_WARN_INTERVAL) {
          LOG_TOPIC(WARN, Logger::THREADS)
              << "number of threads is reaching a critical limit ("
              << infoStatus() << ")";
          _lastThreadWarning.store(now);
        }
      }

      LOG_TOPIC(DEBUG, Logger::THREADS) << "overloading threads ("
                                        << infoStatus() << ")";

      startNewThread();
    }
  }
}

void Scheduler::beginShutdown() {
  if (_stopping) {
    return;
  }

  _jobQueue->beginShutdown();

  _threadManager.reset();

  _managerGuard.reset();
  _managerService->stop();

  _serviceGuard.reset();
  _ioService->stop();

  // set the flag AFTER stopping the threads
  _stopping = true;
}

void Scheduler::shutdown() {
  bool done = false;

  while (!done) {
    MUTEX_LOCKER(guard, _threadsLock);
    done = _threads.empty();
  }

  deleteOldThreads();

  _managerService.reset();
  _ioService.reset();
}

void Scheduler::initializeSignalHandlers() {
#ifdef _WIN32
// Windows does not support POSIX signal handling
#else
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigfillset(&action.sa_mask);

  // ignore broken pipes
  action.sa_handler = SIG_IGN;

  int res = sigaction(SIGPIPE, &action, 0);

  if (res < 0) {
    LOG(ERR) << "cannot initialize signal handlers for pipe";
  }
#endif
}
<commit_msg>don't throw in dtor<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////

#ifdef _WIN32
#include "Basics/win-utils.h"
#endif

#include "Scheduler.h"

#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>

#include "Basics/MutexLocker.h"
#include "Basics/StringUtils.h"
#include "Basics/Thread.h"
#include "Logger/Logger.h"
#include "Rest/GeneralResponse.h"
#include "Scheduler/JobQueue.h"
#include "Scheduler/Task.h"

using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;

// -----------------------------------------------------------------------------
// --SECTION--                                            SchedulerManagerThread
// -----------------------------------------------------------------------------

namespace {
class SchedulerManagerThread : public Thread {
 public:
  SchedulerManagerThread(Scheduler* scheduler, boost::asio::io_service* service)
      : Thread("SchedulerManager"), _scheduler(scheduler), _service(service) {}

  ~SchedulerManagerThread() { shutdown(); }

 public:
  void run() {
    while (!_scheduler->isStopping()) {
      try {
        _service->run_one();
        _scheduler->deleteOldThreads();
      } catch (...) {
        LOG_TOPIC(ERR, Logger::THREADS)
            << "manager loop caught an error, restarting";
      }
    }

    _scheduler->threadDone(this);
  }

 private:
  Scheduler* _scheduler;
  boost::asio::io_service* _service;
};
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   SchedulerThread
// -----------------------------------------------------------------------------

namespace {
class SchedulerThread : public Thread {
 public:
  SchedulerThread(Scheduler* scheduler, boost::asio::io_service* service)
      : Thread("Scheduler"), _scheduler(scheduler), _service(service) {}

  ~SchedulerThread() { shutdown(); }

 public:
  void run() {
    _scheduler->incRunning();
    LOG_TOPIC(DEBUG, Logger::THREADS) << "running (" << _scheduler->infoStatus()
                                      << ")";

    auto start = std::chrono::steady_clock::now();

    try {
      static size_t EVERY_LOOP = 1000;
      static double MIN_SECONDS = 30;

      size_t counter = 0;
      while (!_scheduler->isStopping()) {
        _service->run_one();

        if (++counter > EVERY_LOOP) {
          auto now = std::chrono::steady_clock::now();
          std::chrono::duration<double> diff = now - start;

          if (diff.count() > MIN_SECONDS) {
            if (_scheduler->stopThread()) {
              auto n = _scheduler->decRunning();

              if (n <= 2) {
                _scheduler->incRunning();
              } else {
                break;
              }
            }

            start = std::chrono::steady_clock::now();
          }
        }
      }

      LOG_TOPIC(DEBUG, Logger::THREADS) << "stopped ("
                                        << _scheduler->infoStatus() << ")";
    } catch (...) {
      LOG_TOPIC(ERR, Logger::THREADS)
          << "scheduler loop caught an error, restarting";
      _scheduler->decRunning();
      _scheduler->startNewThread();
    }

    _scheduler->threadDone(this);
  }

 private:
  Scheduler* _scheduler;
  boost::asio::io_service* _service;
};
}

// -----------------------------------------------------------------------------
// --SECTION--                                                         Scheduler
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

Scheduler::Scheduler(size_t nrThreads, size_t maxQueueSize)
    : _nrThreads(nrThreads),
      _maxQueueSize(maxQueueSize),
      _stopping(false),
      _nrBusy(0),
      _nrWorking(0),
      _nrBlocked(0),
      _nrRunning(0),
      _nrMinimal(0),
      _nrMaximal(0),
      _nrRealMaximum(0),
      _lastThreadWarning(0) {
  // setup signal handlers
  initializeSignalHandlers();
}

Scheduler::~Scheduler() {
  if (_threadManager != nullptr) {
    try {
      _threadManager->cancel();
    } catch (...) {
      // must not throw in the dtor
    }
  }

  try {
    deleteOldThreads();
  } catch (...) {
    // probably out of memory here...
    // must not throw in the dtor
    LOG(ERR) << "unable to delete old scheduler threads";
  }
}

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

bool Scheduler::start(ConditionVariable* cv) {
  // start the I/O
  startIoService();

  // initialize thread handling
  if (_nrMaximal <= 0) {
    _nrMaximal = _nrThreads;
  }

  if (_nrRealMaximum <= 0) {
    _nrRealMaximum = 4 * _nrMaximal;
  }

  for (size_t i = 0; i < 2; ++i) {
    startNewThread();
  }

  startManagerThread();
  startRebalancer();

  // initialize the queue handling
  _jobQueue.reset(new JobQueue(_maxQueueSize, _ioService.get()));
  _jobQueue->start();

  // done
  LOG(TRACE) << "all scheduler threads are up and running";
  return true;
}

void Scheduler::startIoService() {
  _ioService.reset(new boost::asio::io_service());
  _serviceGuard.reset(new boost::asio::io_service::work(*_ioService));

  _managerService.reset(new boost::asio::io_service());
  _managerGuard.reset(new boost::asio::io_service::work(*_managerService));
}

void Scheduler::startRebalancer() {
  std::chrono::milliseconds interval(500);
  _threadManager.reset(new boost::asio::steady_timer(*_managerService));

  _threadHandler = [this, interval](const boost::system::error_code& error) {
    if (error || isStopping()) {
      return;
    }

    rebalanceThreads();

    _threadManager->expires_from_now(interval);
    _threadManager->async_wait(_threadHandler);
  };

  _threadManager->expires_from_now(interval);
  _threadManager->async_wait(_threadHandler);

  _lastThreadWarning.store(TRI_microtime());
}

void Scheduler::startManagerThread() {
  MUTEX_LOCKER(guard, _threadsLock);

  auto thread = new SchedulerManagerThread(this, _managerService.get());

  _threads.emplace(thread);
  thread->start();
}

void Scheduler::startNewThread() {
  MUTEX_LOCKER(guard, _threadsLock);

  auto thread = new SchedulerThread(this, _ioService.get());

  _threads.emplace(thread);
  thread->start();
}

bool Scheduler::stopThread() {
  if (_nrRunning <= _nrMinimal) {
    return false;
  }

  if (_nrRunning >= 3) {
    int64_t low = ((_nrRunning <= 4) ? 0 : (_nrRunning * 1 / 4)) - _nrBlocked;

    if (_nrBusy <= low && _nrWorking <= low) {
      return true;
    }
  }

  return false;
}

void Scheduler::threadDone(Thread* thread) {
  MUTEX_LOCKER(guard, _threadsLock);

  _threads.erase(thread);
  _deadThreads.insert(thread);
}

void Scheduler::deleteOldThreads() {
  // delete old thread objects
  std::unordered_set<Thread*> deadThreads;

  {
    MUTEX_LOCKER(guard, _threadsLock);

    if (_deadThreads.empty()) {
      return;
    }

    deadThreads.swap(_deadThreads);
  }

  for (auto thread : deadThreads) {
    try {
      delete thread;
    } catch (...) {
      LOG_TOPIC(ERR, Logger::THREADS) << "cannot delete thread";
    }
  }
}

void Scheduler::rebalanceThreads() {
  static double const MIN_WARN_INTERVAL = 10;
  static double const MIN_ERR_INTERVAL = 300;

  int64_t high = (_nrRunning <= 4) ? 1 : (_nrRunning * 11 / 16);
  int64_t working = (_nrBusy > _nrWorking) ? _nrBusy : _nrWorking;

  LOG_TOPIC(DEBUG, Logger::THREADS) << "rebalancing threads, high: " << high
                                    << ", working: " << working << " ("
                                    << infoStatus() << ")";

  if (working >= high) {
    if (_nrRunning < _nrMaximal + _nrBlocked &&
        _nrRunning < _nrRealMaximum) {   // added by Max 22.12.2016
      // otherwise we exceed the total maximum
      startNewThread();
      return;
    }
  }

  if (working >= _nrMaximal + _nrBlocked || _nrRunning < _nrMinimal) {
    double ltw = _lastThreadWarning.load();
    double now = TRI_microtime();

    if (_nrRunning >= _nrRealMaximum) {
      if (ltw - now > MIN_ERR_INTERVAL) {
        LOG_TOPIC(ERR, Logger::THREADS) << "too many threads (" << infoStatus()
                                        << ")";
        _lastThreadWarning.store(now);
      }
    } else {
      if (_nrRunning >= _nrRealMaximum * 3 / 4) {
        if (ltw - now > MIN_WARN_INTERVAL) {
          LOG_TOPIC(WARN, Logger::THREADS)
              << "number of threads is reaching a critical limit ("
              << infoStatus() << ")";
          _lastThreadWarning.store(now);
        }
      }

      LOG_TOPIC(DEBUG, Logger::THREADS) << "overloading threads ("
                                        << infoStatus() << ")";

      startNewThread();
    }
  }
}

void Scheduler::beginShutdown() {
  if (_stopping) {
    return;
  }

  _jobQueue->beginShutdown();

  _threadManager.reset();

  _managerGuard.reset();
  _managerService->stop();

  _serviceGuard.reset();
  _ioService->stop();

  // set the flag AFTER stopping the threads
  _stopping = true;
}

void Scheduler::shutdown() {
  bool done = false;

  while (!done) {
    MUTEX_LOCKER(guard, _threadsLock);
    done = _threads.empty();
  }

  deleteOldThreads();

  _managerService.reset();
  _ioService.reset();
}

void Scheduler::initializeSignalHandlers() {
#ifdef _WIN32
// Windows does not support POSIX signal handling
#else
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigfillset(&action.sa_mask);

  // ignore broken pipes
  action.sa_handler = SIG_IGN;

  int res = sigaction(SIGPIPE, &action, 0);

  if (res < 0) {
    LOG(ERR) << "cannot initialize signal handlers for pipe";
  }
#endif
}
<|endoftext|>