aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/StudioApplication/DefaultStudioApplicationManager.cs
blob: ee9337eb3de5b304bac11172ddea4396dc57e2fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core.Helpers;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.MachineStudio.Common.Navigation;
using System.Reflection;
using System.Collections;
using Tango.Core;
using Tango.Logging;
using Tango.MachineStudio.Common.Modules;
using Tango.MachineStudio.Common;
using Tango.Settings;
using System.Windows;
using Tango.Integration.ExternalBridge;
using Tango.MachineStudio.Common.EventLogging;
using Tango.BL.Enumerations;
using Tango.Core.DI;

namespace Tango.MachineStudio.UI.StudioApplication
{
    /// <summary>
    /// Represents the default Machine Studio <see cref="IStudioApplicationManager">Application Manager</see>.
    /// </summary>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    /// <seealso cref="Tango.MachineStudio.Common.StudioApplication.IStudioApplicationManager" />
    public class DefaultStudioApplicationManager : ExtendedObject, IStudioApplicationManager
    {
        private INavigationManager _navigationManager;
        private IStudioModuleLoader _moduleLoader;
        private List<Window> _openedWindows;

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultStudioApplicationManager" /> class.
        /// </summary>
        /// <param name="navigationManager">The navigation manager.</param>
        public DefaultStudioApplicationManager(INavigationManager navigationManager, IStudioModuleLoader moduleLoader)
        {
            _moduleLoader = moduleLoader;
            _navigationManager = navigationManager;
            _openedWindows = new List<Window>();

            Task.Factory.StartNew(() =>
            {
                while (MainWindow.Instance == null)
                {
                    Thread.Sleep(100);
                }

                InvokeUI(() =>
                {
                    MainWindow.Instance.ContentRendered += (_, __) =>
                    {
                        TangoIOC.Default.GetAllInstancesByBase<IStudioViewModel>().ToList().ForEach(x => x.OnApplicationStarted());
                    };
                });
            });
        }

        /// <summary>
        /// Gets a value indicating whether Machine Studio is shutting down.
        /// </summary>
        public bool IsShuttingDown { get; private set; }

        /// <summary>
        /// The connected machine
        /// </summary>
        private IExternalBridgeClient _connectedMachine;

        /// <summary>
        /// Occurs when the connected machine property has changed.
        /// </summary>
        public event EventHandler<IExternalBridgeClient> ConnectedMachineChanged;

        /// <summary>
        /// Gets or sets the currently connected machine if any.
        /// </summary>
        public IExternalBridgeClient ConnectedMachine
        {
            get { return _connectedMachine; }
            set
            {
                _connectedMachine = value;
                RaisePropertyChangedAuto();
                RaisePropertyChanged(nameof(IsMachineConnected));
                RaisePropertyChanged(nameof(IsMachineConnectedViaTCP));

                if (_connectedMachine != null)
                {
                    _connectedMachine.StateChanged -= ConnectedMachine_StateChanged;
                    _connectedMachine.StateChanged += ConnectedMachine_StateChanged;
                }

                ConnectedMachineChanged?.Invoke(this, _connectedMachine);
            }
        }

        /// <summary>
        /// Gets a value indicating whether the <see cref="P:Tango.MachineStudio.Common.StudioApplication.IStudioApplicationManager.ConnectedMachine" /> is valid and connected through TCP/IP.
        /// </summary>
        public bool IsMachineConnectedViaTCP
        {
            get { return IsMachineConnected && ConnectedMachine is ExternalBridgeTcpClient; }
        }

        /// <summary>
        /// Handles the <see cref="ConnectedMachine"/> state changed event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void ConnectedMachine_StateChanged(object sender, Transport.TransportComponentState e)
        {
            if (e == Transport.TransportComponentState.Disconnected || e == Transport.TransportComponentState.Failed)
            {
                ConnectedMachine = null;
            }

        }

        /// <summary>
        /// Gets a value indicating whether the <see cref="P:Tango.MachineStudio.Common.StudioApplication.IStudioApplicationManager.ConnectedMachine" /> is valid.
        /// </summary>
        public bool IsMachineConnected
        {
            get { return ConnectedMachine != null; }
        }

        /// <summary>
        /// Gets the machine studio application version.
        /// </summary>
        public Version Version
        {
            get
            {
                return AssemblyHelper.GetCurrentAssemblyVersion();
            }
        }

        /// <summary>
        /// Shutdown the application.
        /// </summary>
        public async void ShutDown()
        {
            if (IsShuttingDown) return;

            IsShuttingDown = true;

            try
            {
                Rect r = new Rect(
                        MainWindow.Instance.Left,
                        MainWindow.Instance.Top,
                        MainWindow.Instance.Width,
                        MainWindow.Instance.Height);

                await Task.Factory.StartNew(async () =>
                {
                //Do Shutdown Procedures...
                foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<IStudioViewModel>())
                    {
                        try
                        {
                            var result = await vm.OnShutdownRequest();
                            if (!result)
                            {
                                IsShuttingDown = false;
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, "Error on shutdown request with " + vm.GetType().Name);
                        }
                    }

                    foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<IStudioViewModel>())
                    {
                        vm.OnShuttingDown();
                    }

                    SettingsManager.Default.GetOrCreate<MachineStudioSettings>().LastBounds = r;

                    try
                    {
                        SettingsManager.Default.Save();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error saving settings.");
                    }

                    _navigationManager.NavigateTo(NavigationView.ShutdownView);

                    Thread.Sleep(1500);

                    foreach (var window in _openedWindows)
                    {
                        ThreadsHelper.InvokeUI(() =>
                        {
                            window.Close();
                        });
                    }

                    try
                    {
                        if (ConnectedMachine != null)
                        {
                            ConnectedMachine.Disconnect().Wait();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error disconnecting from machine.");
                    }

                    var eventLogger = TangoIOC.Default.GetInstance<IEventLogger>();
                    if (eventLogger != null)
                    {
                        eventLogger.Log(EventTypes.ApplicationTerminated, "Application Terminated!");
                        eventLogger.FlushAll();
                    }

                    Thread.Sleep(1500);

                    Environment.Exit(0);

                });
            }
            catch (Exception ex)
            {
                IsShuttingDown = false;
                LogManager.Log(ex,"An error occurred while shutting down machine studio.");
            }
        }

        /// <summary>
        /// Loads the specified module if permitted.
        /// </summary>
        /// <param name="moduleName">Name of the module.</param>
        /// <param name="args">The arguments.</param>
        public void RequestModule(string moduleName, params object[] args)
        {
            IStudioModule module = _moduleLoader.UserModules.SingleOrDefault(x => x.Name == moduleName);

            if (module != null)
            {
                TangoIOC.Default.GetInstance<ViewModels.MainViewVM>().StartModule(module);

                //Notify request listeners.
                foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<IStudioViewModel>())
                {
                    vm.OnModuleRequest(module, args);
                }
            }
            else
            {
                throw new InvalidOperationException("The module was not found or you do not have sufficient privileges.");
            }
        }

        /// <summary>
        /// Notify the application manager about an external opened window.
        /// When application exists. All registered windows will be closed.
        /// </summary>
        /// <param name="window">The window.</param>
        public void RegisterOpenedWindow(Window window)
        {
            _openedWindows.Add(window);

            window.Closed += (x, y) => { _openedWindows.Remove(window); };
        }

        /// <summary>
        /// Gets the core libraries version.
        /// </summary>
        public Version CoreVersion
        {
            get
            {
                return typeof(ExtendedObject).Assembly.GetName().Version;
            }
        }

        /// <summary>
        /// Gets the build date.
        /// </summary>
        public string BuildDate
        {
            get
            {
                return AssemblyHelper.GetCurrentAssemblyBuildDate().ToShortDateString();
            }
        }

        /// <summary>
        /// Gets the change log.
        /// </summary>
        public string ChangeLog
        {
            get
            {
                return EmbeddedResourceHelper.GetEmbeddedResourceText("Tango.MachineStudio.UI.ChangeLog.txt");
            }
        }
    }
}
virtual void clearAllBuffers(){_segmTool.clearAllBuffers();} private: TransientAreasSegmentationModuleImpl _segmTool; }; /** * allocator * @param Size : size of the images input to segment (output will be the same size) */ Ptr<TransientAreasSegmentationModule> TransientAreasSegmentationModule::create(Size inputSize){ return makePtr<TransientAreasSegmentationModuleImpl_>(inputSize); } // Constructor and destructors TransientAreasSegmentationModuleImpl::TransientAreasSegmentationModuleImpl(const Size size) :BasicRetinaFilter(size.height, size.width, 3), // allocate the output of the class _inputToSegment(size.height*size.width), _contextMotionEnergy(size.height*size.width), _segmentedAreas(size.height*size.width), // set the pointer to the 2 frame buffer to the correct adress: // -> the first low pass filter buffer will be _localBuffer // -> the second will be _filterOutput; _localMotion(_localBuffer), _neighborhoodMotion(_filterOutput) { // default parameters setup setup(_segmentationParameters); //clean before running clearAllBuffers(); } TransientAreasSegmentationModuleImpl::~TransientAreasSegmentationModuleImpl() { } void TransientAreasSegmentationModuleImpl::clearAllBuffers() { // flush parent buffers bioinspired::BasicRetinaFilter::clearAllBuffers(); // flush instance buffers _contextMotionEnergy=0; _segmentedAreas=0; } struct SegmentationParameters TransientAreasSegmentationModuleImpl::getParameters() { return _segmentationParameters; } // setup from XML file void TransientAreasSegmentationModuleImpl::setup(String segmentationParameterFile, const bool applyDefaultSetupOnFailure) { try { // opening retinaParameterFile in read mode cv::FileStorage fs(segmentationParameterFile, cv::FileStorage::READ); setup(fs, applyDefaultSetupOnFailure); }catch(cv::Exception &e) { printf("Retina::setup: wrong/unappropriate xml parameter file : error report :`n=>%s\n", e.what()); if (applyDefaultSetupOnFailure) { printf("Retina::setup: resetting retina with default parameters\n"); cv::bioinspired::SegmentationParameters defaults; setup(defaults); } else { printf("=> keeping current parameters"); } } } // setup from cv::Filestorage object void TransientAreasSegmentationModuleImpl::setup(cv::FileStorage &fs, const bool applyDefaultSetupOnFailure) { try { // read parameters file if it exists or apply default setup if asked for if (!fs.isOpened()) { std::cout<<"Retina::setup: provided parameters file could not be open... skeeping configuration"<<std::endl; return; // implicit else case : retinaParameterFile could be open (it exists at least) } // OPL and Parvo init first... update at the same time the parameters structure and the retina core cv::FileNode rootFn = fs.root(), currFn=rootFn["SegmentationModuleSetup"]; currFn["thresholdON"]>>_segmentationParameters.thresholdON; currFn["thresholdOFF"]>>_segmentationParameters.thresholdOFF; currFn["localEnergy_temporalConstant"]>>_segmentationParameters.localEnergy_temporalConstant; currFn["localEnergy_spatialConstant"]>>_segmentationParameters.localEnergy_spatialConstant; currFn["neighborhoodEnergy_temporalConstant"]>>_segmentationParameters.neighborhoodEnergy_temporalConstant; currFn["neighborhoodEnergy_spatialConstant"]>>_segmentationParameters.neighborhoodEnergy_spatialConstant; currFn["contextEnergy_temporalConstant"]>>_segmentationParameters.contextEnergy_temporalConstant; currFn["contextEnergy_spatialConstant"]>>_segmentationParameters.contextEnergy_spatialConstant; setup(_segmentationParameters); }catch(cv::Exception &e) { std::cout<<"Retina::setup: resetting retina with default parameters"<<std::endl; if (applyDefaultSetupOnFailure) { struct cv::bioinspired::SegmentationParameters defaults; setup(defaults); } std::cout<<"SegmentationModule::setup: wrong/unappropriate xml parameter file : error report :`n=>"<<e.what()<<std::endl; std::cout<<"=> keeping current parameters"<<std::endl; } } // setup parameters for the 2 filters that allow the segmentation void TransientAreasSegmentationModuleImpl::setup(cv::bioinspired::SegmentationParameters newParameters) { // copy structure contents memcpy(&_segmentationParameters, &newParameters, sizeof(cv::bioinspired::SegmentationParameters)); // apply setup // init local motion energy extraction low pass filter BasicRetinaFilter::setLPfilterParameters(0, newParameters.localEnergy_temporalConstant, newParameters.localEnergy_spatialConstant); // init neighbohood motion energy extraction low pass filter BasicRetinaFilter::setLPfilterParameters(0, newParameters.neighborhoodEnergy_temporalConstant, newParameters.neighborhoodEnergy_spatialConstant, 1); // init large area low pass filter BasicRetinaFilter::setLPfilterParameters(0, newParameters.contextEnergy_temporalConstant, newParameters.contextEnergy_spatialConstant, 2); } const String TransientAreasSegmentationModuleImpl::printSetup() { std::stringstream outmessage; outmessage<<"Current segmentation instance setup :" <<"\n\t thresholdON : " << _segmentationParameters.thresholdON <<"\n\t thresholdOFF : " << _segmentationParameters.thresholdOFF <<"\n\t localEnergy_temporalConstant : " << _segmentationParameters.localEnergy_temporalConstant <<"\n\t localEnergy_spatialConstant : " << _segmentationParameters.localEnergy_spatialConstant <<"\n\t neighborhoodEnergy_temporalConstant : " << _segmentationParameters.neighborhoodEnergy_temporalConstant <<"\n\t neighborhoodEnergy_spatialConstant : " << _segmentationParameters.neighborhoodEnergy_spatialConstant <<"\n\t contextEnergy_temporalConstant : " << _segmentationParameters.contextEnergy_temporalConstant <<"\n\t contextEnergy_spatialConstant : " << _segmentationParameters.contextEnergy_spatialConstant; return outmessage.str().c_str(); } void TransientAreasSegmentationModuleImpl::write( String fs ) const { cv::FileStorage parametersSaveFile(fs, cv::FileStorage::WRITE ); write(parametersSaveFile); } void TransientAreasSegmentationModuleImpl::write( cv::FileStorage& fs ) const { if (!fs.isOpened()) return; // basic error case fs <<"SegmentationModuleSetup"<<"{"; fs <<"thresholdON" << _segmentationParameters.thresholdON; fs <<"thresholdOFF" << _segmentationParameters.thresholdOFF; fs <<"localEnergy_temporalConstant" << _segmentationParameters.localEnergy_temporalConstant; fs <<"localEnergy_spatialConstant" << _segmentationParameters.localEnergy_spatialConstant; fs <<"neighborhoodEnergy_temporalConstant" << _segmentationParameters.neighborhoodEnergy_temporalConstant; fs <<"neighborhoodEnergy_spatialConstant" << _segmentationParameters.neighborhoodEnergy_spatialConstant; fs <<"contextEnergy_temporalConstant" << _segmentationParameters.contextEnergy_temporalConstant; fs <<"contextEnergy_spatialConstant" << _segmentationParameters.contextEnergy_spatialConstant; fs <<"}"; } void TransientAreasSegmentationModuleImpl::run(InputArray inputToProcess, const int channelIndex) { cv::Mat inputToSegment=inputToProcess.getMat(); // preliminary basic error check if ( (inputToSegment.rows*inputToSegment.cols) != (int)_inputToSegment.size()) { std::stringstream errorMsg; errorMsg<<"Input matrix size does not match instance buffers setup !" <<"\n\t Input size is : "<<inputToSegment.rows*inputToSegment.cols <<"\n\t v.s. internalBuffer size is : "<< _inputToSegment.size(); throw cv::Exception(-1, errorMsg.str().c_str(), "SegmentationModule::run", "SegmentationModule.cpp", 0); } if (channelIndex >= inputToSegment.channels()) { std::stringstream errorMsg; errorMsg<<"Cannot access channel index "<<channelIndex<<" on the input matrix with channels quantity = "<<inputToSegment.channels(); throw cv::Exception(-1, errorMsg.str().c_str(), "SegmentationModule::run", "SegmentationModule.cpp", 0); } // create a cv::Mat header for the input valarray // convert to float AND fill the valarray buffer typedef float T; // define here the target pixel format, here, float const int dsttype = cv::DataType<T>::depth; // output buffer is float format cv::Mat dst(inputToSegment.size(), dsttype, &_inputToSegment[0]); inputToSegment.convertTo(dst, dsttype); //cv::imshow("Mask",dst); //cv::waitKey(); // call the low level method _run(_inputToSegment, channelIndex); } void TransientAreasSegmentationModuleImpl::_run(const std::valarray<float> &inputToSegment, const int channelIndex) { #ifdef SEGMENTATIONDEBUG std::cout<<"Input length vs internal buffers length = "<<inputToSegment.size()<<", "<<_localMotion.size()<<std::endl; #endif // preliminary basic error check // FIXME validate basic tests //if (inputToSegment.size() != _localMotion.size()) // throw cv::Exception(-1, "Input matrix size does not match instance buffers setup !", "SegmentationModule::run", "SegmentationModule.cpp", 0); // first square the input in order to increase the signal to noise ratio // get motion local energy _squaringSpatiotemporalLPfilter(&const_cast<std::valarray<float>&>(inputToSegment)[channelIndex*getNBpixels()], &_localMotion[0]); // second low pass filter: access to the neighborhood motion energy _spatiotemporalLPfilter(&_localMotion[0], &_neighborhoodMotion[0], 1); // third low pass filter: access to the background motion energy _spatiotemporalLPfilter(&_localMotion[0], &_contextMotionEnergy[0], 2); // compute the ON and OFF ways (positive and negative values of the difference of the two filterings) float*localMotionPTR=&_localMotion[0], *neighborhoodMotionPTR=&_neighborhoodMotion[0], *contextMotionPTR=&_contextMotionEnergy[0]; // float meanEnergy=LPfilter2.sum()/(float)_LPfilter2.size(); bool *segmentationPicturePTR= &_segmentedAreas[0]; for (unsigned int index=0; index<_filterOutput.getNBpixels() ; ++index, ++segmentationPicturePTR, ++localMotionPTR, ++neighborhoodMotionPTR, contextMotionPTR++) { float generalMotionContextDecision=*neighborhoodMotionPTR-*contextMotionPTR; if (generalMotionContextDecision>0) // local maximum should be detected in this case { /* apply segmentation on local motion superior to its neighborhood * => to segment objects moving faster than their neighborhood */ if (generalMotionContextDecision>_segmentationParameters.thresholdON)// && meanEnergy*1.1<*neighborhoodMotionPTR) { *segmentationPicturePTR=((*localMotionPTR-*neighborhoodMotionPTR)>_segmentationParameters.thresholdON); } else *segmentationPicturePTR=false; } #ifdef USE_LOCALMINIMUMS else // local minimum should be detected in this case { /* apply segmentation for non moving objects * only if the wide area around motion energy is high * => to segment object moving slower than the neighborhood */ if (-1.0*generalMotionContextDecision>_segmentationParameters.thresholdOFF && meanEnergy*0.9>*neighborhoodMotionPTR) { /* in order to segment non moving objects in a camera motion case * we focus on local energy which is much lower than the wide neighborhood */ *segmentationPicturePTR+=(*neighborhoodMotionPTR-*localMotionPTR>_segmentationParameters.thresholdOFF)*127; } } #else else *segmentationPicturePTR=false; #endif } /* #ifdef SEGMENTATIONDEBUG std::cout<<"ON: max, min="<<_localMotionON.min()<<", "<<_localMotionON.max(); std::cout<<"/// \\\ OFF: max, min="<<_localMotionOFF.min()<<", "<<_localMotionOFF.max()<<std::endl; std::cout<<"/// \\\ motion: max, min="<<_globalMotionEnergy.min()<<", "<<_globalMotionEnergy.max()<<std::endl; std::cout<<"/// \\\ thresholds: ON, OFF="<<_thresholdON<<", "<<_thresholdOFF<<", meanEnergy= "<<meanEnergy<<std::endl; #endif */ } void TransientAreasSegmentationModuleImpl::getSegmentationPicture(OutputArray transientAreas) { _convertValarrayBuffer2cvMat(_segmentedAreas, getNBrows(), getNBcolumns(), transientAreas); } void TransientAreasSegmentationModuleImpl::_convertValarrayBuffer2cvMat(const std::valarray<bool> &grayMatrixToConvert, const unsigned int nbRows, const unsigned int nbColumns, OutputArray outBuffer) { // fill output buffer with the valarray buffer const bool *valarrayPTR=get_data(grayMatrixToConvert); outBuffer.create(cv::Size(nbColumns, nbRows), CV_8U); Mat outMat = outBuffer.getMat(); for (unsigned int i=0;i<nbRows;++i) { for (unsigned int j=0;j<nbColumns;++j) { cv::Point2d pixel(j,i); outMat.at<unsigned char>(pixel)=(unsigned char)*(valarrayPTR++); } } } bool TransientAreasSegmentationModuleImpl::_convertCvMat2ValarrayBuffer(InputArray inputMat, std::valarray<float> &outputValarrayMatrix) { const Mat inputMatToConvert=inputMat.getMat(); // first check input consistency if (inputMatToConvert.empty()) throw cv::Exception(-1, "RetinaImpl cannot be applied, input buffer is empty", "RetinaImpl::run", "RetinaImpl.h", 0); // retreive color mode from image input int imageNumberOfChannels = inputMatToConvert.channels(); // convert to float AND fill the valarray buffer typedef float T; // define here the target pixel format, here, float const int dsttype = DataType<T>::depth; // output buffer is float format const unsigned int nbPixels=inputMat.getMat().rows*inputMat.getMat().cols; const unsigned int doubleNBpixels=inputMat.getMat().rows*inputMat.getMat().cols*2; if(imageNumberOfChannels==4) { // create a cv::Mat table (for RGBA planes) cv::Mat planes[4] = { cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]), cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]), cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]) }; planes[3] = cv::Mat(inputMatToConvert.size(), dsttype); // last channel (alpha) does not point on the valarray (not usefull in our case) // split color cv::Mat in 4 planes... it fills valarray directely cv::split(Mat_<Vec<T, 4> >(inputMatToConvert), planes); } else if (imageNumberOfChannels==3) { // create a cv::Mat table (for RGB planes) cv::Mat planes[] = { cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]), cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]), cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]) }; // split color cv::Mat in 3 planes... it fills valarray directely cv::split(cv::Mat_<Vec<T, 3> >(inputMatToConvert), planes); } else if(imageNumberOfChannels==1) { // create a cv::Mat header for the valarray cv::Mat dst(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]); inputMatToConvert.convertTo(dst, dsttype); } else CV_Error(Error::StsUnsupportedFormat, "input image must be single channel (gray levels), bgr format (color) or bgra (color with transparency which won't be considered"); return imageNumberOfChannels>1; // return bool : false for gray level image processing, true for color mode } }} //namespaces end : cv and bioinspired