PageRenderTime 148ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/OpenCV-2.4.2/modules/highgui/doc/reading_and_writing_images_and_video.rst

#
ReStructuredText | 534 lines | 310 code | 224 blank | 0 comment | 0 complexity | 3bc579708e3d542e153305565687195f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. Reading and Writing Images and Video
  2. ====================================
  3. .. highlight:: cpp
  4. imdecode
  5. ------------
  6. Reads an image from a buffer in memory.
  7. .. ocv:function:: Mat imdecode( InputArray buf, int flags )
  8. .. ocv:cfunction:: IplImage* cvDecodeImage( const CvMat* buf, int iscolor=CV_LOAD_IMAGE_COLOR)
  9. .. ocv:cfunction:: CvMat* cvDecodeImageM( const CvMat* buf, int iscolor=CV_LOAD_IMAGE_COLOR)
  10. .. ocv:pyfunction:: cv2.imdecode(buf, flags) -> retval
  11. :param buf: Input array or vector of bytes.
  12. :param flags: The same flags as in :ocv:func:`imread` .
  13. The function reads an image from the specified buffer in the memory.
  14. If the buffer is too short or contains invalid data, the empty matrix/image is returned.
  15. See
  16. :ocv:func:`imread` for the list of supported formats and flags description.
  17. imencode
  18. ------------
  19. Encodes an image into a memory buffer.
  20. .. ocv:function:: bool imencode( const string& ext, InputArray img, vector<uchar>& buf, const vector<int>& params=vector<int>())
  21. .. ocv:cfunction:: CvMat* cvEncodeImage( const char* ext, const CvArr* image, const int* params=0 )
  22. .. ocv:pyfunction:: cv2.imencode(ext, img[, params]) -> retval, buf
  23. :param ext: File extension that defines the output format.
  24. :param img: Image to be written.
  25. :param buf: Output buffer resized to fit the compressed image.
  26. :param params: Format-specific parameters. See :ocv:func:`imwrite` .
  27. The function compresses the image and stores it in the memory buffer that is resized to fit the result.
  28. See
  29. :ocv:func:`imwrite` for the list of supported formats and flags description.
  30. .. note:: ``cvEncodeImage`` returns single-row matrix of type ``CV_8UC1`` that contains encoded image as array of bytes.
  31. imread
  32. ----------
  33. Loads an image from a file.
  34. .. ocv:function:: Mat imread( const string& filename, int flags=1 )
  35. .. ocv:pyfunction:: cv2.imread(filename[, flags]) -> retval
  36. .. ocv:cfunction:: IplImage* cvLoadImage( const char* filename, int iscolor=CV_LOAD_IMAGE_COLOR )
  37. .. ocv:cfunction:: CvMat* cvLoadImageM( const char* filename, int iscolor=CV_LOAD_IMAGE_COLOR )
  38. .. ocv:pyoldfunction:: cv.LoadImage(filename, iscolor=CV_LOAD_IMAGE_COLOR) -> None
  39. .. ocv:pyoldfunction:: cv.LoadImageM(filename, iscolor=CV_LOAD_IMAGE_COLOR) -> None
  40. :param filename: Name of file to be loaded.
  41. :param flags: Flags specifying the color type of a loaded image:
  42. * **>0** Return a 3-channel color image
  43. * **=0** Return a grayscale image
  44. * **<0** Return the loaded image as is. Note that in the current implementation the alpha channel, if any, is stripped from the output image. For example, a 4-channel RGBA image is loaded as RGB if :math:`flags\ge0` .
  45. The function ``imread`` loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( ``Mat::data==NULL`` ). Currently, the following file formats are supported:
  46. * Windows bitmaps - ``*.bmp, *.dib`` (always supported)
  47. * JPEG files - ``*.jpeg, *.jpg, *.jpe`` (see the *Notes* section)
  48. * JPEG 2000 files - ``*.jp2`` (see the *Notes* section)
  49. * Portable Network Graphics - ``*.png`` (see the *Notes* section)
  50. * Portable image format - ``*.pbm, *.pgm, *.ppm`` (always supported)
  51. * Sun rasters - ``*.sr, *.ras`` (always supported)
  52. * TIFF files - ``*.tiff, *.tif`` (see the *Notes* section)
  53. .. note::
  54. * The function determines the type of an image by the content, not by the file extension.
  55. * On Microsoft Windows* OS and MacOSX*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX.
  56. * On Linux*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian* and Ubuntu*) to get the codec support or turn on the ``OPENCV_BUILD_3RDPARTY_LIBS`` flag in CMake.
  57. imwrite
  58. -----------
  59. Saves an image to a specified file.
  60. .. ocv:function:: bool imwrite( const string& filename, InputArray img, const vector<int>& params=vector<int>() )
  61. .. ocv:pyfunction:: cv2.imwrite(filename, img[, params]) -> retval
  62. .. ocv:cfunction:: int cvSaveImage( const char* filename, const CvArr* image, const int* params=0 )
  63. .. ocv:pyoldfunction:: cv.SaveImage(filename, image)-> None
  64. :param filename: Name of the file.
  65. :param image: Image to be saved.
  66. :param params: Format-specific save parameters encoded as pairs ``paramId_1, paramValue_1, paramId_2, paramValue_2, ...`` . The following parameters are currently supported:
  67. * For JPEG, it can be a quality ( ``CV_IMWRITE_JPEG_QUALITY`` ) from 0 to 100 (the higher is the better). Default value is 95.
  68. * For PNG, it can be the compression level ( ``CV_IMWRITE_PNG_COMPRESSION`` ) from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3.
  69. * For PPM, PGM, or PBM, it can be a binary format flag ( ``CV_IMWRITE_PXM_BINARY`` ), 0 or 1. Default value is 1.
  70. The function ``imwrite`` saves the image to the specified file. The image format is chosen based on the ``filename`` extension (see
  71. :ocv:func:`imread` for the list of extensions). Only 8-bit (or 16-bit in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use
  72. :ocv:func:`Mat::convertTo` , and
  73. :ocv:func:`cvtColor` to convert it before saving. Or, use the universal XML I/O functions to save the image to XML or YAML format.
  74. It is possible to store PNG images with an alpha channel using this function. To do this, create 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535. The sample below shows how to create such a BGRA image and store to PNG file. It also demonstrates how to set custom compression parameters ::
  75. #include <vector>
  76. #include <stdio.h>
  77. #include <opencv2/opencv.hpp>
  78. using namespace cv;
  79. using namespace std;
  80. void createAlphaMat(Mat &mat)
  81. {
  82. for (int i = 0; i < mat.rows; ++i) {
  83. for (int j = 0; j < mat.cols; ++j) {
  84. Vec4b& rgba = mat.at<Vec4b>(i, j);
  85. rgba[0] = UCHAR_MAX;
  86. rgba[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX);
  87. rgba[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX);
  88. rgba[3] = saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2]));
  89. }
  90. }
  91. }
  92. int main(int argv, char **argc)
  93. {
  94. // Create mat with alpha channel
  95. Mat mat(480, 640, CV_8UC4);
  96. createAlphaMat(mat);
  97. vector<int> compression_params;
  98. compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  99. compression_params.push_back(9);
  100. try {
  101. imwrite("alpha.png", mat, compression_params);
  102. }
  103. catch (runtime_error& ex) {
  104. fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
  105. return 1;
  106. }
  107. fprintf(stdout, "Saved PNG file with alpha data.\n");
  108. return 0;
  109. }
  110. VideoCapture
  111. ------------
  112. .. ocv:class:: VideoCapture
  113. Class for video capturing from video files or cameras.
  114. The class provides C++ API for capturing video from cameras or for reading video files. Here is how the class can be used: ::
  115. #include "opencv2/opencv.hpp"
  116. using namespace cv;
  117. int main(int, char**)
  118. {
  119. VideoCapture cap(0); // open the default camera
  120. if(!cap.isOpened()) // check if we succeeded
  121. return -1;
  122. Mat edges;
  123. namedWindow("edges",1);
  124. for(;;)
  125. {
  126. Mat frame;
  127. cap >> frame; // get a new frame from camera
  128. cvtColor(frame, edges, CV_BGR2GRAY);
  129. GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
  130. Canny(edges, edges, 0, 30, 3);
  131. imshow("edges", edges);
  132. if(waitKey(30) >= 0) break;
  133. }
  134. // the camera will be deinitialized automatically in VideoCapture destructor
  135. return 0;
  136. }
  137. .. note:: In C API the black-box structure ``CvCapture`` is used instead of ``VideoCapture``.
  138. VideoCapture::VideoCapture
  139. ------------------------------
  140. VideoCapture constructors.
  141. .. ocv:function:: VideoCapture::VideoCapture()
  142. .. ocv:function:: VideoCapture::VideoCapture(const string& filename)
  143. .. ocv:function:: VideoCapture::VideoCapture(int device)
  144. .. ocv:pyfunction:: cv2.VideoCapture() -> <VideoCapture object>
  145. .. ocv:pyfunction:: cv2.VideoCapture(filename) -> <VideoCapture object>
  146. .. ocv:pyfunction:: cv2.VideoCapture(device) -> <VideoCapture object>
  147. .. ocv:cfunction:: CvCapture* cvCaptureFromCAM( int device )
  148. .. ocv:pyoldfunction:: cv.CaptureFromCAM(index) -> CvCapture
  149. .. ocv:cfunction:: CvCapture* cvCaptureFromFile( const char* filename )
  150. .. ocv:pyoldfunction:: cv.CaptureFromFile(filename) -> CvCapture
  151. :param filename: name of the opened video file
  152. :param device: id of the opened video capturing device (i.e. a camera index). If there is a single camera connected, just pass 0.
  153. .. note:: In C API, when you finished working with video, release ``CvCapture`` structure with ``cvReleaseCapture()``, or use ``Ptr<CvCapture>`` that calls ``cvReleaseCapture()`` automatically in the destructor.
  154. VideoCapture::open
  155. ---------------------
  156. Open video file or a capturing device for video capturing
  157. .. ocv:function:: bool VideoCapture::open(const string& filename)
  158. .. ocv:function:: bool VideoCapture::open(int device)
  159. .. ocv:pyfunction:: cv2.VideoCapture.open(filename) -> retval
  160. .. ocv:pyfunction:: cv2.VideoCapture.open(device) -> retval
  161. :param filename: name of the opened video file
  162. :param device: id of the opened video capturing device (i.e. a camera index).
  163. The methods first call :ocv:func:`VideoCapture::release` to close the already opened file or camera.
  164. VideoCapture::isOpened
  165. ----------------------
  166. Returns true if video capturing has been initialized already.
  167. .. ocv:function:: bool VideoCapture::isOpened()
  168. .. ocv:pyfunction:: cv2.VideoCapture.isOpened() -> retval
  169. If the previous call to ``VideoCapture`` constructor or ``VideoCapture::open`` succeeded, the method returns true.
  170. VideoCapture::release
  171. ---------------------
  172. Closes video file or capturing device.
  173. .. ocv:function:: void VideoCapture::release()
  174. .. ocv:pyfunction:: cv2.VideoCapture.release() -> None
  175. .. ocv:cfunction:: void cvReleaseCapture(CvCapture** capture)
  176. The methods are automatically called by subsequent :ocv:func:`VideoCapture::open` and by ``VideoCapture`` destructor.
  177. The C function also deallocates memory and clears ``*capture`` pointer.
  178. VideoCapture::grab
  179. ---------------------
  180. Grabs the next frame from video file or capturing device.
  181. .. ocv:function:: bool VideoCapture::grab()
  182. .. ocv:pyfunction:: cv2.VideoCapture.grab() -> retval
  183. .. ocv:cfunction:: int cvGrabFrame(CvCapture* capture)
  184. .. ocv:pyoldfunction:: cv.GrabFrame(capture) -> int
  185. The methods/functions grab the next frame from video file or camera and return true (non-zero) in the case of success.
  186. The primary use of the function is in multi-camera environments, especially when the cameras do not have hardware synchronization. That is, you call ``VideoCapture::grab()`` for each camera and after that call the slower method ``VideoCapture::retrieve()`` to decode and get frame from each camera. This way the overhead on demosaicing or motion jpeg decompression etc. is eliminated and the retrieved frames from different cameras will be closer in time.
  187. Also, when a connected camera is multi-head (for example, a stereo camera or a Kinect device), the correct way of retrieving data from it is to call `VideoCapture::grab` first and then call :ocv:func:`VideoCapture::retrieve` one or more times with different values of the ``channel`` parameter. See http://code.opencv.org/svn/opencv/trunk/opencv/samples/cpp/kinect_maps.cpp
  188. VideoCapture::retrieve
  189. ----------------------
  190. Decodes and returns the grabbed video frame.
  191. .. ocv:function:: bool VideoCapture::retrieve(Mat& image, int channel=0)
  192. .. ocv:pyfunction:: cv2.VideoCapture.retrieve([image[, channel]]) -> retval, image
  193. .. ocv:cfunction:: IplImage* cvRetrieveFrame( CvCapture* capture, int streamIdx=0 )
  194. .. ocv:pyoldfunction:: cv.RetrieveFrame(capture) -> image
  195. The methods/functions decode and return the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
  196. .. note:: OpenCV 1.x functions ``cvRetrieveFrame`` and ``cv.RetrieveFrame`` return image stored inside the video capturing structure. It is not allowed to modify or release the image! You can copy the frame using :ocv:cfunc:`cvCloneImage` and then do whatever you want with the copy.
  197. VideoCapture::read
  198. ----------------------
  199. Grabs, decodes and returns the next video frame.
  200. .. ocv:function:: VideoCapture& VideoCapture::operator >> (Mat& image)
  201. .. ocv:function:: bool VideoCapture::read(Mat& image)
  202. .. ocv:pyfunction:: cv2.VideoCapture.read([image]) -> retval, image
  203. .. ocv:cfunction:: IplImage* cvQueryFrame(CvCapture* capture)
  204. .. ocv:pyoldfunction:: cv.QueryFrame(capture) -> image
  205. The methods/functions combine :ocv:func:`VideoCapture::grab` and :ocv:func:`VideoCapture::retrieve` in one call. This is the most convenient method for reading video files or capturing data from decode and return the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
  206. .. note:: OpenCV 1.x functions ``cvRetrieveFrame`` and ``cv.RetrieveFrame`` return image stored inside the video capturing structure. It is not allowed to modify or release the image! You can copy the frame using :ocv:cfunc:`cvCloneImage` and then do whatever you want with the copy.
  207. VideoCapture::get
  208. ---------------------
  209. Returns the specified ``VideoCapture`` property
  210. .. ocv:function:: double VideoCapture::get(int propId)
  211. .. ocv:pyfunction:: cv2.VideoCapture.get(propId) -> retval
  212. .. ocv:cfunction:: double cvGetCaptureProperty( CvCapture* capture, int property_id )
  213. .. ocv:pyoldfunction:: cv.GetCaptureProperty(capture, property_id) -> float
  214. :param propId: Property identifier. It can be one of the following:
  215. * **CV_CAP_PROP_POS_MSEC** Current position of the video file in milliseconds or video capture timestamp.
  216. * **CV_CAP_PROP_POS_FRAMES** 0-based index of the frame to be decoded/captured next.
  217. * **CV_CAP_PROP_POS_AVI_RATIO** Relative position of the video file: 0 - start of the film, 1 - end of the film.
  218. * **CV_CAP_PROP_FRAME_WIDTH** Width of the frames in the video stream.
  219. * **CV_CAP_PROP_FRAME_HEIGHT** Height of the frames in the video stream.
  220. * **CV_CAP_PROP_FPS** Frame rate.
  221. * **CV_CAP_PROP_FOURCC** 4-character code of codec.
  222. * **CV_CAP_PROP_FRAME_COUNT** Number of frames in the video file.
  223. * **CV_CAP_PROP_FORMAT** Format of the Mat objects returned by ``retrieve()`` .
  224. * **CV_CAP_PROP_MODE** Backend-specific value indicating the current capture mode.
  225. * **CV_CAP_PROP_BRIGHTNESS** Brightness of the image (only for cameras).
  226. * **CV_CAP_PROP_CONTRAST** Contrast of the image (only for cameras).
  227. * **CV_CAP_PROP_SATURATION** Saturation of the image (only for cameras).
  228. * **CV_CAP_PROP_HUE** Hue of the image (only for cameras).
  229. * **CV_CAP_PROP_GAIN** Gain of the image (only for cameras).
  230. * **CV_CAP_PROP_EXPOSURE** Exposure (only for cameras).
  231. * **CV_CAP_PROP_CONVERT_RGB** Boolean flags indicating whether images should be converted to RGB.
  232. * **CV_CAP_PROP_WHITE_BALANCE** Currently not supported
  233. * **CV_CAP_PROP_RECTIFICATION** Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
  234. **Note**: When querying a property that is not supported by the backend used by the ``VideoCapture`` class, value 0 is returned.
  235. VideoCapture::set
  236. ---------------------
  237. Sets a property in the ``VideoCapture``.
  238. .. ocv:function:: bool VideoCapture::set( int propId, double value )
  239. .. ocv:pyfunction:: cv2.VideoCapture.set(propId, value) -> retval
  240. .. ocv:cfunction:: int cvSetCaptureProperty( CvCapture* capture, int property_id, double value )
  241. .. ocv:pyoldfunction:: cv.SetCaptureProperty(capture, property_id, value) -> retval
  242. :param propId: Property identifier. It can be one of the following:
  243. * **CV_CAP_PROP_POS_MSEC** Current position of the video file in milliseconds.
  244. * **CV_CAP_PROP_POS_FRAMES** 0-based index of the frame to be decoded/captured next.
  245. * **CV_CAP_PROP_POS_AVI_RATIO** Relative position of the video file: 0 - start of the film, 1 - end of the film.
  246. * **CV_CAP_PROP_FRAME_WIDTH** Width of the frames in the video stream.
  247. * **CV_CAP_PROP_FRAME_HEIGHT** Height of the frames in the video stream.
  248. * **CV_CAP_PROP_FPS** Frame rate.
  249. * **CV_CAP_PROP_FOURCC** 4-character code of codec.
  250. * **CV_CAP_PROP_FRAME_COUNT** Number of frames in the video file.
  251. * **CV_CAP_PROP_FORMAT** Format of the Mat objects returned by ``retrieve()`` .
  252. * **CV_CAP_PROP_MODE** Backend-specific value indicating the current capture mode.
  253. * **CV_CAP_PROP_BRIGHTNESS** Brightness of the image (only for cameras).
  254. * **CV_CAP_PROP_CONTRAST** Contrast of the image (only for cameras).
  255. * **CV_CAP_PROP_SATURATION** Saturation of the image (only for cameras).
  256. * **CV_CAP_PROP_HUE** Hue of the image (only for cameras).
  257. * **CV_CAP_PROP_GAIN** Gain of the image (only for cameras).
  258. * **CV_CAP_PROP_EXPOSURE** Exposure (only for cameras).
  259. * **CV_CAP_PROP_CONVERT_RGB** Boolean flags indicating whether images should be converted to RGB.
  260. * **CV_CAP_PROP_WHITE_BALANCE** Currently unsupported
  261. * **CV_CAP_PROP_RECTIFICATION** Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
  262. :param value: Value of the property.
  263. VideoWriter
  264. -----------
  265. .. ocv:class:: VideoWriter
  266. Video writer class.
  267. VideoWriter::VideoWriter
  268. ------------------------
  269. VideoWriter constructors
  270. .. ocv:function:: VideoWriter::VideoWriter()
  271. .. ocv:function:: VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  272. .. ocv:pyfunction:: cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) -> <VideoWriter object>
  273. .. ocv:cfunction:: CvVideoWriter* cvCreateVideoWriter( const char* filename, int fourcc, double fps, CvSize frame_size, int is_color=1 )
  274. .. ocv:pyoldfunction:: cv.CreateVideoWriter(filename, fourcc, fps, frame_size, is_color=true) -> CvVideoWriter
  275. .. ocv:pyfunction:: cv2.VideoWriter.isOpened() -> retval
  276. .. ocv:pyfunction:: cv2.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor]) -> retval
  277. .. ocv:pyfunction:: cv2.VideoWriter.write(image) -> None
  278. :param filename: Name of the output video file.
  279. :param fourcc: 4-character code of codec used to compress the frames. For example, ``CV_FOURCC('P','I','M,'1')`` is a MPEG-1 codec, ``CV_FOURCC('M','J','P','G')`` is a motion-jpeg codec etc.
  280. :param fps: Framerate of the created video stream.
  281. :param frameSize: Size of the video frames.
  282. :param isColor: If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only).
  283. The constructors/functions initialize video writers. On Linux FFMPEG is used to write videos; on Windows FFMPEG or VFW is used; on MacOSX QTKit is used.
  284. ReleaseVideoWriter
  285. ------------------
  286. Releases the AVI writer.
  287. .. ocv:cfunction:: void cvReleaseVideoWriter( CvVideoWriter** writer )
  288. The function should be called after you finished using ``CvVideoWriter`` opened with :ocv:cfunc:`CreateVideoWriter`.
  289. VideoWriter::open
  290. -----------------
  291. Initializes or reinitializes video writer.
  292. .. ocv:function:: bool VideoWriter::open(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  293. .. ocv:pyfunction:: cv2.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor]) -> retval
  294. The method opens video writer. Parameters are the same as in the constructor :ocv:func:`VideoWriter::VideoWriter`.
  295. VideoWriter::isOpened
  296. ---------------------
  297. Returns true if video writer has been successfully initialized.
  298. .. ocv:function:: bool VideoWriter::isOpened()
  299. .. ocv:pyfunction:: cv2.VideoWriter.isOpened() -> retval
  300. VideoWriter::write
  301. ------------------
  302. Writes the next video frame
  303. .. ocv:function:: VideoWriter& VideoWriter::operator << (const Mat& image)
  304. .. ocv:function:: void VideoWriter::write(const Mat& image)
  305. .. ocv:pyfunction:: cv2.VideoWriter.write(image) -> None
  306. .. ocv:cfunction:: int cvWriteFrame( CvVideoWriter* writer, const IplImage* image )
  307. .. ocv:pyoldfunction:: cv.WriteFrame(writer, image)->int
  308. :param writer: Video writer structure (OpenCV 1.x API)
  309. :param image: The written frame
  310. The functions/methods write the specified image to video file. It must have the same size as has been specified when opening the video writer.