Skip to content
Snippets Groups Projects
Commit 471e2cb9 authored by Thibault Allenet's avatar Thibault Allenet
Browse files

Initial commit : Stimulis, database MNIST, convertion tensor opencv to cpu

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 1348 additions and 0 deletions
# C++ Build
build*/
install*/
# VSCode
.vscode
# Python
*.so
__pycache__
*.pyc
*.egg-info
# Mermaid
*.mmd
# Doxygen
xml*/
# ONNX
*.onnx
\ No newline at end of file
################################################################################
# Pre-configured CI/CD for your Aidge module.
#
# Three stages are already pre-configured to run on Eclipse Aidge CI:
# - build: ubuntu_cpp, ubuntu_python and windows_cpp;
# - test: ubuntu_cpp, ubuntu_python and windows_cpp;
# - coverage: ubuntu_cpp and ubuntu_python.
#
# If your project is pure C++ or pure Python, you can remove the "_python" or
# "_cpp" jobs respectively.
# "ubuntu" jobs require an Ubuntu runner with a docker executor with tag
# "docker".
# "windows" jobs require a Windows runner with a docker-windows executor with
# tag "windows".
#
# You can change the docker images in the YML scripts directly. The default
# images are:
# - nvidia/cuda:12.2.0-devel-ubuntu22.04 for Ubuntu jobs;
# - buildtools for Windows jobs, built on top of
# mcr.microsoft.com/windows/servercore:ltsc2022 with Microsoft Visual Studio
# 2022 BuildTools installed.
#
# See Aidge project wiki for more details on how to setup your own docker images
# and Gitlab runners.
################################################################################
stages:
# Build
- build
# Unit test stage
- test
# Code coverage
- coverage
include:
- local: '/.gitlab/ci/_global.gitlab-ci.yml'
- local: '/.gitlab/ci/build.gitlab-ci.yml'
- local: '/.gitlab/ci/test.gitlab-ci.yml'
- local: '/.gitlab/ci/coverage.gitlab-ci.yml'
cmake_minimum_required(VERSION 3.15)
file(READ "${CMAKE_SOURCE_DIR}/version.txt" version)
file(READ "${CMAKE_SOURCE_DIR}/project_name.txt" project)
message(STATUS "Project name: ${project}")
message(STATUS "Project version: ${version}")
# Note : project name is {project} and python module name is also {project}
set(module_name _${project}) # target name
project(${project})
##############################################
# Define options
option(PYBIND "python binding" ON)
option(WERROR "Warning as error" OFF)
option(TEST "Enable tests" ON)
option(COVERAGE "Enable coverage" OFF)
##############################################
# Import utils CMakeLists
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")
include(PybindModuleCreation)
if(CMAKE_COMPILER_IS_GNUCXX AND COVERAGE)
Include(CodeCoverage)
endif()
##############################################
# Find system dependencies
find_package(aidge_core REQUIRED)
find_package(aidge_backend_cpu REQUIRED)
find_package(OpenCV REQUIRED)
if (${OpenCV_VERSION_MAJOR} LESS 3)
MESSAGE(FATAL_ERROR "Unsupported OpenCV version. OpenCV 3.0.0+ is required")
endif()
##############################################
# Create target and set properties
file(GLOB_RECURSE src_files "src/*.cpp")
file(GLOB_RECURSE inc_files "include/*.hpp")
add_library(${module_name} ${src_files} ${inc_files})
target_link_libraries(${module_name}
PUBLIC
_aidge_core # _ is added because we link the target not the project
_aidge_backend_cpu
)
target_link_libraries(${module_name} PUBLIC ${OpenCV_LIBS})
target_include_directories(${module_name} PUBLIC ${OpenCV_INCLUDE_DIRS})
#Set target properties
set_property(TARGET ${module_name} PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(${module_name}
PUBLIC
$<INSTALL_INTERFACE:include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
# PYTHON BINDING
if (PYBIND)
generate_python_binding(${project} ${module_name})
# Handles Python + pybind11 headers dependencies
target_link_libraries(${module_name}
PUBLIC
pybind11::pybind11
PRIVATE
Python::Python
)
endif()
target_compile_features(${module_name} PRIVATE cxx_std_14)
target_compile_options(${module_name} PRIVATE
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CXX_COMPILER_ID:GNU>>:
-Wall -Wextra -Wold-style-cast -Winline -pedantic -Werror=narrowing -Wshadow $<$<BOOL:${WERROR}>:-Werror>>)
target_compile_options(${module_name} PRIVATE
$<$<CXX_COMPILER_ID:MSVC>:
/W4>)
if(CMAKE_COMPILER_IS_GNUCXX AND COVERAGE)
append_coverage_compiler_flags()
endif()
##############################################
# Installation instructions
include(GNUInstallDirs)
set(INSTALL_CONFIGDIR ${CMAKE_INSTALL_LIBDIR}/cmake/${project})
install(TARGETS ${module_name} EXPORT ${project}-targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
#Export the targets to a script
install(EXPORT ${project}-targets
FILE "${project}-targets.cmake"
DESTINATION ${INSTALL_CONFIGDIR}
# COMPONENT ${module_name}
)
#Create a ConfigVersion.cmake file
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/${project}-config-version.cmake"
VERSION ${version}
COMPATIBILITY AnyNewerVersion
)
configure_package_config_file("${project}-config.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/${project}-config.cmake"
INSTALL_DESTINATION ${INSTALL_CONFIGDIR}
)
#Install the config, configversion and custom find modules
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/${project}-config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/${project}-config-version.cmake"
DESTINATION ${INSTALL_CONFIGDIR}
)
##############################################
## Exporting from the build tree
export(EXPORT ${project}-targets
FILE "${CMAKE_CURRENT_BINARY_DIR}/${project}-targets.cmake")
##############################################
## Add test
if(TEST)
enable_testing()
add_subdirectory(unit_tests)
endif()
LICENSE 0 → 100644
Eclipse Public License - v 2.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial content
Distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program originate from
and are Distributed by that particular Contributor. A Contribution
"originates" from a Contributor if it was added to the Program by
such Contributor itself or anyone acting on such Contributor's behalf.
Contributions do not include changes or additions to the Program that
are not Modified Works.
"Contributor" means any person or entity that Distributes the Program.
"Licensed Patents" mean patent claims licensable by a Contributor which
are necessarily infringed by the use or sale of its Contribution alone
or when combined with the Program.
"Program" means the Contributions Distributed in accordance with this
Agreement.
"Recipient" means anyone who receives the Program under this Agreement
or any Secondary License (as applicable), including Contributors.
"Derivative Works" shall mean any work, whether in Source Code or other
form, that is based on (or derived from) the Program and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship.
"Modified Works" shall mean any work in Source Code or other form that
results from an addition to, deletion from, or modification of the
contents of the Program, including, for purposes of clarity any new file
in Source Code form that contains any contents of the Program. Modified
Works shall not include works that contain only declarations,
interfaces, types, classes, structures, or files of the Program solely
in each case in order to link to, bind by name, or subclass the Program
or Modified Works thereof.
"Distribute" means the acts of a) distributing or b) making available
in any manner that enables the transfer of a copy.
"Source Code" means the form of a Program preferred for making
modifications, including but not limited to software source code,
documentation source, and configuration files.
"Secondary License" means either the GNU General Public License,
Version 2.0, or any later versions of that license, including any
exceptions or additional permissions as identified by the initial
Contributor.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each Contributor hereby
grants Recipient a non-exclusive, worldwide, royalty-free copyright
license to reproduce, prepare Derivative Works of, publicly display,
publicly perform, Distribute and sublicense the Contribution of such
Contributor, if any, and such Derivative Works.
b) Subject to the terms of this Agreement, each Contributor hereby
grants Recipient a non-exclusive, worldwide, royalty-free patent
license under Licensed Patents to make, use, sell, offer to sell,
import and otherwise transfer the Contribution of such Contributor,
if any, in Source Code or other form. This patent license shall
apply to the combination of the Contribution and the Program if, at
the time the Contribution is added by the Contributor, such addition
of the Contribution causes such combination to be covered by the
Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor grants the
licenses to its Contributions set forth herein, no assurances are
provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity.
Each Contributor disclaims any liability to Recipient for claims
brought by any other entity based on infringement of intellectual
property rights or otherwise. As a condition to exercising the
rights and licenses granted hereunder, each Recipient hereby
assumes sole responsibility to secure any other intellectual
property rights needed, if any. For example, if a third party
patent license is required to allow Recipient to Distribute the
Program, it is Recipient's responsibility to acquire that license
before distributing the Program.
d) Each Contributor represents that to its knowledge it has
sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
e) Notwithstanding the terms of any Secondary License, no
Contributor makes additional grants to any Recipient (other than
those set forth in this Agreement) as a result of such Recipient's
receipt of the Program under the terms of a Secondary License
(if permitted under the terms of Section 3).
3. REQUIREMENTS
3.1 If a Contributor Distributes the Program in any form, then:
a) the Program must also be made available as Source Code, in
accordance with section 3.2, and the Contributor must accompany
the Program with a statement that the Source Code for the Program
is available under this Agreement, and informs Recipients how to
obtain it in a reasonable manner on or through a medium customarily
used for software exchange; and
b) the Contributor may Distribute the Program under a license
different than this Agreement, provided that such license:
i) effectively disclaims on behalf of all other Contributors all
warranties and conditions, express and implied, including
warranties or conditions of title and non-infringement, and
implied warranties or conditions of merchantability and fitness
for a particular purpose;
ii) effectively excludes on behalf of all other Contributors all
liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) does not attempt to limit or alter the recipients' rights
in the Source Code under section 3.2; and
iv) requires any subsequent distribution of the Program by any
party to be under a license that satisfies the requirements
of this section 3.
3.2 When the Program is Distributed as Source Code:
a) it must be made available under this Agreement, or if the
Program (i) is combined with other material in a separate file or
files made available under a Secondary License, and (ii) the initial
Contributor attached to the Source Code the notice described in
Exhibit A of this Agreement, then the Program may be made available
under the terms of such Secondary Licenses, and
b) a copy of this Agreement must be included with each copy of
the Program.
3.3 Contributors may not remove or alter any copyright, patent,
trademark, attribution notices, disclaimers of warranty, or limitations
of liability ("notices") contained within the Program from any copy of
the Program which they Distribute, provided that Contributors may add
their own appropriate notices.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain responsibilities
with respect to end users, business partners and the like. While this
license is intended to facilitate the commercial use of the Program,
the Contributor who includes the Program in a commercial product
offering should do so in a manner which does not create potential
liability for other Contributors. Therefore, if a Contributor includes
the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and indemnify every
other Contributor ("Indemnified Contributor") against any losses,
damages and costs (collectively "Losses") arising from claims, lawsuits
and other legal actions brought by a third party against the Indemnified
Contributor to the extent caused by the acts or omissions of such
Commercial Contributor in connection with its distribution of the Program
in a commercial product offering. The obligations in this section do not
apply to any claims or Losses relating to any actual or alleged
intellectual property infringement. In order to qualify, an Indemnified
Contributor must: a) promptly notify the Commercial Contributor in
writing of such claim, and b) allow the Commercial Contributor to control,
and cooperate with the Commercial Contributor in, the defense and any
related settlement negotiations. The Indemnified Contributor may
participate in any such claim at its own expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those performance
claims and warranties, and if a court requires any other Contributor to
pay any damages as a result, the Commercial Contributor must pay
those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE. Each Recipient is solely responsible for determining the
appropriateness of using and distributing the Program and assumes all
risks associated with its exercise of rights under this Agreement,
including but not limited to the risks and costs of program errors,
compliance with applicable laws, damage to or loss of data, programs
or equipment, and unavailability or interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS
SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further
action by the parties hereto, such provision shall be reformed to the
minimum extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other software
or hardware) infringes such Recipient's patent(s), then such Recipient's
rights granted under Section 2(b) shall terminate as of the date such
litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of
time after becoming aware of such noncompliance. If all Recipient's
rights under this Agreement terminate, Recipient agrees to cease use
and distribution of the Program as soon as reasonably practicable.
However, Recipient's obligations under this Agreement and any licenses
granted by Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this Agreement,
but in order to avoid inconsistency the Agreement is copyrighted and
may only be modified in the following manner. The Agreement Steward
reserves the right to publish new versions (including revisions) of
this Agreement from time to time. No one other than the Agreement
Steward has the right to modify this Agreement. The Eclipse Foundation
is the initial Agreement Steward. The Eclipse Foundation may assign the
responsibility to serve as the Agreement Steward to a suitable separate
entity. Each new version of the Agreement will be given a distinguishing
version number. The Program (including Contributions) may always be
Distributed subject to the version of the Agreement under which it was
received. In addition, after a new version of the Agreement is published,
Contributor may elect to Distribute the Program (including its
Contributions) under the new version.
Except as expressly stated in Sections 2(a) and 2(b) above, Recipient
receives no rights or licenses to the intellectual property of any
Contributor under this Agreement, whether expressly, by implication,
estoppel or otherwise. All rights in the Program not expressly granted
under this Agreement are reserved. Nothing in this Agreement is intended
to be enforceable by any entity that is not a Contributor or Recipient.
No third-party beneficiary rights are created under this Agreement.
Exhibit A - Form of Secondary Licenses Notice
"This Source Code may also be made available under the following
Secondary Licenses when the conditions for such availability set forth
in the Eclipse Public License, v. 2.0 are satisfied: {name license(s),
version(s), and exceptions or additional permissions here}."
Simply including a copy of this Agreement, including this Exhibit A
is not sufficient to license the Source Code under Secondary Licenses.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to
look for such a notice.
You may add additional accurate notices of copyright ownership.
\ No newline at end of file
# Aidge CPU library
You can find in this folder the library that implements :
- Computer vision databases
- The OpenCV tensor, operators and stimulis
So far be sure to have the correct requirements to use this library
- GCC
- OpenCV >= 3.0
- Make
- CMake
- aidge_core
- aidge_backend_cpu
- Python (optional, if you have no intend to use this library in python with pybind)
## Pip installation
You will need to install first the aidge_core and aidge_backend_cpu libraries before installing aidge_backend_opencv.
Then run in your python environnement :
``` bash
pip install . -v
```
\ No newline at end of file
@PACKAGE_INIT@
include(${CMAKE_CURRENT_LIST_DIR}/aidge_backend_opencv-config-version.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/aidge_backend_opencv-targets.cmake)
# Example 1: import .so generated by PyBind
from aidge_backend_opencv.aidge_backend_opencv import *
import unittest
import aidge_core
import aidge_backend_opencv
import numpy as np
class test_tensor(unittest.TestCase):
"""Test tensor binding
"""
def setUp(self):
pass
def tearDown(self):
pass
def test_getavailable_backends(self):
self.assertTrue("opencv" in aidge_core.Tensor.get_available_backends())
# def test_numpy_int_to_tensor(self):
# np_array = np.arange(9).reshape(1,1,3,3)
# # Numpy -> Tensor
# t = aidge_core.Tensor(np_array)
# self.assertEqual(t.dtype(), aidge_core.DataType.Int32)
# for i_t, i_n in zip(t, np_array.flatten()):
# self.assertTrue(i_t == i_n)
# for i,j in zip(t.dims(), np_array.shape):
# self.assertEqual(i,j)
# def test_tensor_int_to_numpy(self):
# np_array = np.arange(9).reshape(1,1,3,3)
# # Numpy -> Tensor
# t = aidge_core.Tensor(np_array)
# # Tensor -> Numpy
# nnarray = np.array(t)
# for i_nn, i_n in zip(nnarray.flatten(), np_array.flatten()):
# self.assertTrue(i_nn == i_n)
# for i,j in zip(t.dims(), nnarray.shape):
# self.assertEqual(i,j)
# def test_numpy_float_to_tensor(self):
# t = aidge_core.Tensor()
# np_array = np.random.rand(1, 1, 3, 3).astype(np.float32)
# # Numpy -> Tensor
# t = aidge_core.Tensor(np_array)
# self.assertEqual(t.dtype(), aidge_core.DataType.Float32)
# for i_t, i_n in zip(t, np_array.flatten()):
# self.assertTrue(i_t == i_n) # TODO : May need to change this to a difference
# for i,j in zip(t.dims(), np_array.shape):
# self.assertEqual(i,j)
if __name__ == '__main__':
unittest.main()
This diff is collapsed.
function(generate_python_binding name target_to_bind)
if (PYBIND)
add_definitions(-DPYBIND)
Include(FetchContent)
FetchContent_Declare(
PyBind11
GIT_REPOSITORY https://github.com/pybind/pybind11.git
GIT_TAG v2.10.4 # or a later release
)
# Use the New FindPython mode, recommanded. Requires CMake 3.15+
find_package(Python COMPONENTS Interpreter Development)
FetchContent_MakeAvailable(PyBind11)
message(STATUS "Creating binding for module ${name}")
file(GLOB_RECURSE pybind_src_files "python_binding/*.cpp")
pybind11_add_module(${name} MODULE ${pybind_src_files} "NO_EXTRAS") # NO EXTRA recquired for pip install
target_include_directories(${name} PUBLIC "python_binding")
target_link_libraries(${name} PUBLIC ${target_to_bind})
endif()
endfunction()
/********************************************************************************
* Copyright (c) 2023 CEA-List
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
********************************************************************************/
#ifndef AIDGE_OPENCV_IMPORTS_H_
#define AIDGE_OPENCV_IMPORTS_H_
#include "aidge/backend/opencv/data/TensorImpl.hpp"
#include "aidge/backend/opencv/stimuli/StimuliImpl.hpp"
#include "aidge/backend/opencv/database/MNIST.hpp"
#include "aidge/backend/opencv/utils/Utils.hpp"
#endif /* AIDGE_OPENCV_IMPORTS_H_ */
\ No newline at end of file
#ifndef TensorImpl_opencv_H_
#define TensorImpl_opencv_H_
#include "opencv2/core.hpp"
#include "aidge/backend/TensorImpl.hpp"
#include "aidge/data/Tensor.hpp"
#include "aidge/utils/Registrar.hpp"
#include "aidge/utils/Types.h"
#include <iostream>
namespace {
template <typename T> struct OpenCvType { static const int type; };
template <> const int OpenCvType<char>::type = CV_8SC1;
template <> const int OpenCvType<short>::type = CV_16SC1;
template <> const int OpenCvType<int>::type = CV_32SC1;
template <> const int OpenCvType<unsigned char>::type = CV_8UC1;
template <> const int OpenCvType<unsigned short>::type = CV_16UC1;
template <> const int OpenCvType<float>::type = CV_32FC1;
template <> const int OpenCvType<double>::type = CV_64FC1;
} // namespace
namespace Aidge {
class TensorImpl_opencv_ {
protected:
cv::Mat mData;
public :
virtual const cv::Mat getCvMat() const { return mData; }
virtual void setCvMat(cv::Mat mat) {mData=mat;}
};
template <class T> class TensorImpl_opencv : public TensorImpl, public TensorImpl_opencv_ {
private:
const Tensor &mTensor; // Impl needs to access Tensor information, but is not
// supposed to change it!
cv::Mat mData;
public:
static constexpr const char *Backend = "opencv";
TensorImpl_opencv(const Tensor &tensor)
: TensorImpl(Backend), mTensor(tensor) {}
bool operator==(const TensorImpl &otherImpl) const override final {
// Create iterators for both matrices
cv::MatConstIterator_<T> it1 = mData.begin<T>();
const cv::Mat otherData =
reinterpret_cast<const TensorImpl_opencv<T> &>(otherImpl).data();
cv::MatConstIterator_<T> it2 = otherData.begin<T>();
// Iterate over the elements and compare them
for (; it1 != mData.end<T>(); ++it1, ++it2) {
if (*it1 != *it2) {
return false;
}
}
return true;
}
static std::unique_ptr<TensorImpl_opencv<T>> create(const Tensor &tensor) {
return std::make_unique<TensorImpl_opencv<T>>(tensor);
}
// native interface
const cv::Mat &data() const { return mData; }
// void setData(cv::Mat mat){mData=mat;}
std::size_t scalarSize() const override { return sizeof(T); }
void copy(const void *src, NbElts_t length, std::size_t /*offset = 0*/) override {
std::copy(static_cast<const T*>(src), static_cast<const T*>(src) + length, static_cast<T*>(rawPtr()));
}
void *rawPtr() override {
if (mData.ptr() == nullptr) {
lazyInit(mData);
}
return mData.ptr<T>();
};
void setRawPtr(void */*ptr*/) override final {
printf("Not implemented yet.\n");
// assert(mTensor.nbDims()<=3 && "nbDims > 3 is not supported for opencv backends.");
// std::vector<cv::Mat> channels;
// for (std::size_t k = 0; k < mTensor.dims()[2]; ++k) {
// channels.push_back(cv::Mat(static_cast<int>(mTensor.dims()[1]),
// static_cast<int>(mTensor.dims()[0]),
// OpenCvType<T>::type,
// static_cast<T*>(ptr) + k*mTensor.dims()[1]*mTensor.dims()[0]*sizeof(T)));
// }
// cv::merge(channels, mData);
};
void* getRaw(std::size_t idx) override {
return static_cast<void*>(&mData.at<T>(static_cast<int>(idx)));
};
virtual ~TensorImpl_opencv() = default;
private:
void lazyInit(cv::Mat &mat) {
std::cout << "call lazy init tensorimpl_opencv : " << std::endl;
assert(mTensor.nbDims() <= 3 && "OpenCV implementation does not support "
"tensor with more than 3 dimensions");
if (mat.cols == static_cast<int>(mTensor.dims()[0]) && mat.rows == static_cast<int>(mTensor.dims()[1]) &&
mat.channels() == static_cast<int>(mTensor.dims()[2])) {
// Correct size, not change
return;
}
if (mat.rows * mat.cols * mat.channels() == static_cast<int>(mTensor.size())) {
// Shape has changed, data will not be invalided
mat = mat.reshape(mTensor.dims()[2], mTensor.dims()[1]);
return;
}
// Number of element has changed, daya WILL BE invalided
if (mTensor.nbDims() < 3) {
mat = cv::Mat(((mTensor.nbDims() > 1) ? static_cast<int>(mTensor.dims()[1])
: (mTensor.nbDims() > 0) ? 1
: 0),
(mTensor.nbDims() > 0) ? static_cast<int>(mTensor.dims()[0]) : 0,
OpenCvType<T>::type);
} else {
std::vector<cv::Mat> channels;
for (std::size_t k = 0; k < mTensor.dims()[2]; ++k) {
channels.push_back(cv::Mat(static_cast<int>(mTensor.dims()[1]),
static_cast<int>(mTensor.dims()[0]),
OpenCvType<T>::type));
}
cv::merge(channels, mat);
}
}
};
namespace {
static Registrar<Tensor>
registrarTensorImpl_opencv_Float64({"opencv", DataType::Float64},
Aidge::TensorImpl_opencv<double>::create);
static Registrar<Tensor>
registrarTensorImpl_opencv_Float32({"opencv", DataType::Float32},
Aidge::TensorImpl_opencv<float>::create);
static Registrar<Tensor>
registrarTensorImpl_opencv_Int32({"opencv", DataType::Int32},
Aidge::TensorImpl_opencv<int>::create);
static Registrar<Tensor>
registrarTensorImpl_opencv_Int16({"opencv", DataType::Int16},
Aidge::TensorImpl_opencv<int16_t>::create);
static Registrar<Tensor>
registrarTensorImpl_opencv_UInt16({"opencv", DataType::UInt16},
Aidge::TensorImpl_opencv<uint16_t>::create);
// static Registrar<Tensor>
// registrarTensorImpl_opencv_Int8({"opencv", DataType::Int8},
// Aidge::TensorImpl_opencv<int8_t>::create);
static Registrar<Tensor>
registrarTensorImpl_opencv_UInt8({"opencv", DataType::UInt8},
Aidge::TensorImpl_opencv<uint8_t>::create);
} // namespace
} // namespace Aidge
#endif /* TensorImpl_opencv_H_ */
#ifndef MNIST_H
#define MNIST_H
#include <fstream>
#include <iomanip>
#include <tuple>
#include "opencv2/core.hpp"
#include <opencv2/opencv.hpp>
#include "aidge/data/Database.hpp"
#include "aidge/stimuli/Stimuli.hpp"
#include "aidge/graph/GraphView.hpp"
#include "aidge/scheduler/Scheduler.hpp"
#include "aidge/data/Tensor.hpp"
#include "aidge/backend/opencv/utils/Utils.hpp"
// #include "aidge/backend/opencv/data/TensorImpl.hpp"
namespace Aidge {
template <class T> void swapEndian(T& obj)
{
unsigned char* memp = reinterpret_cast<unsigned char*>(&obj);
std::reverse(memp, memp + sizeof(T));
}
inline bool isBigEndian()
{
const union {
uint32_t i;
char c[4];
} bint = {0x01020304};
return bint.c[0] == 1;
}
class MNIST : public Database {
public:
MNIST() = delete;
MNIST(const std::string& dataPath,
// const GraphView transformations,
bool train,
bool loadDataInMemory = false)
: Database(),
mDataPath(dataPath),
// mDataTransformations(transformations),
mTrain(train),
mLoadDataInMemory(loadDataInMemory)
{
// Uncompress train database
if (mTrain){
MNIST::uncompress(mDataPath + "/train-images-idx3-ubyte",
dataPath + "/train-labels-idx1-ubyte");
}else { // Uncompress test database
MNIST::uncompress(mDataPath + "/t10k-images-idx3-ubyte",
dataPath + "/t10k-labels-idx1-ubyte");
}
}
std::vector<std::shared_ptr<Tensor>> getItem(std::size_t index) override;
void uncompress(const std::string& dataPath,
const std::string& labelPath);
std::size_t getLen() override;
union MagicNumber {
unsigned int value;
unsigned char byte[4];
};
enum DataType {
Unsigned = 0x08,
Signed = 0x09,
Short = 0x0B,
Int = 0x0C,
Float = 0x0D,
Double = 0x0E
};
protected:
/// Stimuli data path
std::string mDataPath;
// True select the train database, False Select the test database
bool mTrain;
// True Load images in memory, False reload at each call
bool mLoadDataInMemory;
/// Stimuli data
// Each index of the vector is one item of the database
// One item of the MNIST database is the tuple <Image,label>
// First stimuli of the tuple is a gray scale image stimuli of a writen digit
// Second stimuli of the tuple is the label associated to the digit : unsigned integer 0-9
std::vector<std::tuple<Stimuli,Stimuli>> mStimulis;
/// Data Transformations
// Data transformations use the GraphView mecanism
// Transformations are a sequential graph with each operator of the graph being one transformation
// GraphView mDataTransformations;
// Scheduler to run the graph of data transformations
// Scheduler mScheduler;
};
}
#endif // MNIST_H
/********************************************************************************
* Copyright (c) 2023 CEA-List
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
********************************************************************************/
#ifndef LOAD_H_
#define LOAD_H_
#include <cstring>
#include <memory>
#include <iostream>
#include "opencv2/core.hpp"
#include <opencv2/imgcodecs.hpp>
#include "aidge/data/Data.hpp"
#include "aidge/data/Tensor.hpp"
#include "aidge/backend/StimuliImpl.hpp"
#include "aidge/stimuli/Stimuli.hpp"
#include "aidge/backend/opencv/data/TensorImpl.hpp"
namespace Aidge {
class StimuliImpl_opencv_imread : public StimuliImpl {
public:
StimuliImpl_opencv_imread(const std::string& dataPath="", int colorFlag=cv::IMREAD_COLOR) :
mDataPath(dataPath),
mColorFlag(colorFlag) {}
virtual ~StimuliImpl_opencv_imread() {};
std::shared_ptr<Tensor> load() override;
static std::unique_ptr<StimuliImpl_opencv_imread> create(const std::string& dataPath) {
return std::make_unique<StimuliImpl_opencv_imread>(dataPath);
}
protected:
/// Stimuli data path
std::string mDataPath;
int mColorFlag;
};
namespace {
static Registrar<Aidge::Stimuli> registrarStimuliImpl_opencv_png(
{"opencv", "png"}, Aidge::StimuliImpl_opencv_imread::create);
static Registrar<Aidge::Stimuli> registrarStimuliImpl_opencv_pgm(
{"opencv", "pgm"}, Aidge::StimuliImpl_opencv_imread::create);
} // namespace
} // namespace Aidge
#endif /* LOAD_H_ */
/********************************************************************************
* Copyright (c) 2023 CEA-List
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
********************************************************************************/
#ifndef AIDGE_BACKEND_OPENCV_UTILS_ATTRIBUTES_H_
#define AIDGE_BACKEND_OPENCV_UTILS_ATTRIBUTES_H_
#include <tuple>
#include "opencv2/core.hpp"
#include <opencv2/opencv.hpp>
#include "aidge/data/Tensor.hpp"
#include "aidge/backend/opencv/data/TensorImpl.hpp"
#include "aidge/backend/cpu/data/TensorImpl.hpp"
#include "aidge/data/Data.hpp"
namespace Aidge {
/**
* @brief Instanciate an aidge tensor with backend "opencv" containing an opencv matrix
*
* @param mat the cv::mat to instanciate the tensor from
* @return std::shared_ptr<Tensor> aidge tensor
*/
inline std::shared_ptr<Tensor> tensorOpencv(cv::Mat mat){
// Get Mat dims
std::vector<DimSize_t> matDims = std::vector<DimSize_t>({static_cast<DimSize_t>(mat.cols),
static_cast<DimSize_t>(mat.rows),
static_cast<DimSize_t>(mat.channels())});
// Create tensor from the dims of the Cv::Mat
std::shared_ptr<Tensor> tensor = std::make_shared<Tensor>(matDims);
// Set beackend opencv
tensor->setBackend("opencv");
// Set Data Type
switch (mat.depth()) {
case CV_8U:
tensor->setDatatype(Aidge::DataType::UInt8);
break;
case CV_8S:
tensor->setDatatype(Aidge::DataType::Int8);
break;
case CV_16U:
tensor->setDatatype(Aidge::DataType::UInt16);
break;
case CV_16S:
tensor->setDatatype(Aidge::DataType::Int16);
break;
case CV_32S:
tensor->setDatatype(Aidge::DataType::Int32);
break;
case CV_32F:
tensor->setDatatype(Aidge::DataType::Float32);
break;
case CV_64F:
tensor->setDatatype(Aidge::DataType::Float64);
break;
default:
throw std::runtime_error(
"Cannot convert cv::Mat to Tensor: incompatible types.");
}
// Cast the tensorImpl to access setCvMat function
TensorImpl_opencv_* tImpl_opencv = dynamic_cast<TensorImpl_opencv_*>(tensor->getImpl().get());
tImpl_opencv->setCvMat(mat);
return tensor;
}
/**
* @brief Copy the data from a source 2D cv::mat to a destination pointer with an offset
*
* @tparam CV_T The standard type corresponding to the opencv data type
* @param mat opencv 2D mat to copy the data from
* @param data destination pointer
* @param offset offset an the destination data pointer
*/
template <class CV_T>
void convert(const cv::Mat& mat, void* data, size_t offset);
/**
* @brief Convert a tensor backend opencv into a tensor backend cpu
*
* @param tensorOpencv tensor with backend opencv (contains a cv::mat)
* @return std::shared_ptr<Tensor> tensor backend cpu (contains a std::vector)
*/
std::shared_ptr<Tensor> convertCpu(std::shared_ptr<Aidge::Tensor> tensorOpencv);
} // namespace
#endif // AIDGE_BACKEND_OPENCV_UTILS_ATTRIBUTES_H_
\ No newline at end of file
aidge_backend_opencv
\ No newline at end of file
#include <pybind11/pybind11.h>
// Need to call this header to register tensorImpl when initializing opencv python module
#include "aidge/backend/opencv.hpp"
namespace py = pybind11;
namespace Aidge {
void init_Aidge(py::module& /*m*/){
}
PYBIND11_MODULE(aidge_backend_opencv, m) {
init_Aidge(m);
}
}
setup.py 0 → 100644
#!/usr/bin/env python3
""" Aidge
#TODO To change
POC of the next framework named Aidge
"""
DOCLINES = (__doc__ or '').split("\n")
import sys
import os
# Python supported version checks
if sys.version_info[:2] < (3, 7):
raise RuntimeError("Python version >= 3.7 required.")
CLASSIFIERS = """\
Development Status :: 2 - Pre-Alpha
"""
import shutil
import pathlib
import subprocess
import multiprocessing
from math import ceil
from setuptools import setup, Extension
from setuptools import find_packages
from setuptools.command.build_ext import build_ext
def get_project_name() -> str:
return open(pathlib.Path().absolute() / "project_name.txt", "r").read()
def get_project_version() -> str:
aidge_root = pathlib.Path().absolute()
version = open(aidge_root / "version.txt", "r").read().strip()
return version
class CMakeExtension(Extension):
def __init__(self, name):
super().__init__(name, sources=[])
class CMakeBuild(build_ext):
def run(self):
# This lists the number of processors available on the machine
# The compilation will use half of them
max_jobs = str(ceil(multiprocessing.cpu_count() / 2))
cwd = pathlib.Path().absolute()
build_temp = cwd / "build"
if not build_temp.exists():
build_temp.mkdir(parents=True, exist_ok=True)
build_lib = pathlib.Path(self.build_lib)
if not build_lib.exists():
build_lib.mkdir(parents=True, exist_ok=True)
os.chdir(str(build_temp))
# Impose to use the executable of the python
# used to launch setup.py to setup PythonInterp
param_py = "-DPYTHON_EXECUTABLE=" + sys.executable
install_path = f"{build_temp}/install" if "AIDGE_INSTALL" not in os.environ else os.environ["AIDGE_INSTALL"]
self.spawn(['cmake', str(cwd), param_py, '-DTEST=OFF', f'-DCMAKE_INSTALL_PREFIX:PATH={install_path}'])
if not self.dry_run:
self.spawn(['make', 'all', 'install', '-j', max_jobs])
os.chdir(str(cwd))
aidge_package = build_lib / (get_project_name())
# Get "aidge core" package
# ext_lib = build_temp
print(build_temp.absolute())
# Copy all shared object files from build_temp/lib to aidge_package
for root, _, files in os.walk(build_temp.absolute()):
for file in files:
if file.endswith('.so') and (root != str(aidge_package.absolute())):
currentFile=os.path.join(root, file)
shutil.copy(currentFile, str(aidge_package.absolute()))
# Copy version.txt in aidge_package
os.chdir(os.path.dirname(__file__))
shutil.copy("version.txt", str(aidge_package.absolute()))
if __name__ == '__main__':
setup(
name=get_project_name(),
version=get_project_version(),
python_requires='>=3.7',
description=DOCLINES[0],
long_description_content_type="text/markdown",
long_description="\n".join(DOCLINES[2:]),
classifiers=[c for c in CLASSIFIERS.split('\n') if c],
platforms=["Linux"],
packages=find_packages(where="."),
include_package_data=True,
ext_modules=[CMakeExtension(get_project_name())],
cmdclass={
'build_ext': CMakeBuild,
},
zip_safe=False,
)
#include "aidge/backend/opencv/database/MNIST.hpp"
void Aidge::MNIST::uncompress(const std::string& dataPath,
const std::string& labelPath)
{
// Images
std::ifstream images(dataPath.c_str(), std::fstream::binary);
if (!images.good())
throw std::runtime_error("Could not open images file: " + dataPath);
MagicNumber magicNumber;
unsigned int nbImages;
unsigned int nbRows;
unsigned int nbColumns;
images.read(reinterpret_cast<char*>(&magicNumber.value),
sizeof(magicNumber));
images.read(reinterpret_cast<char*>(&nbImages), sizeof(nbImages));
images.read(reinterpret_cast<char*>(&nbRows), sizeof(nbRows));
images.read(reinterpret_cast<char*>(&nbColumns), sizeof(nbColumns));
if (!Aidge::isBigEndian()) {
Aidge::swapEndian(magicNumber.value);
Aidge::swapEndian(nbImages);
Aidge::swapEndian(nbRows);
Aidge::swapEndian(nbColumns);
}
if (magicNumber.byte[3] != 0 || magicNumber.byte[2] != 0
|| magicNumber.byte[1] != Unsigned || magicNumber.byte[0] != 3) {
throw std::runtime_error("Wrong file format for images file: "
+ dataPath);
}
// Labels
std::ifstream labels(labelPath.c_str(), std::fstream::binary);
if (!labels.good())
throw std::runtime_error("Could not open labels file: " + labelPath);
MagicNumber magicNumberLabels;
unsigned int nbItemsLabels;
labels.read(reinterpret_cast<char*>(&magicNumberLabels.value),
sizeof(magicNumberLabels));
labels.read(reinterpret_cast<char*>(&nbItemsLabels), sizeof(nbItemsLabels));
if (!Aidge::isBigEndian()) {
Aidge::swapEndian(magicNumberLabels);
Aidge::swapEndian(nbItemsLabels);
}
if (magicNumberLabels.byte[3] != 0 || magicNumberLabels.byte[2] != 0
|| magicNumberLabels.byte[1] != Unsigned
|| magicNumberLabels.byte[0] != 1) {
throw std::runtime_error("Wrong file format for labels file: "
+ labelPath);
}
if (nbImages != nbItemsLabels)
throw std::runtime_error(
"The number of images and the number of labels does not match.");
// For each image...
for (unsigned int i = 0; i < nbImages; ++i) {
unsigned char buff;
std::ostringstream nameStr;
nameStr << dataPath << "[" << std::setfill('0') << std::setw(5) << i
<< "].pgm";
// ... generate the stimuli
if (!std::ifstream(nameStr.str()).good()) {
cv::Mat frame(cv::Size(nbColumns, nbRows), CV_8UC1);
for (unsigned int y = 0; y < nbRows; ++y) {
for (unsigned int x = 0; x < nbColumns; ++x) {
images.read(reinterpret_cast<char*>(&buff), sizeof(buff));
frame.at<unsigned char>(y, x) = buff;
}
}
if (!cv::imwrite(nameStr.str(), frame))
throw std::runtime_error("Unable to write image: "
+ nameStr.str());
} else {
// Skip image data (to grab labels only)
images.seekg(nbColumns * nbRows, images.cur);
}
// Create the stimuli of the image
Aidge::Stimuli StimuliImg(nameStr.str(), mLoadDataInMemory);
StimuliImg.setBackend("opencv");
// Create the stimuli of the corresponding label by filing integer to the stimuli directly
labels.read(reinterpret_cast<char*>(&buff), sizeof(buff));
int label = static_cast<int>(buff);
std::shared_ptr<Tensor> lbl = std::make_shared<Tensor>(Array1D<int, 1>{label});
Aidge::Stimuli StimuliLabel(lbl);
// Push back the corresponding image & label in the vector
mStimulis.push_back(std::make_tuple(StimuliImg, StimuliLabel));
}
if (images.eof())
throw std::runtime_error(
"End-of-file reached prematurely in data file: " + dataPath);
else if (!images.good())
throw std::runtime_error("Error while reading data file: " + dataPath);
else if (images.get() != std::fstream::traits_type::eof())
throw std::runtime_error("Data file size larger than expected: "
+ dataPath);
if (labels.eof())
throw std::runtime_error(
"End-of-file reached prematurely in data file: " + labelPath);
else if (!labels.good())
throw std::runtime_error("Error while reading data file: " + labelPath);
else if (labels.get() != std::fstream::traits_type::eof())
throw std::runtime_error("Data file size larger than expected: "
+ labelPath);
}
std::vector<std::shared_ptr<Aidge::Tensor>> Aidge::MNIST::getItem(std::size_t index) {
std::vector<std::shared_ptr<Tensor>> item;
// Load the digit tensor
// TODO : Currently converts the tensor Opencv but this operation will be carried by a convert operator later
item.push_back(Aidge::convertCpu((std::get<0>(mStimulis.at(index))).load()));
// item.push_back((std::get<0>(mStimulis.at(index))).load());
// Load the label tensor
item.push_back((std::get<1>(mStimulis.at(index))).load());
return item;
}
std::size_t Aidge::MNIST::getLen(){
return mStimulis.size();
}
\ No newline at end of file
#include "aidge/backend/opencv/stimuli/StimuliImpl_opencv_imread.hpp"
std::shared_ptr<Aidge::Tensor> Aidge::StimuliImpl_opencv_imread::load() {
cv::Mat cv_img = cv::imread(mDataPath, mColorFlag);
if (cv_img.empty()) {
throw std::runtime_error("Could not open images file: " + mDataPath);
}
// Get Mat dims
std::vector<DimSize_t> matDims = std::vector<DimSize_t>({static_cast<DimSize_t>(cv_img.cols),
static_cast<DimSize_t>(cv_img.rows),
static_cast<DimSize_t>(cv_img.channels())});
// Create tensor from the dims of the Cv::Mat
std::shared_ptr<Tensor> img = std::make_shared<Tensor>(matDims);
// Set beackend opencv
img->setBackend("opencv");
// Set Data Type
img->setDatatype(DataType::UInt8);
// Cast the tensorImpl to access setCvMat function
TensorImpl_opencv_* tImpl_opencv = dynamic_cast<TensorImpl_opencv_*>(img->getImpl().get());
tImpl_opencv->setCvMat(cv_img);
return img;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment