File: itkOpenCVVideoCapture.hxx

package info (click to toggle)
insighttoolkit4 4.10.1-dfsg1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 416,780 kB
  • ctags: 104,347
  • sloc: cpp: 553,142; ansic: 142,389; fortran: 34,788; python: 16,392; lisp: 2,070; sh: 1,862; tcl: 993; java: 362; perl: 200; makefile: 111; csh: 81; pascal: 69; xml: 19; ruby: 10
file content (386 lines) | stat: -rw-r--r-- 10,244 bytes parent folder | download
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*=========================================================================
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkOpenCVVideoCapture_hxx
#define itkOpenCVVideoCapture_hxx

#include "itkOpenCVVideoCapture.h"
#include "itkNumericTraits.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "cv.h"

namespace itk
{

//-CONSTRUCTORS----------------------------------------------------------------

//
// OpenCVVideoCapture()
//
template<typename TVideoStream>
OpenCVVideoCapture<TVideoStream>::OpenCVVideoCapture()
{
  m_VideoStream = ITK_NULLPTR;

  // Default to reporting 24fps. This may change once RealTime is implemented
  m_FpS = 24;

  // Default to mp4.2
  m_FourCC = CV_FOURCC('M','P','4','2');
}

//
// OpenCVVideoCapture(videoStream)
//
template<typename TVideoStream>
OpenCVVideoCapture<TVideoStream>::OpenCVVideoCapture(TVideoStream* videoStream)
{
  m_VideoStream = videoStream;

  // Default to reporting 24fps. This may change once RealTime is implemented
  m_FpS = 24;

  // Default to mp4.2
  m_FourCC = CV_FOURCC('M','P','4','2');
}


//-OPEN CLOSE FUNCTIONALITY----------------------------------------------------

//
// open(videoStream)
//
template<typename TVideoStream>
bool OpenCVVideoCapture<TVideoStream>::open(TVideoStream* videoStream)
{
  // We only support 2D
  if (this->Dimensions != 2)
    {
    return false;
    }

  // Make sure pointer isn't null
  if (!videoStream)
    {
    return false;
    }
  m_VideoStream = videoStream;
  return true;
}

//
// release
//
template<typename TVideoStream>
void OpenCVVideoCapture<TVideoStream>::release()
{
  m_VideoStream = ITK_NULLPTR;
}


//-FRAME ACCESS----------------------------------------------------------------

//
// grab
//
template<typename TVideoStream>
bool OpenCVVideoCapture<TVideoStream>::grab()
{
  // We only support 2D
  if (this->Dimensions != 2)
    {
    return false;
    }

  // Move the current frame forward by 1
  SizeValueType currentFrame = m_VideoStream->GetRequestedTemporalRegion().GetFrameStart();
  return set(CV_CAP_PROP_POS_FRAMES, currentFrame + 1);
}

//
// retrieve
//
template<typename TVideoStream>
bool OpenCVVideoCapture<TVideoStream>::retrieve(cv::Mat& image, int itkNotUsed(channel))
{
  // We only support 2D
  if (this->Dimensions != 2)
    {
    image.release();
    return false;
    }

  // Make sure VideoStream isn't null
  if (!m_VideoStream)
    {
    image.release();
    return false;
    }

  // Get the requested frame
  SizeValueType frameNum = m_VideoStream->GetRequestedTemporalRegion().GetFrameStart();
  FrameType* frame = m_VideoStream->GetFrame(frameNum);

  // Make sure frame isn't null
  if (!frame)
    {
    image.release();
    return false;
    }

  // Instantiate the cv::Mat with the proper size and type
  typename FrameType::SizeType size = frame->GetLargestPossibleRegion().GetSize();
  unsigned int depth = cv::DataDepth< typename itk::NumericTraits< PixelType >::ValueType >::value;
  unsigned int channels = itk::NumericTraits< PixelType >::MeasurementVectorType::Dimension;
  int matrixType = CV_MAKETYPE(depth, channels);

  // Copy the pixels -- There is probably a faster way to do this
  typedef itk::ImageRegionConstIteratorWithIndex<FrameType> ITKIterType;
  ITKIterType itkIter(frame, frame->GetLargestPossibleRegion());

  // Currently only support mono and RGB (unsigned) char pixels
  IplImage* iplImg = cvCreateImage( cvSize(size[0], size[1]), IPL_DEPTH_8U, channels );
  if (matrixType == CV_8UC1 || matrixType == CV_8SC1)
    {
    // Insert the buffer into iplImg
    cvSetData(iplImg,
      reinterpret_cast<char*>(frame->GetBufferPointer()),
      iplImg->widthStep);
    }
  else if (matrixType == CV_8UC3 || matrixType == CV_8SC3)
    {
    // Place the contents of the buffer into an OpenCV image
    IplImage* tempImg = cvCreateImage( cvSize(size[0], size[1]), IPL_DEPTH_8U, channels );

    // Insert the buffer into tempImg
    cvSetData(tempImg,
      reinterpret_cast<char*>(frame->GetBufferPointer()),
      tempImg->widthStep);

    // Convert to BGR
    cvCvtColor(tempImg, iplImg, CV_RGB2BGR);
    }
  else
    {
    itkExceptionMacro("itk::OpenCVVideoCaptures -> Pixel type not supported");
    }

  // Pass off to the Mat
  image.create(size[0], size[1], matrixType);
  image = cv::cvarrToMat(iplImg, true);

  // Return success
  return true;
}

//
// operator >>
//
template<typename TVideoStream>
OpenCVVideoCapture<TVideoStream>& OpenCVVideoCapture<TVideoStream>::operator >>(cv::Mat& image)
{
  if (!read(image))
    {
    image.release();
    }
  return *this;
}

//
// read
//
template<typename TVideoStream>
bool OpenCVVideoCapture<TVideoStream>::read(cv::Mat& image)
{
  if (!grab())
    {
    image.release();
    return false;
    }
  else
    {
    return retrieve(image);
    }
}


//-PROPERTIES------------------------------------------------------------------

//
// set
//
template<typename TVideoStream>
bool OpenCVVideoCapture<TVideoStream>::set(int propId, double value)
{
  // Make sure the VideoSource isn't null
  if (!m_VideoStream)
    {
    return false;
    }

  // Variables for use in cases
  SizeValueType maxFrame;
  SizeValueType nextFrame;
  SizeValueType ratioFrameOffset;
  SizeValueType newFrame;
  TemporalRegion largestPossible;
  TemporalRegion newRequest;

  // Handle all of the different properties
  switch (propId)
    {
    // Figure out the frame numbers from the value -- This is not currently supported
    case CV_CAP_PROP_POS_MSEC:
      itkExceptionMacro("OpenCVVideoCapture: Video Pipeline does not currently support RealTime");
      break;

    // Set the frame start of the requested region and update the pipeline
    case CV_CAP_PROP_POS_FRAMES:

      // Get the largest temporal region and make sure it has some duration
      m_VideoStream->UpdateOutputInformation();
      largestPossible = m_VideoStream->GetLargestPossibleTemporalRegion();

      if (!largestPossible.GetFrameDuration())
        {
        return false;
        }

      // Verify that we aren't trying to skip past the end of the video
      maxFrame =
        largestPossible.GetFrameStart() + largestPossible.GetFrameDuration() - 1;
      nextFrame = (long)value;
      if (nextFrame > maxFrame)
        {
        return false;
        }

      // Move the requested temporal region
      newRequest.SetFrameStart(nextFrame);
      newRequest.SetFrameDuration(1);
      m_VideoStream->SetRequestedTemporalRegion(newRequest);

      // Make sure we're requesting the largest possible spatial region
      m_VideoStream->SetFrameRequestedSpatialRegion(nextFrame,
        m_VideoStream->GetFrameLargestPossibleSpatialRegion(nextFrame));

      // Update the pipeline
      m_VideoStream->Update();
      break;

    // Figure out the frame number from the AVI ratio and set accordingly
    case CV_CAP_PROP_POS_AVI_RATIO:

      // Compute the new frame
      m_VideoStream->UpdateOutputInformation();
      largestPossible = m_VideoStream->GetLargestPossibleTemporalRegion();
      ratioFrameOffset = (SizeValueType)((double)largestPossible.GetFrameDuration() * value);
      newFrame = largestPossible.GetFrameStart() + ratioFrameOffset;

      // Use the CV_CAP_PROP_POS_FRAMES property to update
      set(CV_CAP_PROP_POS_FRAMES, newFrame);
      break;

    // Set FourCC
    case CV_CAP_PROP_FOURCC:
      m_FourCC = (int)value;
      break;

    // Set FpS
    case CV_CAP_PROP_FPS:
      m_FpS = value;
      break;

    // We don't support setting anything else
    default:
      return false;
    }

  // Return success
  return true;
}

//
// get
//
template<typename TVideoStream>
double OpenCVVideoCapture<TVideoStream>::get(int propId)
{
  // Make sure the VideoSource isn't null
  if (!m_VideoStream)
    {
    return 0;
    }

  // Variables for use in cases
  SizeValueType frameNum = m_VideoStream->GetRequestedTemporalRegion().GetFrameStart();
  SizeValueType currentOffset;
  TemporalRegion largest;
  TemporalRegion requested;

  // Handle all of the different properties
  switch (propId)
    {
    // Figure out the frame numbers from the value -- This is not currently supported
    case CV_CAP_PROP_POS_MSEC:
      itkExceptionMacro("OpenCVVideoCapture: Video Pipeline does not currently support RealTime");
      break;

    // Get the frame start of the requested region and update the pipeline
    case CV_CAP_PROP_POS_FRAMES:
      return frameNum;

    // Figure out the frame number from the AVI ratio and set accordingly
    case CV_CAP_PROP_POS_AVI_RATIO:

      // Compute the frame number from the ratio
      m_VideoStream->UpdateOutputInformation();
      largest = m_VideoStream->GetLargestPossibleTemporalRegion();
      requested = m_VideoStream->GetRequestedTemporalRegion();
      currentOffset = requested.GetFrameStart() - largest.GetFrameStart();
      return (double)currentOffset / (double)largest.GetFrameDuration();

    // Get FourCC
    case CV_CAP_PROP_FOURCC:
      return m_FourCC;

    // Set FpS
    case CV_CAP_PROP_FPS:
      return m_FpS;

    // Get Frame Width
    case CV_CAP_PROP_FRAME_WIDTH:
      m_VideoStream->UpdateOutputInformation();
      return m_VideoStream->GetFrameLargestPossibleSpatialRegion(frameNum).GetSize()[0];

    // Get Frame Height
    case CV_CAP_PROP_FRAME_HEIGHT:
      m_VideoStream->UpdateOutputInformation();
      return m_VideoStream->GetFrameLargestPossibleSpatialRegion(frameNum).GetSize()[1];

    // We don't support getting anything else
    default:
      return false;
    }

  // Return success
  return true;
}

} // end namespace itk

#endif