1 /*========================================================================= 2 * 3 * Copyright Insight Software Consortium 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0.txt 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 *=========================================================================*/ 18 /*========================================================================= 19 * 20 * Portions of this file are subject to the VTK Toolkit Version 3 copyright. 21 * 22 * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 23 * 24 * For complete copyright, license and disclaimer of warranty information 25 * please refer to the NOTICE file at the top of the ITK source tree. 26 * 27 *=========================================================================*/ 28 #ifndef itkImageSource_h 29 #define itkImageSource_h 30 31 #include "itkProcessObject.h" 32 #include "itkImage.h" 33 #include "itkImageRegionSplitterBase.h" 34 #include "itkImageSourceCommon.h" 35 36 namespace itk 37 { 38 39 /** \class ImageSource 40 * \brief Base class for all process objects that output image data. 41 * 42 * ImageSource is the base class for all process objects that output 43 * image data. Specifically, this class defines the GetOutput() method 44 * that returns a pointer to the output image. The class also defines 45 * some internal private data members that are used to manage streaming 46 * of data. 47 * 48 * Memory management in an ImageSource is slightly different than a 49 * standard ProcessObject. ProcessObject's always release the bulk 50 * data associated with their output prior to GenerateData() being 51 * called. ImageSources default to not releasing the bulk data incase 52 * that particular memory block is large enough to hold the new output 53 * values. This avoids unnecessary deallocation/allocation 54 * sequences. ImageSource's can be forced to use a memory management 55 * model similar to the default ProcessObject behaviour by calling 56 * ProcessObject::ReleaseDataBeforeUpdateFlagOn(). A user may want to 57 * set this flag to limit peak memory usage during a pipeline update. 58 * 59 * \ingroup DataSources 60 * \ingroup ITKCommon 61 * 62 * \wiki 63 * \wikiexample{Developer/ImageSource,Produce an image programmatically.} 64 * \endwiki 65 */ 66 template< typename TOutputImage > 67 class ITK_TEMPLATE_EXPORT ImageSource 68 : public ProcessObject, private ImageSourceCommon 69 { 70 public: 71 ITK_DISALLOW_COPY_AND_ASSIGN(ImageSource); 72 73 /** Standard class type aliases. */ 74 using Self = ImageSource; 75 using Superclass = ProcessObject; 76 using Pointer = SmartPointer< Self >; 77 using ConstPointer = SmartPointer< const Self >; 78 79 /** Smart Pointer type to a DataObject. */ 80 using DataObjectPointer = DataObject::Pointer; 81 82 using DataObjectIdentifierType = Superclass::DataObjectIdentifierType; 83 using DataObjectPointerArraySizeType = Superclass::DataObjectPointerArraySizeType; 84 85 /** Run-time type information (and related methods). */ 86 itkTypeMacro(ImageSource, ProcessObject); 87 88 /** Some convenient type alias. */ 89 using OutputImageType = TOutputImage; 90 using OutputImagePointer = typename OutputImageType::Pointer; 91 using OutputImageRegionType = typename OutputImageType::RegionType; 92 using OutputImagePixelType = typename OutputImageType::PixelType; 93 94 /** ImageDimension constant */ 95 static constexpr unsigned int OutputImageDimension = TOutputImage::ImageDimension; 96 97 /** Get the output data of this process object. The output of this 98 * function is not valid until an appropriate Update() method has 99 * been called, either explicitly or implicitly. Both the filter 100 * itself and the data object have Update() methods, and both 101 * methods update the data. Here are three ways to use 102 * GetOutput() and make sure the data is valid. In these 103 * examples, \a image is a pointer to some Image object, and the 104 * particular ProcessObjects involved are filters. The same 105 * examples apply to non-image (e.g. Mesh) data as well. 106 * 107 \code 108 anotherFilter->SetInput( someFilter->GetOutput() ); 109 anotherFilter->Update(); 110 \endcode 111 * 112 * In this situation, \a someFilter and \a anotherFilter are said 113 * to constitute a \b pipeline. 114 * 115 \code 116 image = someFilter->GetOutput(); 117 image->Update(); 118 \endcode 119 * 120 \code 121 someFilter->Update(); 122 image = someFilter->GetOutput(); 123 \endcode 124 * (In the above example, the two lines of code can be in 125 * either order.) 126 * 127 * Note that Update() is not called automatically except within a 128 * pipeline as in the first example. When \b streaming (using a 129 * StreamingImageFilter) is activated, it may be more efficient to 130 * use a pipeline than to call Update() once for each filter in 131 * turn. 132 * 133 * For an image, the data generated is for the requested 134 * Region, which can be set using ImageBase::SetRequestedRegion(). 135 * By default, the largest possible region is requested. 136 * 137 * For Filters which have multiple outputs of different types, the 138 * GetOutput() method assumes the output is of OutputImageType. For 139 * the GetOutput(unsigned int) method, a dynamic_cast is performed 140 * incase the filter has outputs of different types or image 141 * types. Derived classes should have names get methods for these 142 * outputs. 143 */ 144 OutputImageType * GetOutput(); 145 const OutputImageType * GetOutput() const; 146 147 OutputImageType * GetOutput(unsigned int idx); 148 149 /** Graft the specified DataObject onto this ProcessObject's output. 150 * This method grabs a handle to the specified DataObject's bulk 151 * data to use as its output's own bulk data. It also copies the 152 * region ivars (RequestedRegion, BufferedRegion, LargestPossibleRegion) 153 * and meta-data (Spacing, Origin, Direction) from the 154 * specified data object into this filter's output data object. Most 155 * importantly, however, it leaves the Source ivar untouched so the 156 * original pipeline routing is intact. This method is used when a 157 * process object is implemented using a mini-pipeline which is 158 * defined in its GenerateData() method. The usage is: 159 * 160 \code 161 // Setup the mini-pipeline to process the input to this filter 162 // The input is not connected to the pipeline. 163 typename InputImageType::Pointer input = InputImageType::New(); 164 input->Graft( const_cast< InputImageType * >( this->GetInput() ); 165 firstFilterInMiniPipeline->SetInput( input ); 166 167 // setup the mini-pipeline to calculate the correct regions 168 // and write to the appropriate bulk data block 169 lastFilterInMiniPipeline->GraftOutput( this->GetOutput() ); 170 171 // execute the mini-pipeline 172 lastFilterInMiniPipeline->Update(); 173 174 // graft the mini-pipeline output back onto this filter's output. 175 // this is needed to get the appropriate regions passed back. 176 this->GraftOutput( lastFilterInMiniPipeline->GetOutput() ); 177 \endcode 178 * 179 * For proper pipeline execution, a filter using a mini-pipeline 180 * must implement the GenerateInputRequestedRegion(), 181 * GenerateOutputRequestedRegion(), GenerateOutputInformation() and 182 * EnlargeOutputRequestedRegion() methods as necessary to reflect 183 * how the mini-pipeline will execute (in other words, the outer 184 * filter's pipeline mechanism must be consistent with what the 185 * mini-pipeline will do). 186 * */ 187 virtual void GraftOutput(DataObject *output); 188 189 /** Graft the specified data object onto this ProcessObject's named 190 * output. This is similar to the GraftOutput method except it 191 * allows you to specify which output is affected. 192 * See the GraftOutput for general usage information. 193 */ 194 virtual void GraftOutput(const DataObjectIdentifierType & key, DataObject *output); 195 196 /** Graft the specified data object onto this ProcessObject's idx'th 197 * output. This is similar to the GraftOutput method except it 198 * allows you to specify which output is affected. The specified index 199 * must be a valid output number (less than 200 * ProcessObject::GetNumberOfIndexedOutputs()). See the GraftOutput for 201 * general usage information. */ 202 virtual void GraftNthOutput(unsigned int idx, DataObject *output); 203 204 /** Make a DataObject of the correct type to used as the specified 205 * output. Every ProcessObject subclass must be able to create a 206 * DataObject that can be used as a specified output. This method 207 * is automatically called when DataObject::DisconnectPipeline() is 208 * called. DataObject::DisconnectPipeline, disconnects a data object 209 * from being an output of its current source. When the data object 210 * is disconnected, the ProcessObject needs to construct a replacement 211 * output data object so that the ProcessObject is in a valid state. 212 * So DataObject::DisconnectPipeline eventually calls 213 * ProcessObject::MakeOutput. Note that MakeOutput always returns a 214 * SmartPointer to a DataObject. If a subclass of ImageSource has 215 * multiple outputs of different types, then that class must provide 216 * an implementation of MakeOutput(). */ 217 ProcessObject::DataObjectPointer MakeOutput(ProcessObject::DataObjectPointerArraySizeType idx) override; 218 ProcessObject::DataObjectPointer MakeOutput(const ProcessObject::DataObjectIdentifierType &) override; 219 220 protected: 221 ImageSource(); 222 ~ImageSource() override = default; 223 224 /** A version of GenerateData() specific for image processing 225 * filters. This implementation will split the processing across 226 * multiple threads. The buffer is allocated by this method. Then 227 * the BeforeThreadedGenerateData() method is called (if 228 * provided). Then, a series of threads are spawned each calling 229 * DynamicThreadedGenerateData(). After all the threads have completed 230 * processing, the AfterThreadedGenerateData() method is called (if 231 * provided). If an image processing filter cannot be threaded, the 232 * filter should provide an implementation of GenerateData(). That 233 * implementation is responsible for allocating the output buffer. 234 * If a filter can be threaded, it should NOT provide a 235 * GenerateData() method but should provide a 236 * DynamicThreadedGenerateData() instead. 237 * 238 * \sa ThreadedGenerateData() */ 239 void GenerateData() override; 240 241 /** Many filters do special management of image buffer and threading, 242 * so this method provides just the multi-threaded invocation part 243 * of GenerateData() method. */ 244 void ClassicMultiThread(ThreadFunctionType callbackFunction); 245 246 /** If an imaging filter can be implemented as a multithreaded 247 * algorithm, the filter will provide an implementation of 248 * ThreadedGenerateData() or DynamicThreadedGenerateData(). 249 * This superclass will automatically split the output image into a 250 * number of pieces, spawn multiple threads, and call 251 * (Dynamic)ThreadedGenerateData() in each thread. Prior to spawning 252 * threads, the BeforeThreadedGenerateData() method is called. After 253 * all the threads have completed, the AfterThreadedGenerateData() 254 * method is called. If an image processing filter cannot support 255 * threading, that filter should provide an implementation of the 256 * GenerateData() method instead of providing an implementation of 257 * (Dynamic)ThreadedGenerateData(). If a filter provides a GenerateData() 258 * method as its implementation, then the filter is responsible for 259 * allocating the output data. If a filter provides a 260 * (Dynamic)ThreadedGenerateData() method as its implementation, then the 261 * output memory will allocated automatically by this superclass. 262 * The (Dynamic)ThreadedGenerateData() method should only produce the output 263 * specified by "outputThreadRegion" 264 * parameter. (Dynamic)ThreadedGenerateData() cannot write to any other 265 * portion of the output image (as this is responsibility of a 266 * different thread). 267 * 268 * DynamicThreadedGenerateData() is the newer variant without threadId, 269 * and is the preferred signature, which is called by default. This 270 * variant can split the requested region into different number of 271 * pieces depending on current multi-processing load, which allows 272 * better load balancing. The non-dynamic (also known as classic) 273 * ThreadedGenerateData() signature has threadId, and number of pieces 274 * to be split into is known in advance. It is activated by calling 275 * this->DynamicMultiThreadingOff(); in derived class constructor. 276 * It should be used when the 277 * multi-threaded algorithm needs to pre-allocate some data structure 278 * with size dependent on the number of pieces (also known as chunks, 279 * work units, and sometimes also incorrectly as threads). Only 280 * PlatformMultiThreader guarantees that each piece will be processed 281 * in its own specific thread. Pool and TBB multi-threaders maintain 282 * a pool of threads (normally equal to number of processing cores) 283 * which they use to process the pieces. This normally results 284 * in a single thread being reused to process multiple work units. 285 * 286 * \sa GenerateData(), SplitRequestedRegion() */ 287 virtual void ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, 288 ThreadIdType threadId); 289 virtual void DynamicThreadedGenerateData(const OutputImageRegionType & outputRegionForThread); 290 291 /** The GenerateData method normally allocates the buffers for all of the 292 * outputs of a filter. Some filters may want to override this default 293 * behavior. For example, a filter may have multiple outputs with 294 * varying resolution. Or a filter may want to process data in place by 295 * grafting its input to its output. */ 296 virtual void AllocateOutputs(); 297 298 /** If an imaging filter needs to perform processing after the buffer 299 * has been allocated but before threads are spawned, the filter can 300 * can provide an implementation for BeforeThreadedGenerateData(). The 301 * execution flow in the default GenerateData() method will be: 302 * 1) Allocate the output buffer 303 * 2) Call BeforeThreadedGenerateData() 304 * 3) Spawn threads, calling ThreadedGenerateData() in each thread. 305 * 4) Call AfterThreadedGenerateData() 306 * Note that this flow of control is only available if a filter provides 307 * a ThreadedGenerateData() method and NOT a GenerateData() method. */ BeforeThreadedGenerateData()308 virtual void BeforeThreadedGenerateData() {} 309 310 /** If an imaging filter needs to perform processing after all 311 * processing threads have completed, the filter can can provide an 312 * implementation for AfterThreadedGenerateData(). The execution 313 * flow in the default GenerateData() method will be: 314 * 1) Allocate the output buffer 315 * 2) Call BeforeThreadedGenerateData() 316 * 3) Spawn threads, calling ThreadedGenerateData() in each thread. 317 * 4) Call AfterThreadedGenerateData() 318 * Note that this flow of control is only available if a filter provides 319 * a ThreadedGenerateData() method and NOT a GenerateData() method. */ AfterThreadedGenerateData()320 virtual void AfterThreadedGenerateData() {} 321 322 /** \brief Returns the default image region splitter 323 * 324 * This is an adapter function from the private common base class to 325 * the interface of this class. 326 */ GetGlobalDefaultSplitter()327 static const ImageRegionSplitterBase* GetGlobalDefaultSplitter() 328 { 329 return ImageSourceCommon::GetGlobalDefaultSplitter(); 330 } 331 332 /** \brief Get the image splitter to split the image for multi-threading. 333 * 334 * The Splitter object divides the image into regions for threading 335 * or streaming. The algorithms on how to split an images are 336 * separated into class so that they can be easily be reused. When 337 * deriving from this class to write a filter consideration to the 338 * algorithm used to divide the image should be made. If a change is 339 * desired this method should be overridden to return the 340 * appropriate object. 341 */ 342 virtual const ImageRegionSplitterBase* GetImageRegionSplitter() const; 343 344 /** Split the output's RequestedRegion into "pieces" pieces, returning 345 * region "i" as "splitRegion". This method is called concurrently 346 * "pieces" times. The regions must not overlap. The method returns the number 347 * of pieces that the routine is capable of splitting the output RequestedRegion, 348 * i.e. return value is less than or equal to "pieces". 349 * 350 * To override the algorithm used split the image this method should 351 * no longer be overridden. Instead, the algorithm should be 352 * implemented in a ImageRegionSplitterBase class, and the 353 * GetImageRegionSplitter should overridden to return the splitter 354 * object with the desired algorithm. 355 * 356 * \sa GetImageRegionSplitter 357 **/ 358 virtual 359 unsigned int SplitRequestedRegion(unsigned int i, unsigned int pieces, OutputImageRegionType & splitRegion); 360 361 /** Static function used as a "callback" by the classic MultiThreader. 362 * The threading library will call this routine for each thread, 363 * which will delegate the control to ThreadedGenerateData(). */ 364 static ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION ThreaderCallback(void *arg); 365 366 /** Internal structure used for passing image data into the threading library */ 367 struct ThreadStruct 368 { 369 Pointer Filter; 370 }; 371 372 void PrintSelf(std::ostream & os, Indent indent) const override; 373 374 /** Whether to use classic multi-threading infrastructure (OFF by default). 375 * Classic multi-threading uses derived class' ImageRegionSplitter, 376 * thus enabling custom region splitting methods. */ 377 itkGetConstMacro(DynamicMultiThreading, bool); 378 itkSetMacro(DynamicMultiThreading, bool); 379 itkBooleanMacro(DynamicMultiThreading); 380 381 bool m_DynamicMultiThreading; 382 }; 383 } // end namespace itk 384 385 #ifndef ITK_MANUAL_INSTANTIATION 386 #include "itkImageSource.hxx" 387 #endif 388 389 #endif 390