<commit_before>#include "common.hpp"

#include "bini322.hpp"
#include "classical.hpp"
#include "fast333.hpp"
#include "grey-fast234.hpp"
#include "grey-fast243.hpp"
#include "grey-fast322.hpp"
#include "grey-fast324.hpp"
#include "grey-fast332.hpp"
#include "grey-fast333.hpp"
#include "grey-fast342.hpp"
#include "grey-fast423.hpp"
#include "grey-fast432.hpp"
#include "grey-fast433.hpp"
#include "hk332.hpp"
#include "strassen.hpp"

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

#include <algorithm>
#include <chrono>
#include <random>
#include <vector>

enum {
  BINI332,
  CLASSICAL,
  GREY322,
  GREY332,
  GREY333,
  GREY432,
  GREY423,
  GREY324,
  GREY342,
  GREY234,
  GREY243,
  GREY433,
  HK332,
};

// Run a single benchmark for multiplying m x k x n with numsteps of recursion.
// To just call GEMM, set numsteps to zero.
// The median of five trials is printed to std::cout.
// If run_check is true, then it also
void SingleBenchmark(int m, int k, int n, int numsteps, int algorithm, bool run_check=false) {
    Matrix<double> A(m, k);
    Matrix<double> B(k, n);
    Matrix<double> C1(m, n);
    for (int j = 0; j < A.n(); ++j) {
        for (int i = 0; i < A.m(); ++i) {
            A.data()[i + j * A.stride()] = ((double) rand() / RAND_MAX) * 1024;
	}
    }
    for (int j = 0; j < B.n(); ++j) {
        for (int i = 0; i < B.m(); ++i) {
	    B.data()[i + j * B.stride()] = ((double) rand() / RAND_MAX) * 1024;
	}
    }
    // Run a set number of trials and pick the median time.
    int num_trials = 5;
    std::vector<double> times(num_trials);
    for (int trial = 0; trial < num_trials; ++trial) {
        auto t1 = std::chrono::high_resolution_clock::now();
	switch (algorithm) {
	case BINI332:
	  bini322::FastMatmul(A, B, C1, numsteps);
	  break;
	case CLASSICAL:
	  classical::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY322:
	  grey322_11_50::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY332:
	  grey332_15_103::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY333:
	  grey333_23_152::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY432:
	  grey432_20_144::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY423:
	  grey423_20_144::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY324:
	  grey324_20_144::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY342:
	  grey342_20_144::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY234:
	  grey234_20_144::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY243:
	  grey324_20_144::FastMatmul(A, B, C1, numsteps);
	  break;
	case GREY433:
	  grey433_29_234::FastMatmul(A, B, C1, numsteps);
	  break;
	case HK332:
	  hk332_2::FastMatmul(A, B, C1, numsteps);
	  break;
	default:
	  std::cout << "Unknown algorithm type!" << std::endl;
	}
	auto t2 = std::chrono::high_resolution_clock::now();
	times[trial] = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count();
    }
    // Spit out the median time
    std::sort(times.begin(), times.end());
    size_t ind = num_trials / 2 + 1;
    std::cout << " " << m << " " << k << " " << n << " "
	      << numsteps << " " << times[ind] << " "
	      << "; ..." << std::endl;

    if (run_check) {
	// Test for correctness.
        Matrix<double> C2(m, n);
	Gemm(A, B, C2);
	std::cout << "Maximum relative difference: " << MaxRelativeDiff(C1, C2) << std::endl;
    }
}

// Runs a set of benchmarks.
void BenchmarkSet(std::vector<int>& m_vals, std::vector<int>& k_vals,
		  std::vector<int>& n_vals, std::vector<int>& numsteps,
		  bool run_check=false) {
    assert(m_vals.size() == k_vals.size() && k_vals.size() == n_vals.size());
    for (int i = 0; i < m_vals.size(); ++i) {
      for (int curr_numsteps : numsteps) {
	SingleBenchmark(m_vals[i], k_vals[i], n_vals[i], curr_numsteps, run_check);
      }
    }
}

int main(int argc, char **argv) {
    std::vector<int> numsteps = {0, 1};
    std::vector<int> m_vals = {1200, 2100};
    BenchmarkSet(m_vals, m_vals, m_vals, numsteps);
}
<commit_msg>benchmark figured out<commit_after>#include "common.hpp"

#include "bini322.hpp"
#include "classical.hpp"
#include "fast333.hpp"
#include "grey-fast234.hpp"
#include "grey-fast243.hpp"
#include "grey-fast322.hpp"
#include "grey-fast324.hpp"
#include "grey-fast332.hpp"
#include "grey-fast333.hpp"
#include "grey-fast342.hpp"
#include "grey-fast423.hpp"
#include "grey-fast432.hpp"
#include "grey-fast433.hpp"
#include "hk332.hpp"
#include "strassen.hpp"

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

#include <algorithm>
#include <chrono>
#include <random>
#include <vector>

enum {
  BINI332,
  CLASSICAL,
  GREY322,
  GREY332,
  GREY333,
  GREY432,
  GREY423,
  GREY324,
  GREY342,
  GREY234,
  GREY243,
  GREY433,
  HK332,
};

// Run a single benchmark for multiplying m x k x n with numsteps of recursion.
// To just call GEMM, set numsteps to zero.
// The median of five trials is printed to std::cout.
// If run_check is true, then it also
void SingleBenchmark(int m, int k, int n, int numsteps, int algorithm, bool run_check=false) {
  Matrix<double> A(m, k);
  Matrix<double> B(k, n);
  Matrix<double> C1(m, n);
  for (int j = 0; j < A.n(); ++j) {
    for (int i = 0; i < A.m(); ++i) {
      A.data()[i + j * A.stride()] = ((double) rand() / RAND_MAX) * 1024;
    }
  }
  for (int j = 0; j < B.n(); ++j) {
    for (int i = 0; i < B.m(); ++i) {
      B.data()[i + j * B.stride()] = ((double) rand() / RAND_MAX) * 1024;
    }
  }
  // Run a set number of trials and pick the median time.
  int num_trials = 5;
  std::vector<double> times(num_trials);
  for (int trial = 0; trial < num_trials; ++trial) {
    auto t1 = std::chrono::high_resolution_clock::now();
    switch (algorithm) {
    case BINI332:
      bini322::FastMatmul(A, B, C1, numsteps);
      break;
    case CLASSICAL:
      classical::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY322:
      grey322_11_50::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY332:
      grey332_15_103::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY333:
      grey333_23_152::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY432:
      grey432_20_144::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY423:
      grey423_20_144::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY324:
      grey324_20_144::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY342:
      grey342_20_144::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY234:
      grey234_20_144::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY243:
      grey324_20_144::FastMatmul(A, B, C1, numsteps);
      break;
    case GREY433:
      grey433_29_234::FastMatmul(A, B, C1, numsteps);
      break;
    case HK332:
      hk332_2::FastMatmul(A, B, C1, numsteps);
      break;
    default:
      std::cout << "Unknown algorithm type!" << std::endl;
    }
    auto t2 = std::chrono::high_resolution_clock::now();
    times[trial] = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count();
  }
  // Spit out the median time
  std::sort(times.begin(), times.end());
  size_t ind = num_trials / 2 + 1;
  std::cout << " " << m << " " << k << " " << n << " "
            << numsteps << " " << times[ind] << " "
            << "; ..." << std::endl;

  if (run_check) {
    // Test for correctness.
    Matrix<double> C2(m, n);
    Gemm(A, B, C2);
    std::cout << "Maximum relative difference: " << MaxRelativeDiff(C1, C2) << std::endl;
  }
}

// Runs a set of benchmarks.
void BenchmarkSet(std::vector<int>& m_vals, std::vector<int>& k_vals,
                  std::vector<int>& n_vals, std::vector<int>& numsteps,
                  int algorithm, bool run_check=false) {
  assert(m_vals.size() == k_vals.size() && k_vals.size() == n_vals.size());
  for (int i = 0; i < m_vals.size(); ++i) {
    for (int curr_numsteps : numsteps) {
      SingleBenchmark(m_vals[i], k_vals[i], n_vals[i], curr_numsteps, algorithm, run_check);
    }
  }
}

int main(int argc, char **argv) {
  std::vector<int> numsteps = {0, 1};
  std::vector<int> m_vals = {1200, 2100};
  BenchmarkSet(m_vals, m_vals, m_vals, numsteps, GREY333);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 - 2022, Intel Corporation
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "config.h"

#include "SharedMemoryImp.hpp"

#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <glob.h>

#include <iostream>
#include <sstream>
#include <utility>

#include "geopm_time.h"
#include "geopm/Exception.hpp"
#include "geopm/Helper.hpp"

namespace geopm
{
    void SharedMemory::cleanup_shmem(void)
    {
        std::string pattern = "/geopm-shm-" + std::to_string(geteuid()) + "-*";
        pattern = SharedMemoryImp::construct_shm_path(pattern);
        glob_t globbuf;
        int err = glob(pattern.c_str(), 0, nullptr, &globbuf);
        if (err == 0) {
            for (size_t path_idx = 0; path_idx != globbuf.gl_pathc; ++path_idx) {
                int unlink_err = ::unlink(globbuf.gl_pathv[path_idx]);
                if (unlink_err != 0) {
#ifdef GEOPM_DEBUG
                    std::cerr << "Warning: <geopm> SharedMemory:cleanup_shmem(): unable to unlink file: " << globbuf.gl_pathv[path_idx] << "\n";
#endif
                }
            }
            globfree(&globbuf);
        }
    }

    /// @brief Size of the lock in memory.
    static constexpr size_t M_LOCK_SIZE = geopm::hardware_destructive_interference_size;
    static_assert(sizeof(pthread_mutex_t) <= M_LOCK_SIZE, "M_LOCK_SIZE not large enough for mutex type");

    static void setup_mutex(pthread_mutex_t *lock)
    {
        pthread_mutexattr_t lock_attr;
        int err = pthread_mutexattr_init(&lock_attr);
        if (err) {
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_ERRORCHECK);
        if (err) {
            (void) pthread_mutexattr_destroy(&lock_attr);
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED);
        if (err) {
            (void) pthread_mutexattr_destroy(&lock_attr);
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutex_init(lock, &lock_attr);
        if (err) {
            (void) pthread_mutexattr_destroy(&lock_attr);
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutexattr_destroy(&lock_attr);
        if (err) {
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
    }

    std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner(const std::string &shm_key, size_t size)
    {
        std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>();
        owner->create_memory_region(shm_key, size, false);
        return std::unique_ptr<SharedMemory>(std::move(owner));
    }

    std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner_secure(const std::string &shm_key, size_t size)
    {
        std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>();
        owner->create_memory_region(shm_key, size, true);
        return std::unique_ptr<SharedMemory>(std::move(owner));
    }

    std::unique_ptr<SharedMemory> SharedMemory::make_unique_user(const std::string &shm_key, unsigned int timeout)
    {
        std::unique_ptr<SharedMemoryImp> user = geopm::make_unique<SharedMemoryImp>();
        user->attach_memory_region(shm_key, timeout);
        return std::unique_ptr<SharedMemory>(std::move(user));
    }

    SharedMemoryImp::SharedMemoryImp()
        : m_size(0)
        , m_ptr(NULL)
        , m_is_linked(false)
        , m_do_unlink_check(false)
    {

    }

    void SharedMemoryImp::create_memory_region(const std::string &shm_key, size_t size, bool is_secure)
    {
        if (!size) {
            throw Exception("SharedMemoryImp: Cannot create shared memory region of zero size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        m_shm_key = shm_key;
        m_shm_path = construct_shm_path(shm_key);
        m_size = size + M_LOCK_SIZE;

        mode_t old_mask = umask(0);
        int shm_id = 0;
        if (is_secure) {
            shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL,
                          S_IRUSR | S_IWUSR);
        }
        else {
            shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL,
                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
                          S_IROTH | S_IWOTH);
        }
        if (shm_id < 0) {
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not open shared memory with key " << m_shm_key;
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        int err = ftruncate(shm_id, m_size);
        if (err) {
            (void) close(shm_id);
            (void) ::unlink(m_shm_path.c_str());
            (void) umask(old_mask);
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not extend shared memory to size " << m_size;
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);
        if (m_ptr == MAP_FAILED) {
            (void) close(shm_id);
            (void) ::unlink(m_shm_path.c_str());
            (void) umask(old_mask);
            throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = close(shm_id);
        if (err) {
            (void) umask(old_mask);
            throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        umask(old_mask);

        setup_mutex((pthread_mutex_t*)m_ptr);

        m_is_linked = true;
        m_do_unlink_check = false;
    }

    SharedMemoryImp::~SharedMemoryImp()
    {
        if (m_ptr != nullptr) {
            if (munmap(m_ptr, m_size)) {
#ifdef GEOPM_DEBUG
                std::cerr << "Warning: <geopm> SharedMemoryImp: Could not unmap pointer" << std::endl;
#endif
            }
        }
    }

    void SharedMemoryImp::unlink(void)
    {
        // ProfileSampler destructor calls unlink, so don't throw if constructed
        // as owner
        if (m_is_linked) {
            int err = ::unlink(m_shm_path.c_str());
            if (err && m_do_unlink_check) {
                std::ostringstream tmp_str;
                tmp_str << "SharedMemoryImp::unlink() Call to unlink(" << m_shm_path  << ") failed";
                throw Exception(tmp_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
            m_is_linked = false;
        }
    }

    void *SharedMemoryImp::pointer(void) const
    {
        return (char*)m_ptr + M_LOCK_SIZE;
    }

    std::string SharedMemoryImp::key(void) const
    {
        return m_shm_key;
    }

    size_t SharedMemoryImp::size(void) const
    {
        return m_size - M_LOCK_SIZE;
    }

    std::unique_ptr<SharedMemoryScopedLock> SharedMemoryImp::get_scoped_lock(void)
    {
        return geopm::make_unique<SharedMemoryScopedLock>((pthread_mutex_t*)m_ptr);
    }

    void SharedMemoryImp::attach_memory_region(const std::string &shm_key, unsigned int timeout)
    {
        m_shm_key = shm_key;
        m_shm_path = construct_shm_path(shm_key);
        m_is_linked = false;

        int shm_id = -1;
        struct stat stat_struct;
        int err = 0;

        if (!timeout) {
            shm_id = open(m_shm_path.c_str(), O_RDWR, 0);
            if (shm_id < 0) {
                std::ostringstream ex_str;
                ex_str << "SharedMemoryImp: Could not open shared memory with key \""  <<  shm_key << "\"";
                throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
            err = fstat(shm_id, &stat_struct);
            if (err) {
                (void) close(shm_id);
                std::ostringstream ex_str;
                ex_str << "SharedMemoryImp: fstat() error on shared memory with key \"" << shm_key << "\"";
                throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
            m_size = stat_struct.st_size;

            m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);
            if (m_ptr == MAP_FAILED) {
                (void) close(shm_id);
                throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
        }
        else {
            struct geopm_time_s begin_time;
            geopm_time(&begin_time);
            while (shm_id < 0 && geopm_time_since(&begin_time) < (double)timeout) {
                shm_id = open(m_shm_path.c_str(), O_RDWR, 0);
            }
            if (shm_id < 0) {
                std::ostringstream ex_str;
                ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << shm_key << "\"";
                throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }

            while (!m_size && geopm_time_since(&begin_time) < (double)timeout) {
                err = fstat(shm_id, &stat_struct);
                if (!err) {
                    m_size = stat_struct.st_size;
                }
            }
            if (!m_size) {
                (void) close(shm_id);
                throw Exception("SharedMemoryImp: Opened shared memory region, but it is zero length", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }

            m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);
            if (m_ptr == MAP_FAILED) {
                (void) close(shm_id);
                throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
        }

        err = close(shm_id);
        if (err) {
            throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        m_is_linked = true;
        m_do_unlink_check = true;
    }

    void SharedMemoryImp::chown(const unsigned int uid, const unsigned int gid) const {
        int err = 0;
        int shm_id = -1;
        if (m_is_linked) {
            shm_id = open(m_shm_path.c_str(), O_RDWR, 0);
        }
        else {
            throw Exception("SharedMemoryImp: Cannot chown shm that has been unlinked.", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        if (shm_id < 0) {
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not open shared memory with key \""  <<  m_shm_key << "\"";
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        err = fchown(shm_id, uid, gid);
        if (err) {
            (void) close(shm_id);
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not chown shmem with key (" << m_shm_key
                   << ") to UID (" << std::to_string(uid)
                   << "), GID (" << std::to_string(gid) + ")";
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        err = close(shm_id);
        if (err) {
            throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
    }

    std::string SharedMemoryImp::construct_shm_path(const std::string &key)
    {
        std::string path;
        if (key.length() > 1 && key[0] == '/' &&
            key.find('/', 1) == std::string::npos) {
            // shmem key

            // pam_systemd/logind enabled?
            std::string usr_run_dir = "/run/user/" +
                                      std::to_string(getuid());
            if (access(usr_run_dir.c_str(), F_OK) == 0) {
                path = usr_run_dir + key;
            }
            else {
                path = "/dev/shm" + key;
            }
        } else {
            // regular file path
            path = key;
        }

        return path;
    }
}
<commit_msg>Avoid memory leak if glob fails<commit_after>/*
 * Copyright (c) 2015 - 2022, Intel Corporation
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "config.h"

#include "SharedMemoryImp.hpp"

#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <glob.h>

#include <iostream>
#include <sstream>
#include <utility>

#include "geopm_time.h"
#include "geopm/Exception.hpp"
#include "geopm/Helper.hpp"

namespace geopm
{
    void SharedMemory::cleanup_shmem(void)
    {
        std::string pattern = "/geopm-shm-" + std::to_string(geteuid()) + "-*";
        pattern = SharedMemoryImp::construct_shm_path(pattern);
        glob_t globbuf;
        int err = glob(pattern.c_str(), 0, nullptr, &globbuf);
        if (err == 0) {
            for (size_t path_idx = 0; path_idx != globbuf.gl_pathc; ++path_idx) {
                int unlink_err = ::unlink(globbuf.gl_pathv[path_idx]);
                if (unlink_err != 0) {
#ifdef GEOPM_DEBUG
                    std::cerr << "Warning: <geopm> SharedMemory:cleanup_shmem(): unable to unlink file: " << globbuf.gl_pathv[path_idx] << "\n";
#endif
                }
            }
        }
        globfree(&globbuf);
    }

    /// @brief Size of the lock in memory.
    static constexpr size_t M_LOCK_SIZE = geopm::hardware_destructive_interference_size;
    static_assert(sizeof(pthread_mutex_t) <= M_LOCK_SIZE, "M_LOCK_SIZE not large enough for mutex type");

    static void setup_mutex(pthread_mutex_t *lock)
    {
        pthread_mutexattr_t lock_attr;
        int err = pthread_mutexattr_init(&lock_attr);
        if (err) {
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_ERRORCHECK);
        if (err) {
            (void) pthread_mutexattr_destroy(&lock_attr);
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED);
        if (err) {
            (void) pthread_mutexattr_destroy(&lock_attr);
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutex_init(lock, &lock_attr);
        if (err) {
            (void) pthread_mutexattr_destroy(&lock_attr);
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = pthread_mutexattr_destroy(&lock_attr);
        if (err) {
            throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
    }

    std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner(const std::string &shm_key, size_t size)
    {
        std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>();
        owner->create_memory_region(shm_key, size, false);
        return std::unique_ptr<SharedMemory>(std::move(owner));
    }

    std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner_secure(const std::string &shm_key, size_t size)
    {
        std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>();
        owner->create_memory_region(shm_key, size, true);
        return std::unique_ptr<SharedMemory>(std::move(owner));
    }

    std::unique_ptr<SharedMemory> SharedMemory::make_unique_user(const std::string &shm_key, unsigned int timeout)
    {
        std::unique_ptr<SharedMemoryImp> user = geopm::make_unique<SharedMemoryImp>();
        user->attach_memory_region(shm_key, timeout);
        return std::unique_ptr<SharedMemory>(std::move(user));
    }

    SharedMemoryImp::SharedMemoryImp()
        : m_size(0)
        , m_ptr(NULL)
        , m_is_linked(false)
        , m_do_unlink_check(false)
    {

    }

    void SharedMemoryImp::create_memory_region(const std::string &shm_key, size_t size, bool is_secure)
    {
        if (!size) {
            throw Exception("SharedMemoryImp: Cannot create shared memory region of zero size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        m_shm_key = shm_key;
        m_shm_path = construct_shm_path(shm_key);
        m_size = size + M_LOCK_SIZE;

        mode_t old_mask = umask(0);
        int shm_id = 0;
        if (is_secure) {
            shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL,
                          S_IRUSR | S_IWUSR);
        }
        else {
            shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL,
                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
                          S_IROTH | S_IWOTH);
        }
        if (shm_id < 0) {
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not open shared memory with key " << m_shm_key;
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        int err = ftruncate(shm_id, m_size);
        if (err) {
            (void) close(shm_id);
            (void) ::unlink(m_shm_path.c_str());
            (void) umask(old_mask);
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not extend shared memory to size " << m_size;
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);
        if (m_ptr == MAP_FAILED) {
            (void) close(shm_id);
            (void) ::unlink(m_shm_path.c_str());
            (void) umask(old_mask);
            throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        err = close(shm_id);
        if (err) {
            (void) umask(old_mask);
            throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        umask(old_mask);

        setup_mutex((pthread_mutex_t*)m_ptr);

        m_is_linked = true;
        m_do_unlink_check = false;
    }

    SharedMemoryImp::~SharedMemoryImp()
    {
        if (m_ptr != nullptr) {
            if (munmap(m_ptr, m_size)) {
#ifdef GEOPM_DEBUG
                std::cerr << "Warning: <geopm> SharedMemoryImp: Could not unmap pointer" << std::endl;
#endif
            }
        }
    }

    void SharedMemoryImp::unlink(void)
    {
        // ProfileSampler destructor calls unlink, so don't throw if constructed
        // as owner
        if (m_is_linked) {
            int err = ::unlink(m_shm_path.c_str());
            if (err && m_do_unlink_check) {
                std::ostringstream tmp_str;
                tmp_str << "SharedMemoryImp::unlink() Call to unlink(" << m_shm_path  << ") failed";
                throw Exception(tmp_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
            m_is_linked = false;
        }
    }

    void *SharedMemoryImp::pointer(void) const
    {
        return (char*)m_ptr + M_LOCK_SIZE;
    }

    std::string SharedMemoryImp::key(void) const
    {
        return m_shm_key;
    }

    size_t SharedMemoryImp::size(void) const
    {
        return m_size - M_LOCK_SIZE;
    }

    std::unique_ptr<SharedMemoryScopedLock> SharedMemoryImp::get_scoped_lock(void)
    {
        return geopm::make_unique<SharedMemoryScopedLock>((pthread_mutex_t*)m_ptr);
    }

    void SharedMemoryImp::attach_memory_region(const std::string &shm_key, unsigned int timeout)
    {
        m_shm_key = shm_key;
        m_shm_path = construct_shm_path(shm_key);
        m_is_linked = false;

        int shm_id = -1;
        struct stat stat_struct;
        int err = 0;

        if (!timeout) {
            shm_id = open(m_shm_path.c_str(), O_RDWR, 0);
            if (shm_id < 0) {
                std::ostringstream ex_str;
                ex_str << "SharedMemoryImp: Could not open shared memory with key \""  <<  shm_key << "\"";
                throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
            err = fstat(shm_id, &stat_struct);
            if (err) {
                (void) close(shm_id);
                std::ostringstream ex_str;
                ex_str << "SharedMemoryImp: fstat() error on shared memory with key \"" << shm_key << "\"";
                throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
            m_size = stat_struct.st_size;

            m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);
            if (m_ptr == MAP_FAILED) {
                (void) close(shm_id);
                throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
        }
        else {
            struct geopm_time_s begin_time;
            geopm_time(&begin_time);
            while (shm_id < 0 && geopm_time_since(&begin_time) < (double)timeout) {
                shm_id = open(m_shm_path.c_str(), O_RDWR, 0);
            }
            if (shm_id < 0) {
                std::ostringstream ex_str;
                ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << shm_key << "\"";
                throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }

            while (!m_size && geopm_time_since(&begin_time) < (double)timeout) {
                err = fstat(shm_id, &stat_struct);
                if (!err) {
                    m_size = stat_struct.st_size;
                }
            }
            if (!m_size) {
                (void) close(shm_id);
                throw Exception("SharedMemoryImp: Opened shared memory region, but it is zero length", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }

            m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);
            if (m_ptr == MAP_FAILED) {
                (void) close(shm_id);
                throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
            }
        }

        err = close(shm_id);
        if (err) {
            throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        m_is_linked = true;
        m_do_unlink_check = true;
    }

    void SharedMemoryImp::chown(const unsigned int uid, const unsigned int gid) const {
        int err = 0;
        int shm_id = -1;
        if (m_is_linked) {
            shm_id = open(m_shm_path.c_str(), O_RDWR, 0);
        }
        else {
            throw Exception("SharedMemoryImp: Cannot chown shm that has been unlinked.", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        if (shm_id < 0) {
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not open shared memory with key \""  <<  m_shm_key << "\"";
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        err = fchown(shm_id, uid, gid);
        if (err) {
            (void) close(shm_id);
            std::ostringstream ex_str;
            ex_str << "SharedMemoryImp: Could not chown shmem with key (" << m_shm_key
                   << ") to UID (" << std::to_string(uid)
                   << "), GID (" << std::to_string(gid) + ")";
            throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        err = close(shm_id);
        if (err) {
            throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
    }

    std::string SharedMemoryImp::construct_shm_path(const std::string &key)
    {
        std::string path;
        if (key.length() > 1 && key[0] == '/' &&
            key.find('/', 1) == std::string::npos) {
            // shmem key

            // pam_systemd/logind enabled?
            std::string usr_run_dir = "/run/user/" +
                                      std::to_string(getuid());
            if (access(usr_run_dir.c_str(), F_OK) == 0) {
                path = usr_run_dir + key;
            }
            else {
                path = "/dev/shm" + key;
            }
        } else {
            // regular file path
            path = key;
        }

        return path;
    }
}
<|endoftext|>


<commit_before>#include "GameCtrl.h"

int main() {
    auto game = GameCtrl::getInstance();

    // Set FPS. Default is 60.0
    game->setFPS(60.0);

    // Set whether to enable the snake AI. Default is true.
    game->setEnableAI(true);

    // Set whether to use a hamiltonian cycle to guide the AI. Default is true.
    game->setEnableHamilton(true);

    // Set the interval time between each snake's movement. Default is 30 ms.
    // To play classic snake game, set to 150 ms is perfect.
    game->setMoveInterval(30);

    // Set whether to record the snake's movements to file. Default is true.
    // The movements will be written to a file named "movements.txt".
    game->setRecordMovements(true);

    // Set whether to run the test program. Default is false.
    // You can select different testing methods by modifying GameCtrl::test().
    game->setRunTest(false);

    // Set map's size(including boundaries). Default is 10*10. Minimum is 5*5.
    game->setMapRow(10);
    game->setMapCol(10);

    return game->run();
}
<commit_msg>Create menu GUI #2<commit_after>#include "GameCtrl.h"

char title[16][30]=
{
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,1,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,0,0,1,0,0,1,0,1,1,1,1,1,0},
	{0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,0,0},
	{0,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,0,0,1,1,0,0,0,1,1,1,1,1,0},
	{0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,0,0},
	{0,1,1,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,0,1,0,0,1,0,1,1,1,1,1,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,0,0,1,1,1,1,1,0},
	{0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0},
	{0,0,1,0,0,1,1,0,0,1,1,1,1,0,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0},
	{0,0,1,1,1,1,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,1,0,0,1,0,0,0,0,0},
	{0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,1,1,1,1,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}

};

int main() {
	int menu;
	printf("\n");
	for(int x=0;x<16;x++){
		printf("\t");
		for(int y=0;y<30;y++)
		{
			if(title[x][y] == 1)
			{
				printf("");
			}
			if(title[x][y] == 0)
			{
				printf("");
			}
		}
		printf("\n");
	}
	printf("\t------------------------------------------------------------\n");
	printf("\t\t\t\t<MENU>\n");
	printf("\t\t\t     1.Snake Game\n");
	printf("\t\t\t     =>Input Menu Number : ");
	scanf("%d",&menu);
	if(menu==1)
	{
    auto game = GameCtrl::getInstance();

    // Set FPS. Default is 60.0
    game->setFPS(60.0);

    // Set whether to enable the snake AI. Default is true.
    game->setEnableAI(true);

    // Set whether to use a hamiltonian cycle to guide the AI. Default is true.
    game->setEnableHamilton(true);

    // Set the interval time between each snake's movement. Default is 30 ms.
    // To play classic snake game, set to 150 ms is perfect.
    game->setMoveInterval(30);

    // Set whether to record the snake's movements to file. Default is true.
    // The movements will be written to a file named "movements.txt".
    game->setRecordMovements(true);

    // Set whether to run the test program. Default is false.
    // You can select different testing methods by modifying GameCtrl::test().
    game->setRunTest(false);

    // Set map's size(including boundaries). Default is 10*10. Minimum is 5*5.
    game->setMapRow(10);
    game->setMapCol(10);

    return game->run();
	}
	else return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 New Designs Unlimited, LLC
 * Opensource Automated License Plate Recognition [http://www.openalpr.com]
 *
 * This file is part of OpenAlpr.
 *
 * OpenAlpr is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License
 * version 3 as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdio>
#include <sstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <signal.h>

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include "tclap/CmdLine.h"
#include "support/filesystem.h"
#include "support/timing.h"
#include "videobuffer.h"
#include "alpr.h"

const std::string MAIN_WINDOW_NAME = "ALPR main window";

const bool SAVE_LAST_VIDEO_STILL = false;
const std::string LAST_VIDEO_STILL_LOCATION = "/tmp/laststill.jpg";

/** Function Headers */
bool detectandshow(Alpr* alpr, cv::Mat frame, std::string region, bool writeJson);
void sighandler(int sig);

bool measureProcessingTime = false;

// This boolean is set to false when the user hits terminates (e.g., CTRL+C )
// so we can end infinite loops for things like video processing.
bool program_active = true;

int main( int argc, const char** argv )
{
  std::string filename;
  std::string configFile = "";
  bool outputJson = false;
  int seektoms = 0;
  bool detectRegion = false;
  std::string templateRegion;
  std::string country;
  int topn;

  TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion());

  TCLAP::UnlabeledValueArg<std::string>  fileArg( "image_file", "Image containing license plates", false, "", "image_file_path"  );

  TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe).  Default=us",false, "us" ,"country_code");
  TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specied millisecond in a video file. Default=0",false, 0 ,"integer_ms");
  TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file");
  TCLAP::ValueArg<std::string> templateRegionArg("t","template_region","Attempt to match the plate number against a region template (e.g., md for Maryland, ca for California)",false, "" ,"region code");
  TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return.  Default=10",false, 10 ,"topN");

  TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format.  Default=off", cmd, false);
  TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image.  Default=off", cmd, false);
  TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates.  Default=off", cmd, false);

  try
  {
    cmd.add( templateRegionArg );
    cmd.add( seekToMsArg );
    cmd.add( topNArg );
    cmd.add( configFileArg );
    cmd.add( fileArg );
    cmd.add( countryCodeArg );

    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    filename = fileArg.getValue();

    country = countryCodeArg.getValue();
    seektoms = seekToMsArg.getValue();
    outputJson = jsonSwitch.getValue();
    configFile = configFileArg.getValue();
    detectRegion = detectRegionSwitch.getValue();
    templateRegion = templateRegionArg.getValue();
    topn = topNArg.getValue();
    measureProcessingTime = clockSwitch.getValue();
  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }

  struct sigaction sigIntHandler;

  sigIntHandler.sa_handler = sighandler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;

  sigaction(SIGHUP, &sigIntHandler, NULL);
  sigaction(SIGINT, &sigIntHandler, NULL);
  sigaction(SIGQUIT, &sigIntHandler, NULL);
  sigaction(SIGKILL, &sigIntHandler, NULL);
  sigaction(SIGTERM, &sigIntHandler, NULL);
  //sigaction(SIGABRT, &sigIntHandler, NULL);

  cv::Mat frame;

  Alpr alpr(country, configFile);
  alpr.setTopN(topn);

  if (detectRegion)
    alpr.setDetectRegion(detectRegion);

  if (templateRegion.empty() == false)
    alpr.setDefaultRegion(templateRegion);

  if (alpr.isLoaded() == false)
  {
    std::cerr << "Error loading OpenALPR" << std::endl;
    return 1;
  }

  if (filename.empty())
  {
    std::string filename;
    while (std::getline(std::cin, filename))
    {
      if (fileExists(filename.c_str()))
      {
	frame = cv::imread( filename );
	detectandshow( &alpr, frame, "", outputJson);
      }
      else
      {
	std::cerr << "Image file not found: " << filename << std::endl;
      }

    }
  }
  else if (filename == "webcam")
  {
    int framenum = 0;
    cv::VideoCapture cap(0);
    if (!cap.isOpened())
    {
      std::cout << "Error opening webcam" << std::endl;
      return 1;
    }

    while (cap.read(frame))
    {
      detectandshow(&alpr, frame, "", outputJson);
      cv::waitKey(1);
      framenum++;
    }
  }
  else if (startsWith(filename, "http://") || startsWith(filename, "https://"))
  {
    int framenum = 0;

    VideoBuffer videoBuffer;

    videoBuffer.connect(filename, 5);

    cv::Mat latestFrame;

    while (program_active)
    {
      int response = videoBuffer.getLatestFrame(&latestFrame);

      if (response != -1)
      {
        detectandshow( &alpr, latestFrame, "", outputJson);
      }

      cv::waitKey(10);
    }

    videoBuffer.disconnect();

    std::cout << "Video processing ended" << std::endl;
  }
  else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") ||
	   hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg"))
  {
    if (fileExists(filename.c_str()))
    {
      int framenum = 0;

      cv::VideoCapture cap=cv::VideoCapture();
      cap.open(filename);
      cap.set(CV_CAP_PROP_POS_MSEC, seektoms);

      while (cap.read(frame))
      {
        if (SAVE_LAST_VIDEO_STILL)
        {
          cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame);
        }
        std::cout << "Frame: " << framenum << std::endl;

        detectandshow( &alpr, frame, "", outputJson);
        //create a 1ms delay
        cv::waitKey(1);
        framenum++;
      }
    }
    else
    {
      std::cerr << "Video file not found: " << filename << std::endl;
    }
  }
  else if (hasEndingInsensitive(filename, ".png") || hasEndingInsensitive(filename, ".jpg") ||
	   hasEndingInsensitive(filename, ".jpeg") || hasEndingInsensitive(filename, ".gif"))
  {
    if (fileExists(filename.c_str()))
    {
      frame = cv::imread( filename );

      detectandshow( &alpr, frame, "", outputJson);
    }
    else
    {
      std::cerr << "Image file not found: " << filename << std::endl;
    }
  }
  else if (DirectoryExists(filename.c_str()))
  {
    std::vector<std::string> files = getFilesInDir(filename.c_str());

    std::sort( files.begin(), files.end(), stringCompare );

    for (int i = 0; i< files.size(); i++)
    {
      if (hasEndingInsensitive(files[i], ".jpg") || hasEndingInsensitive(files[i], ".png"))
      {
        std::string fullpath = filename + "/" + files[i];
        std::cout << fullpath << std::endl;
        frame = cv::imread( fullpath.c_str() );
        if (detectandshow( &alpr, frame, "", outputJson))
        {
          //while ((char) cv::waitKey(50) != 'c') { }
        }
        else
        {
          //cv::waitKey(50);
        }
      }
    }
  }
  else
  {
    std::cerr << "Unknown file type" << std::endl;
    return 1;
  }

  return 0;
}

void sighandler(int sig)
{
  program_active = false;
  //std::cout << "Sig handler caught " << sig << std::endl;
}

bool detectandshow( Alpr* alpr, cv::Mat frame, std::string region, bool writeJson)
{
  std::vector<uchar> buffer;
  cv::imencode(".bmp", frame, buffer );

  timespec startTime;
  getTime(&startTime);

  std::vector<AlprResult> results = alpr->recognize(buffer);

  if (writeJson)
  {
    std::cout << alpr->toJson(results) << std::endl;
  }
  else
  {
    for (int i = 0; i < results.size(); i++)
    {
      std::cout << "plate" << i << ": " << results[i].result_count << " results -- Processing Time = " << results[i].processing_time_ms << "ms." << std::endl;

      for (int k = 0; k < results[i].topNPlates.size(); k++)
      {
        std::cout << "    - " << results[i].topNPlates[k].characters << "\t confidence: " << results[i].topNPlates[k].overall_confidence << "\t template_match: " << results[i].topNPlates[k].matches_template << std::endl;
      }
    }
  }

  timespec endTime;
  getTime(&endTime);
  if (measureProcessingTime)
    std::cout << "Total Time to process image: " << diffclock(startTime, endTime) << "ms." << std::endl;

  return results.size() > 0;
}
<commit_msg>Removed unnecessary signal handlers<commit_after>/*
 * Copyright (c) 2013 New Designs Unlimited, LLC
 * Opensource Automated License Plate Recognition [http://www.openalpr.com]
 *
 * This file is part of OpenAlpr.
 *
 * OpenAlpr is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License
 * version 3 as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdio>
#include <sstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <signal.h>

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include "tclap/CmdLine.h"
#include "support/filesystem.h"
#include "support/timing.h"
#include "videobuffer.h"
#include "alpr.h"

const std::string MAIN_WINDOW_NAME = "ALPR main window";

const bool SAVE_LAST_VIDEO_STILL = false;
const std::string LAST_VIDEO_STILL_LOCATION = "/tmp/laststill.jpg";

/** Function Headers */
bool detectandshow(Alpr* alpr, cv::Mat frame, std::string region, bool writeJson);
void sighandler(int sig);

bool measureProcessingTime = false;

// This boolean is set to false when the user hits terminates (e.g., CTRL+C )
// so we can end infinite loops for things like video processing.
bool program_active = true;

int main( int argc, const char** argv )
{
  std::string filename;
  std::string configFile = "";
  bool outputJson = false;
  int seektoms = 0;
  bool detectRegion = false;
  std::string templateRegion;
  std::string country;
  int topn;

  TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion());

  TCLAP::UnlabeledValueArg<std::string>  fileArg( "image_file", "Image containing license plates", false, "", "image_file_path"  );

  TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe).  Default=us",false, "us" ,"country_code");
  TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specied millisecond in a video file. Default=0",false, 0 ,"integer_ms");
  TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file");
  TCLAP::ValueArg<std::string> templateRegionArg("t","template_region","Attempt to match the plate number against a region template (e.g., md for Maryland, ca for California)",false, "" ,"region code");
  TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return.  Default=10",false, 10 ,"topN");

  TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format.  Default=off", cmd, false);
  TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image.  Default=off", cmd, false);
  TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates.  Default=off", cmd, false);

  try
  {
    cmd.add( templateRegionArg );
    cmd.add( seekToMsArg );
    cmd.add( topNArg );
    cmd.add( configFileArg );
    cmd.add( fileArg );
    cmd.add( countryCodeArg );

    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    filename = fileArg.getValue();

    country = countryCodeArg.getValue();
    seektoms = seekToMsArg.getValue();
    outputJson = jsonSwitch.getValue();
    configFile = configFileArg.getValue();
    detectRegion = detectRegionSwitch.getValue();
    templateRegion = templateRegionArg.getValue();
    topn = topNArg.getValue();
    measureProcessingTime = clockSwitch.getValue();
  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }

  struct sigaction sigIntHandler;

  sigIntHandler.sa_handler = sighandler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;

  sigaction(SIGHUP, &sigIntHandler, NULL);
  sigaction(SIGINT, &sigIntHandler, NULL);

  cv::Mat frame;

  Alpr alpr(country, configFile);
  alpr.setTopN(topn);

  if (detectRegion)
    alpr.setDetectRegion(detectRegion);

  if (templateRegion.empty() == false)
    alpr.setDefaultRegion(templateRegion);

  if (alpr.isLoaded() == false)
  {
    std::cerr << "Error loading OpenALPR" << std::endl;
    return 1;
  }

  if (filename.empty())
  {
    std::string filename;
    while (std::getline(std::cin, filename))
    {
      if (fileExists(filename.c_str()))
      {
	frame = cv::imread( filename );
	detectandshow( &alpr, frame, "", outputJson);
      }
      else
      {
	std::cerr << "Image file not found: " << filename << std::endl;
      }

    }
  }
  else if (filename == "webcam")
  {
    int framenum = 0;
    cv::VideoCapture cap(0);
    if (!cap.isOpened())
    {
      std::cout << "Error opening webcam" << std::endl;
      return 1;
    }

    while (cap.read(frame))
    {
      detectandshow(&alpr, frame, "", outputJson);
      cv::waitKey(1);
      framenum++;
    }
  }
  else if (startsWith(filename, "http://") || startsWith(filename, "https://"))
  {
    int framenum = 0;

    VideoBuffer videoBuffer;

    videoBuffer.connect(filename, 5);

    cv::Mat latestFrame;

    while (program_active)
    {
      int response = videoBuffer.getLatestFrame(&latestFrame);

      if (response != -1)
      {
        detectandshow( &alpr, latestFrame, "", outputJson);
      }

      cv::waitKey(10);
    }

    videoBuffer.disconnect();

    std::cout << "Video processing ended" << std::endl;
  }
  else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") ||
	   hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg"))
  {
    if (fileExists(filename.c_str()))
    {
      int framenum = 0;

      cv::VideoCapture cap=cv::VideoCapture();
      cap.open(filename);
      cap.set(CV_CAP_PROP_POS_MSEC, seektoms);

      while (cap.read(frame))
      {
        if (SAVE_LAST_VIDEO_STILL)
        {
          cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame);
        }
        std::cout << "Frame: " << framenum << std::endl;

        detectandshow( &alpr, frame, "", outputJson);
        //create a 1ms delay
        cv::waitKey(1);
        framenum++;
      }
    }
    else
    {
      std::cerr << "Video file not found: " << filename << std::endl;
    }
  }
  else if (hasEndingInsensitive(filename, ".png") || hasEndingInsensitive(filename, ".jpg") ||
	   hasEndingInsensitive(filename, ".jpeg") || hasEndingInsensitive(filename, ".gif"))
  {
    if (fileExists(filename.c_str()))
    {
      frame = cv::imread( filename );

      detectandshow( &alpr, frame, "", outputJson);
    }
    else
    {
      std::cerr << "Image file not found: " << filename << std::endl;
    }
  }
  else if (DirectoryExists(filename.c_str()))
  {
    std::vector<std::string> files = getFilesInDir(filename.c_str());

    std::sort( files.begin(), files.end(), stringCompare );

    for (int i = 0; i< files.size(); i++)
    {
      if (hasEndingInsensitive(files[i], ".jpg") || hasEndingInsensitive(files[i], ".png"))
      {
        std::string fullpath = filename + "/" + files[i];
        std::cout << fullpath << std::endl;
        frame = cv::imread( fullpath.c_str() );
        if (detectandshow( &alpr, frame, "", outputJson))
        {
          //while ((char) cv::waitKey(50) != 'c') { }
        }
        else
        {
          //cv::waitKey(50);
        }
      }
    }
  }
  else
  {
    std::cerr << "Unknown file type" << std::endl;
    return 1;
  }

  return 0;
}

void sighandler(int sig)
{
  program_active = false;
  //std::cout << "Sig handler caught " << sig << std::endl;
}

bool detectandshow( Alpr* alpr, cv::Mat frame, std::string region, bool writeJson)
{
  std::vector<uchar> buffer;
  cv::imencode(".bmp", frame, buffer );

  timespec startTime;
  getTime(&startTime);

  std::vector<AlprResult> results = alpr->recognize(buffer);

  if (writeJson)
  {
    std::cout << alpr->toJson(results) << std::endl;
  }
  else
  {
    for (int i = 0; i < results.size(); i++)
    {
      std::cout << "plate" << i << ": " << results[i].result_count << " results -- Processing Time = " << results[i].processing_time_ms << "ms." << std::endl;

      for (int k = 0; k < results[i].topNPlates.size(); k++)
      {
        std::cout << "    - " << results[i].topNPlates[k].characters << "\t confidence: " << results[i].topNPlates[k].overall_confidence << "\t template_match: " << results[i].topNPlates[k].matches_template << std::endl;
      }
    }
  }

  timespec endTime;
  getTime(&endTime);
  if (measureProcessingTime)
    std::cout << "Total Time to process image: " << diffclock(startTime, endTime) << "ms." << std::endl;

  return results.size() > 0;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#include "itkTestingHashImageFilter.h"
#include "itkTestingMacros.h"

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkCustomColormapFunction.h"

#include "itkScalarToRGBColormapImageFilter.h"

int itkScalarToRGBColormapImageFilterTest( int argc, char *argv[] )
{
  if ( argc < 4 )
    {
    std::cout << "Usage: " << argv[0] <<
      " inputImage outputImage colormap [customColormapFile]" << std::endl;
    std::cout <<
      "  Possible colormaps: grey, red, green, blue, copper, jet, hsv, ";
    std::cout <<
      "spring, summer, autumn, winter, hot, cool, custom" << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int ImageDimension = 2;

  typedef unsigned int                    PixelType;
  typedef itk::RGBPixel<unsigned char>    RGBPixelType;

  typedef itk::Image<PixelType, ImageDimension>     ImageType;
  typedef itk::Image<float, ImageDimension>         RealImageType;
  typedef itk::Image<RGBPixelType, ImageDimension>  RGBImageType;

  typedef itk::ImageFileReader<ImageType>           ReaderType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );
  reader->Update();

  std::string colormapString( argv[3] );

  typedef itk::VectorImage< unsigned char, ImageDimension> VectorImageType;
  typedef itk::ScalarToRGBColormapImageFilter<ImageType, VectorImageType> VectorFilterType;
  VectorFilterType::Pointer vfilter = VectorFilterType::New();

  typedef itk::ScalarToRGBColormapImageFilter<ImageType, RGBImageType> RGBFilterType;
  RGBFilterType::Pointer rgbfilter = RGBFilterType::New();

  rgbfilter->Print( std::cout );

  rgbfilter->SetInput( reader->GetOutput() );
  vfilter->SetInput( reader->GetOutput() );

  if ( colormapString == "red" )
    {
    rgbfilter->SetColormap( RGBFilterType::Red );
    vfilter->SetColormap( VectorFilterType::Red );
    }
  else if ( colormapString == "green"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Green );
    vfilter->SetColormap( VectorFilterType::Green );
    }
  else if ( colormapString == "blue"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Blue );
    vfilter->SetColormap( VectorFilterType::Blue );
    }
  else if ( colormapString == "grey"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Grey );
    vfilter->SetColormap( VectorFilterType::Grey );
    }
  else if ( colormapString == "cool"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Cool );
    vfilter->SetColormap( VectorFilterType::Cool );
    }
  else if ( colormapString == "hot"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Hot );
    vfilter->SetColormap( VectorFilterType::Hot );
    }
  else if ( colormapString == "spring"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Spring );
    vfilter->SetColormap( VectorFilterType::Spring );
    }
  else if ( colormapString == "autumn"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Autumn );
    vfilter->SetColormap( VectorFilterType::Autumn );
    }
  else if ( colormapString == "winter"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Winter );
    vfilter->SetColormap( VectorFilterType::Winter );
    }
  else if ( colormapString == "copper"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Copper );
    vfilter->SetColormap( VectorFilterType::Copper );
    }
  else if ( colormapString == "summer"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Summer );
    vfilter->SetColormap( VectorFilterType::Summer );
    }
  else if ( colormapString == "jet"  )
    {
    typedef itk::Function::JetColormapFunction<
      ImageType::PixelType, RGBImageType::PixelType> ColormapType;

    ColormapType::Pointer colormap = ColormapType::New();

    rgbfilter->SetColormap( colormap );

    typedef itk::Function::JetColormapFunction<
      ImageType::PixelType, VectorImageType::PixelType> VectorColormapType;

    VectorColormapType::Pointer vcolormap = VectorColormapType::New();

    vfilter->SetColormap( vcolormap );
    }
  else if ( colormapString == "hsv"  )
    {
    typedef itk::Function::HSVColormapFunction<
      ImageType::PixelType, RGBImageType::PixelType> ColormapType;

    ColormapType::Pointer colormap = ColormapType::New();
    rgbfilter->SetColormap( colormap );

    typedef itk::Function::HSVColormapFunction<
      ImageType::PixelType, VectorImageType::PixelType> VectorColormapType;

    VectorColormapType::Pointer vcolormap = VectorColormapType::New();
    vfilter->SetColormap( vcolormap );
    }
  else if ( colormapString == "overunder"  )
    {
    rgbfilter->SetColormap( RGBFilterType::OverUnder );
    vfilter->SetColormap( VectorFilterType::OverUnder );
    }
  else if ( colormapString == "custom"  )
    {
    typedef itk::Function::CustomColormapFunction<
      ImageType::PixelType, RGBImageType::PixelType> ColormapType;

    ColormapType::Pointer colormap = ColormapType::New();

    typedef itk::Function::CustomColormapFunction<
      ImageType::PixelType, VectorImageType::PixelType> VectorColormapType;

    VectorColormapType::Pointer vcolormap = VectorColormapType::New();

    std::ifstream str( argv[4] );
    std::string line;

    float value;
    ColormapType::ChannelType       channel;

    // Get red values
    std::getline( str, line );
    std::istringstream issr( line );
    while ( issr >> value )
      {
      channel.push_back( value );
      }
    colormap->SetRedChannel( channel );
    vcolormap->SetRedChannel( channel );

    // Get green values
    std::getline( str, line );
    std::istringstream issg( line );
    while ( issg >> value )
      {
      channel.push_back( value );
      }
    colormap->SetGreenChannel( channel );
    vcolormap->SetGreenChannel( channel );

    // Get blue values
    std::getline( str, line );
    std::istringstream issb( line );
    while ( issb >> value )
      {
      channel.push_back( value );
      }
    colormap->SetBlueChannel( channel );
    vcolormap->SetBlueChannel( channel );
    rgbfilter->SetColormap( colormap );
    vfilter->SetColormap( vcolormap );
    }

  rgbfilter->GetColormap()->SetMinimumRGBComponentValue( 0 );
  rgbfilter->GetColormap()->SetMaximumRGBComponentValue( 255 );

  typedef itk::Testing::HashImageFilter<RGBImageType> RGBHasher;
  RGBHasher::Pointer rgbhasher = RGBHasher::New();
  rgbhasher->SetInput( rgbfilter->GetOutput() );
  rgbhasher->InPlaceOff();

  typedef itk::Testing::HashImageFilter<VectorImageType> VectorHasher;
  VectorHasher::Pointer vhasher = VectorHasher::New();
  vhasher->SetInput( vfilter->GetOutput() );

  try
    {
    rgbfilter->Update();
    vfilter->Update();

    rgbhasher->Update();
    vhasher->Update();

    }
  catch (...)
    {
    return EXIT_FAILURE;
    }

  typedef itk::ImageFileWriter<RGBImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[2] );
  writer->SetInput( rgbfilter->GetOutput() );
  writer->Update();

  // compare the hash values of the Image and RGBPixel Image to ensure
  // they are the same
  TEST_EXPECT_EQUAL( rgbhasher->GetHash(), vhasher->GetHash() );

  return EXIT_SUCCESS;
}
<commit_msg>COMP: Colormap tests need platform specific image<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#include "itkTestingHashImageFilter.h"
#include "itkTestingMacros.h"

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkCustomColormapFunction.h"

#include "itkScalarToRGBColormapImageFilter.h"

int itkScalarToRGBColormapImageFilterTest( int argc, char *argv[] )
{
  if ( argc < 4 )
    {
    std::cout << "Usage: " << argv[0] <<
      " inputImage outputImage colormap [customColormapFile]" << std::endl;
    std::cout <<
      "  Possible colormaps: grey, red, green, blue, copper, jet, hsv, ";
    std::cout <<
      "spring, summer, autumn, winter, hot, cool, custom" << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int ImageDimension = 2;

  typedef unsigned int                    PixelType;
  typedef itk::RGBPixel<unsigned char>    RGBPixelType;

  typedef itk::Image<PixelType, ImageDimension>     ImageType;
  typedef itk::Image<float, ImageDimension>         RealImageType;
  typedef itk::Image<RGBPixelType, ImageDimension>  RGBImageType;

  typedef itk::ImageFileReader<ImageType>           ReaderType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );
  reader->Update();

  std::string colormapString( argv[3] );

  typedef itk::VectorImage< unsigned char, ImageDimension> VectorImageType;
  typedef itk::ScalarToRGBColormapImageFilter<ImageType, VectorImageType> VectorFilterType;
  VectorFilterType::Pointer vfilter = VectorFilterType::New();

  typedef itk::ScalarToRGBColormapImageFilter<ImageType, RGBImageType> RGBFilterType;
  RGBFilterType::Pointer rgbfilter = RGBFilterType::New();

  rgbfilter->Print( std::cout );

  rgbfilter->SetInput( reader->GetOutput() );
  vfilter->SetInput( reader->GetOutput() );

  if ( colormapString == "red" )
    {
    rgbfilter->SetColormap( RGBFilterType::Red );
    vfilter->SetColormap( VectorFilterType::Red );
    }
  else if ( colormapString == "green"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Green );
    vfilter->SetColormap( VectorFilterType::Green );
    }
  else if ( colormapString == "blue"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Blue );
    vfilter->SetColormap( VectorFilterType::Blue );
    }
  else if ( colormapString == "grey"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Grey );
    vfilter->SetColormap( VectorFilterType::Grey );
    }
  else if ( colormapString == "cool"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Cool );
    vfilter->SetColormap( VectorFilterType::Cool );
    }
  else if ( colormapString == "hot"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Hot );
    vfilter->SetColormap( VectorFilterType::Hot );
    }
  else if ( colormapString == "spring"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Spring );
    vfilter->SetColormap( VectorFilterType::Spring );
    }
  else if ( colormapString == "autumn"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Autumn );
    vfilter->SetColormap( VectorFilterType::Autumn );
    }
  else if ( colormapString == "winter"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Winter );
    vfilter->SetColormap( VectorFilterType::Winter );
    }
  else if ( colormapString == "copper"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Copper );
    vfilter->SetColormap( VectorFilterType::Copper );
    }
  else if ( colormapString == "summer"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Summer );
    vfilter->SetColormap( VectorFilterType::Summer );
    }
  else if ( colormapString == "jet"  )
    {
    typedef itk::Function::JetColormapFunction<
      ImageType::PixelType, RGBImageType::PixelType> ColormapType;

    ColormapType::Pointer colormap = ColormapType::New();

    rgbfilter->SetColormap( colormap );

    typedef itk::Function::JetColormapFunction<
      ImageType::PixelType, VectorImageType::PixelType> VectorColormapType;

    VectorColormapType::Pointer vcolormap = VectorColormapType::New();

    vfilter->SetColormap( vcolormap );
    }
  else if ( colormapString == "hsv"  )
    {
    typedef itk::Function::HSVColormapFunction<
      ImageType::PixelType, RGBImageType::PixelType> ColormapType;

    ColormapType::Pointer colormap = ColormapType::New();
    rgbfilter->SetColormap( colormap );

    typedef itk::Function::HSVColormapFunction<
      ImageType::PixelType, VectorImageType::PixelType> VectorColormapType;

    VectorColormapType::Pointer vcolormap = VectorColormapType::New();
    vfilter->SetColormap( vcolormap );
    }
  else if ( colormapString == "overunder"  )
    {
    rgbfilter->SetColormap( RGBFilterType::OverUnder );
    vfilter->SetColormap( VectorFilterType::OverUnder );
    }
  else if ( colormapString == "custom"  )
    {
    typedef itk::Function::CustomColormapFunction<
      ImageType::PixelType, RGBImageType::PixelType> ColormapType;

    ColormapType::Pointer colormap = ColormapType::New();

    typedef itk::Function::CustomColormapFunction<
      ImageType::PixelType, VectorImageType::PixelType> VectorColormapType;

    VectorColormapType::Pointer vcolormap = VectorColormapType::New();

    std::ifstream str( argv[4] );
    std::string line;

    float value;
    ColormapType::ChannelType       channel;

    // Get red values
    std::getline( str, line );
    std::istringstream issr( line );
    while ( issr >> value )
      {
      channel.push_back( value );
      }
    colormap->SetRedChannel( channel );
    vcolormap->SetRedChannel( channel );

    // Get green values
    std::getline( str, line );
    std::istringstream issg( line );
    while ( issg >> value )
      {
      channel.push_back( value );
      }
    colormap->SetGreenChannel( channel );
    vcolormap->SetGreenChannel( channel );

    // Get blue values
    std::getline( str, line );
    std::istringstream issb( line );
    while ( issb >> value )
      {
      channel.push_back( value );
      }
    colormap->SetBlueChannel( channel );
    vcolormap->SetBlueChannel( channel );
    rgbfilter->SetColormap( colormap );
    vfilter->SetColormap( vcolormap );
    }

  rgbfilter->GetColormap()->SetMinimumRGBComponentValue( 0 );
  rgbfilter->GetColormap()->SetMaximumRGBComponentValue( 255 );

  typedef itk::Testing::HashImageFilter<RGBImageType> RGBHasher;
  RGBHasher::Pointer rgbhasher = RGBHasher::New();
  rgbhasher->SetInput( rgbfilter->GetOutput() );
  rgbhasher->InPlaceOff();

  typedef itk::Testing::HashImageFilter<VectorImageType> VectorHasher;
  VectorHasher::Pointer vhasher = VectorHasher::New();
  vhasher->SetInput( vfilter->GetOutput() );

  try
    {
    rgbfilter->Update();
    vfilter->Update();

    rgbhasher->Update();
    vhasher->Update();

    }
  catch (...)
    {
    return EXIT_FAILURE;
    }

  typedef itk::ImageFileWriter<RGBImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[2] );
  writer->SetInput( rgbfilter->GetOutput() );
  writer->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
	This file is part of the MinSG library extension BlueSurfels.
	Copyright (C) 2012-2013 Claudius Jhn <claudius@uni-paderborn.de>
	Copyright (C) 2013 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_BLUE_SURFELS

#include "E_SurfelGenerator.h"
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <E_Util/Graphics/E_PixelAccessor.h>
#include <E_Rendering/Mesh/E_Mesh.h>
#include <Util/Graphics/PixelAccessor.h>

namespace E_MinSG{
namespace BlueSurfels{

//! (static)
EScript::Type * E_SurfelGenerator::getTypeObject() {
	// E_SurfelGenerator ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! (static) init members
void E_SurfelGenerator::init(EScript::Namespace & lib) {

	EScript::Type * typeObject = E_SurfelGenerator::getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	using namespace MinSG::BlueSurfels;

	//!	[ESMF] SurfelGenerator new MinSG.SurfelGenerator
	ES_CTOR(typeObject,0,0,new E_SurfelGenerator(thisType))

	//! [ESMF] self SurfelGenerator.clearBenchmarkResults()
	ES_MFUN(typeObject,SurfelGenerator,"clearBenchmarkResults",0,0,			(thisObj->clearBenchmarkResults(),thisEObj))

	//! [ESMF] ExtObject SurfelGenerator.createSurfels(PixelAccessor,PixelAccessor,PixelAccessor,PixelAccessor)
	ES_MFUNCTION(typeObject,SurfelGenerator,"createSurfels",4,4,{
		const auto surfelResult = thisObj->createSurfels(
												parameter[0].to<Util::PixelAccessor&>(rt),
												parameter[1].to<Util::PixelAccessor&>(rt),
												parameter[2].to<Util::PixelAccessor&>(rt),
												parameter[3].to<Util::PixelAccessor&>(rt));
		static const EScript::StringId meshAttr("mesh");
		static const EScript::StringId relativeCoveringAttr("relativeCovering");
		EScript::ExtObject * result = new EScript::ExtObject;
		result->setAttribute(meshAttr, EScript::create(surfelResult.first.get()));
		result->setAttribute(relativeCoveringAttr, EScript::Number::create(surfelResult.second));
		return result;
	})

	//! [ESMF] Map SurfelGenerator.getBenchmarkResults()
	ES_MFUNCTION(typeObject,const SurfelGenerator,"getBenchmarkResults",0,0,{
		EScript::Map* m = new EScript::Map;
		for(const auto& entry : thisObj->getBenchmarkResults()) // string -> number
			m->setValue( EScript::create(entry.first), EScript::create(entry.second) );
		return m;
	})

	//! [ESMF] Number SurfelGenerator.getReusalRate()
	ES_MFUN(typeObject,const SurfelGenerator,"getReusalRate",0,0,			thisObj->getReusalRate())

	//! [ESMF] Number SurfelGenerator.getMaxAbsSurfels()
	ES_MFUN(typeObject,const SurfelGenerator,"getMaxAbsSurfels",0,0,		thisObj->getMaxAbsSurfels())

	//! [ESMF] self SurfelGenerator.setMaxAbsSurfels(Number)
	ES_MFUN(typeObject,SurfelGenerator,"setMaxAbsSurfels",1,1,				(thisObj->setMaxAbsSurfels(parameter[0].toUInt()),thisEObj))

	//! [ESMF] self SurfelGenerator.setReusalRate(Number)
	ES_MFUN(typeObject,SurfelGenerator,"setReusalRate",1,1,					(thisObj->setReusalRate(parameter[0].toFloat()),thisEObj))

	//! [ESMF] self SurfelGenerator.setBenchmarkingEnabled(Bool)
	ES_MFUN(typeObject,SurfelGenerator,"setBenchmarkingEnabled",1,1,		(thisObj->setBenchmarkingEnabled(parameter[0].toBool()),thisEObj))

}
}

}
#endif // MINSG_EXT_BLUE_SURFELS

<commit_msg>E_SurfelGenerator: removed old bindings.<commit_after>/*
	This file is part of the MinSG library extension BlueSurfels.
	Copyright (C) 2012-2013 Claudius Jhn <claudius@uni-paderborn.de>
	Copyright (C) 2013 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_BLUE_SURFELS

#include "E_SurfelGenerator.h"
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <E_Util/Graphics/E_PixelAccessor.h>
#include <E_Rendering/Mesh/E_Mesh.h>
#include <Util/Graphics/PixelAccessor.h>

namespace E_MinSG{
namespace BlueSurfels{

//! (static)
EScript::Type * E_SurfelGenerator::getTypeObject() {
	// E_SurfelGenerator ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! (static) init members
void E_SurfelGenerator::init(EScript::Namespace & lib) {

	EScript::Type * typeObject = E_SurfelGenerator::getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	using namespace MinSG::BlueSurfels;

	//!	[ESMF] SurfelGenerator new MinSG.SurfelGenerator
	ES_CTOR(typeObject,0,0,new E_SurfelGenerator(thisType))

	//! [ESMF] self SurfelGenerator.clearBenchmarkResults()
	ES_MFUN(typeObject,SurfelGenerator,"clearBenchmarkResults",0,0,			(thisObj->clearBenchmarkResults(),thisEObj))

	//! [ESMF] ExtObject SurfelGenerator.createSurfels(PixelAccessor,PixelAccessor,PixelAccessor,PixelAccessor)
	ES_MFUNCTION(typeObject,SurfelGenerator,"createSurfels",4,4,{
		const auto surfelResult = thisObj->createSurfels(
												parameter[0].to<Util::PixelAccessor&>(rt),
												parameter[1].to<Util::PixelAccessor&>(rt),
												parameter[2].to<Util::PixelAccessor&>(rt),
												parameter[3].to<Util::PixelAccessor&>(rt));
		static const EScript::StringId meshAttr("mesh");
		static const EScript::StringId relativeCoveringAttr("relativeCovering");
		EScript::ExtObject * result = new EScript::ExtObject;
		result->setAttribute(meshAttr, EScript::create(surfelResult.first.get()));
		result->setAttribute(relativeCoveringAttr, EScript::Number::create(surfelResult.second));
		return result;
	})

	//! [ESMF] Map SurfelGenerator.getBenchmarkResults()
	ES_MFUNCTION(typeObject,const SurfelGenerator,"getBenchmarkResults",0,0,{
		EScript::Map* m = new EScript::Map;
		for(const auto& entry : thisObj->getBenchmarkResults()) // string -> number
			m->setValue( EScript::create(entry.first), EScript::create(entry.second) );
		return m;
	})

	//! [ESMF] Number SurfelGenerator.getMaxAbsSurfels()
	ES_MFUN(typeObject,const SurfelGenerator,"getMaxAbsSurfels",0,0,		thisObj->getMaxAbsSurfels())

	//! [ESMF] self SurfelGenerator.setMaxAbsSurfels(Number)
	ES_MFUN(typeObject,SurfelGenerator,"setMaxAbsSurfels",1,1,				(thisObj->setMaxAbsSurfels(parameter[0].toUInt()),thisEObj))

	//! [ESMF] self SurfelGenerator.setBenchmarkingEnabled(Bool)
	ES_MFUN(typeObject,SurfelGenerator,"setBenchmarkingEnabled",1,1,		(thisObj->setBenchmarkingEnabled(parameter[0].toBool()),thisEObj))

}
}

}
#endif // MINSG_EXT_BLUE_SURFELS

<|endoftext|>