Repository: puku0x/cvdrone Branch: master Commit: 4011ff486e5c Files: 660 Total size: 5.4 MB Directory structure: gitextract_ueim0nzk/ ├── .gitignore ├── build/ │ ├── cleanup.bat │ ├── unix/ │ │ └── makefile │ ├── vs2010/ │ │ ├── test.sln │ │ ├── test.vcxproj │ │ └── test.vcxproj.filters │ ├── vs2012/ │ │ ├── test.sln │ │ ├── test.vcxproj │ │ └── test.vcxproj.filters │ ├── vs2013/ │ │ ├── test.sln │ │ ├── test.vcxproj │ │ └── test.vcxproj.filters │ └── vs2015/ │ ├── test.sln │ ├── test.vcxproj │ └── test.vcxproj.filters ├── cvdrone-license-BSD.txt ├── cvdrone-license-LGPL.txt ├── licenses/ │ ├── FFmpeg-LGPLv2.1.txt │ ├── ffmpeg.txt │ ├── glut.txt │ ├── opencv.txt │ ├── parrot.txt │ ├── parrotdisclaimer.txt │ └── pthreads-w32.txt ├── readme.txt ├── samples/ │ ├── camera.xml │ ├── old/ │ │ ├── sample_camera_calibration.cpp │ │ ├── sample_condens_tracking.cpp │ │ ├── sample_deadreckoning.cpp │ │ ├── sample_deadreckoning_kalman.cpp │ │ ├── sample_default.cpp │ │ ├── sample_default2.cpp │ │ ├── sample_detection.cpp │ │ ├── sample_detection2.cpp │ │ ├── sample_flight_animation.cpp │ │ ├── sample_hog.cpp │ │ ├── sample_hough_circle.cpp │ │ ├── sample_kalman_tracking.cpp │ │ ├── sample_led_animation.cpp │ │ ├── sample_marker_based_ar.cpp │ │ ├── sample_minimal.cpp │ │ ├── sample_navdata.cpp │ │ ├── sample_optical_flow.cpp │ │ ├── sample_stitching.cpp │ │ ├── sample_vanishing_point.cpp │ │ ├── sample_video_record.cpp │ │ └── sample_video_writer.cpp │ ├── sample_camera_calibration.cpp │ ├── sample_deadreckoning.cpp │ ├── sample_deadreckoning_kalman.cpp │ ├── sample_default.cpp │ ├── sample_detection.cpp │ ├── sample_flight_animation.cpp │ ├── sample_hog.cpp │ ├── sample_kalman_tracking.cpp │ ├── sample_led_animation.cpp │ ├── sample_marker_based_ar.cpp │ ├── sample_minimal.cpp │ ├── sample_navdata.cpp │ ├── sample_optical_flow.cpp │ ├── sample_stitching.cpp │ ├── sample_tracking.cpp │ ├── sample_video_record.cpp │ └── sample_video_writer.cpp └── src/ ├── 3rdparty/ │ ├── ffmpeg/ │ │ ├── include/ │ │ │ ├── inttypes.h │ │ │ ├── libavcodec/ │ │ │ │ ├── avcodec.h │ │ │ │ ├── avfft.h │ │ │ │ ├── dxva2.h │ │ │ │ ├── old_codec_ids.h │ │ │ │ ├── vaapi.h │ │ │ │ ├── vda.h │ │ │ │ ├── vdpau.h │ │ │ │ ├── version.h │ │ │ │ └── xvmc.h │ │ │ ├── libavdevice/ │ │ │ │ ├── avdevice.h │ │ │ │ └── version.h │ │ │ ├── libavfilter/ │ │ │ │ ├── asrc_abuffer.h │ │ │ │ ├── avcodec.h │ │ │ │ ├── avfilter.h │ │ │ │ ├── avfiltergraph.h │ │ │ │ ├── buffersink.h │ │ │ │ ├── buffersrc.h │ │ │ │ └── version.h │ │ │ ├── libavformat/ │ │ │ │ ├── avformat.h │ │ │ │ ├── avio.h │ │ │ │ └── version.h │ │ │ ├── libavutil/ │ │ │ │ ├── adler32.h │ │ │ │ ├── aes.h │ │ │ │ ├── attributes.h │ │ │ │ ├── audio_fifo.h │ │ │ │ ├── audioconvert.h │ │ │ │ ├── avassert.h │ │ │ │ ├── avconfig.h │ │ │ │ ├── avstring.h │ │ │ │ ├── avutil.h │ │ │ │ ├── base64.h │ │ │ │ ├── blowfish.h │ │ │ │ ├── bprint.h │ │ │ │ ├── bswap.h │ │ │ │ ├── buffer.h │ │ │ │ ├── channel_layout.h │ │ │ │ ├── common.h │ │ │ │ ├── cpu.h │ │ │ │ ├── crc.h │ │ │ │ ├── dict.h │ │ │ │ ├── downmix_info.h │ │ │ │ ├── error.h │ │ │ │ ├── eval.h │ │ │ │ ├── ffversion.h │ │ │ │ ├── fifo.h │ │ │ │ ├── file.h │ │ │ │ ├── frame.h │ │ │ │ ├── hmac.h │ │ │ │ ├── imgutils.h │ │ │ │ ├── intfloat.h │ │ │ │ ├── intfloat_readwrite.h │ │ │ │ ├── intreadwrite.h │ │ │ │ ├── lfg.h │ │ │ │ ├── log.h │ │ │ │ ├── lzo.h │ │ │ │ ├── macros.h │ │ │ │ ├── mathematics.h │ │ │ │ ├── md5.h │ │ │ │ ├── mem.h │ │ │ │ ├── murmur3.h │ │ │ │ ├── old_pix_fmts.h │ │ │ │ ├── opt.h │ │ │ │ ├── parseutils.h │ │ │ │ ├── pixdesc.h │ │ │ │ ├── pixfmt.h │ │ │ │ ├── random_seed.h │ │ │ │ ├── rational.h │ │ │ │ ├── ripemd.h │ │ │ │ ├── samplefmt.h │ │ │ │ ├── sha.h │ │ │ │ ├── sha512.h │ │ │ │ ├── stereo3d.h │ │ │ │ ├── time.h │ │ │ │ ├── timecode.h │ │ │ │ ├── timestamp.h │ │ │ │ ├── version.h │ │ │ │ └── xtea.h │ │ │ ├── libswresample/ │ │ │ │ ├── swresample.h │ │ │ │ └── version.h │ │ │ ├── libswscale/ │ │ │ │ ├── swscale.h │ │ │ │ └── version.h │ │ │ └── stdint.h │ │ └── lib/ │ │ ├── avcodec.lib │ │ ├── avdevice.lib │ │ ├── avfilter.lib │ │ ├── avformat.lib │ │ ├── avutil.lib │ │ ├── swresample.lib │ │ └── swscale.lib │ ├── glut/ │ │ ├── include/ │ │ │ └── GL/ │ │ │ └── glut.h │ │ └── lib/ │ │ ├── glut.def │ │ └── glut32.lib │ ├── opencv/ │ │ ├── include/ │ │ │ ├── opencv/ │ │ │ │ ├── cv.h │ │ │ │ ├── cv.hpp │ │ │ │ ├── cvaux.h │ │ │ │ ├── cvaux.hpp │ │ │ │ ├── cvwimage.h │ │ │ │ ├── cxcore.h │ │ │ │ ├── cxcore.hpp │ │ │ │ ├── cxeigen.hpp │ │ │ │ ├── cxmisc.h │ │ │ │ ├── highgui.h │ │ │ │ └── ml.h │ │ │ └── opencv2/ │ │ │ ├── aruco/ │ │ │ │ ├── charuco.hpp │ │ │ │ └── dictionary.hpp │ │ │ ├── aruco.hpp │ │ │ ├── bgsegm.hpp │ │ │ ├── bioinspired/ │ │ │ │ ├── bioinspired.hpp │ │ │ │ ├── retina.hpp │ │ │ │ ├── retinafasttonemapping.hpp │ │ │ │ └── transientareassegmentationmodule.hpp │ │ │ ├── bioinspired.hpp │ │ │ ├── calib3d/ │ │ │ │ ├── calib3d.hpp │ │ │ │ └── calib3d_c.h │ │ │ ├── calib3d.hpp │ │ │ ├── ccalib/ │ │ │ │ ├── multicalib.hpp │ │ │ │ ├── omnidir.hpp │ │ │ │ └── randpattern.hpp │ │ │ ├── ccalib.hpp │ │ │ ├── core/ │ │ │ │ ├── affine.hpp │ │ │ │ ├── base.hpp │ │ │ │ ├── bufferpool.hpp │ │ │ │ ├── core.hpp │ │ │ │ ├── core_c.h │ │ │ │ ├── cuda/ │ │ │ │ │ ├── block.hpp │ │ │ │ │ ├── border_interpolate.hpp │ │ │ │ │ ├── color.hpp │ │ │ │ │ ├── common.hpp │ │ │ │ │ ├── datamov_utils.hpp │ │ │ │ │ ├── detail/ │ │ │ │ │ │ ├── color_detail.hpp │ │ │ │ │ │ ├── reduce.hpp │ │ │ │ │ │ ├── reduce_key_val.hpp │ │ │ │ │ │ ├── transform_detail.hpp │ │ │ │ │ │ ├── type_traits_detail.hpp │ │ │ │ │ │ └── vec_distance_detail.hpp │ │ │ │ │ ├── dynamic_smem.hpp │ │ │ │ │ ├── emulation.hpp │ │ │ │ │ ├── filters.hpp │ │ │ │ │ ├── funcattrib.hpp │ │ │ │ │ ├── functional.hpp │ │ │ │ │ ├── limits.hpp │ │ │ │ │ ├── reduce.hpp │ │ │ │ │ ├── saturate_cast.hpp │ │ │ │ │ ├── scan.hpp │ │ │ │ │ ├── simd_functions.hpp │ │ │ │ │ ├── transform.hpp │ │ │ │ │ ├── type_traits.hpp │ │ │ │ │ ├── utility.hpp │ │ │ │ │ ├── vec_distance.hpp │ │ │ │ │ ├── vec_math.hpp │ │ │ │ │ ├── vec_traits.hpp │ │ │ │ │ ├── warp.hpp │ │ │ │ │ ├── warp_reduce.hpp │ │ │ │ │ └── warp_shuffle.hpp │ │ │ │ ├── cuda.hpp │ │ │ │ ├── cuda.inl.hpp │ │ │ │ ├── cuda_stream_accessor.hpp │ │ │ │ ├── cuda_types.hpp │ │ │ │ ├── cvdef.h │ │ │ │ ├── cvstd.hpp │ │ │ │ ├── cvstd.inl.hpp │ │ │ │ ├── directx.hpp │ │ │ │ ├── eigen.hpp │ │ │ │ ├── fast_math.hpp │ │ │ │ ├── hal/ │ │ │ │ │ ├── hal.hpp │ │ │ │ │ ├── interface.h │ │ │ │ │ ├── intrin.hpp │ │ │ │ │ ├── intrin_cpp.hpp │ │ │ │ │ ├── intrin_neon.hpp │ │ │ │ │ └── intrin_sse.hpp │ │ │ │ ├── ippasync.hpp │ │ │ │ ├── mat.hpp │ │ │ │ ├── mat.inl.hpp │ │ │ │ ├── matx.hpp │ │ │ │ ├── neon_utils.hpp │ │ │ │ ├── ocl.hpp │ │ │ │ ├── ocl_genbase.hpp │ │ │ │ ├── opengl.hpp │ │ │ │ ├── operations.hpp │ │ │ │ ├── optim.hpp │ │ │ │ ├── persistence.hpp │ │ │ │ ├── private.cuda.hpp │ │ │ │ ├── private.hpp │ │ │ │ ├── ptr.inl.hpp │ │ │ │ ├── saturate.hpp │ │ │ │ ├── sse_utils.hpp │ │ │ │ ├── traits.hpp │ │ │ │ ├── types.hpp │ │ │ │ ├── types_c.h │ │ │ │ ├── utility.hpp │ │ │ │ ├── va_intel.hpp │ │ │ │ ├── version.hpp │ │ │ │ └── wimage.hpp │ │ │ ├── core.hpp │ │ │ ├── cvconfig.h │ │ │ ├── datasets/ │ │ │ │ ├── ar_hmdb.hpp │ │ │ │ ├── ar_sports.hpp │ │ │ │ ├── dataset.hpp │ │ │ │ ├── fr_adience.hpp │ │ │ │ ├── fr_lfw.hpp │ │ │ │ ├── gr_chalearn.hpp │ │ │ │ ├── gr_skig.hpp │ │ │ │ ├── hpe_humaneva.hpp │ │ │ │ ├── hpe_parse.hpp │ │ │ │ ├── ir_affine.hpp │ │ │ │ ├── ir_robot.hpp │ │ │ │ ├── is_bsds.hpp │ │ │ │ ├── is_weizmann.hpp │ │ │ │ ├── msm_epfl.hpp │ │ │ │ ├── msm_middlebury.hpp │ │ │ │ ├── or_imagenet.hpp │ │ │ │ ├── or_mnist.hpp │ │ │ │ ├── or_pascal.hpp │ │ │ │ ├── or_sun.hpp │ │ │ │ ├── pd_caltech.hpp │ │ │ │ ├── pd_inria.hpp │ │ │ │ ├── slam_kitti.hpp │ │ │ │ ├── slam_tumindoor.hpp │ │ │ │ ├── tr_chars.hpp │ │ │ │ ├── tr_icdar.hpp │ │ │ │ ├── tr_svt.hpp │ │ │ │ ├── track_vot.hpp │ │ │ │ └── util.hpp │ │ │ ├── dnn/ │ │ │ │ ├── blob.hpp │ │ │ │ ├── blob.inl.hpp │ │ │ │ ├── dict.hpp │ │ │ │ ├── dnn.hpp │ │ │ │ ├── dnn.inl.hpp │ │ │ │ └── layer.hpp │ │ │ ├── dnn.hpp │ │ │ ├── dpm.hpp │ │ │ ├── face/ │ │ │ │ ├── facerec.hpp │ │ │ │ └── predict_collector.hpp │ │ │ ├── face.hpp │ │ │ ├── features2d/ │ │ │ │ └── features2d.hpp │ │ │ ├── features2d.hpp │ │ │ ├── flann/ │ │ │ │ ├── all_indices.h │ │ │ │ ├── allocator.h │ │ │ │ ├── any.h │ │ │ │ ├── autotuned_index.h │ │ │ │ ├── composite_index.h │ │ │ │ ├── config.h │ │ │ │ ├── defines.h │ │ │ │ ├── dist.h │ │ │ │ ├── dummy.h │ │ │ │ ├── dynamic_bitset.h │ │ │ │ ├── flann.hpp │ │ │ │ ├── flann_base.hpp │ │ │ │ ├── general.h │ │ │ │ ├── ground_truth.h │ │ │ │ ├── hdf5.h │ │ │ │ ├── heap.h │ │ │ │ ├── hierarchical_clustering_index.h │ │ │ │ ├── index_testing.h │ │ │ │ ├── kdtree_index.h │ │ │ │ ├── kdtree_single_index.h │ │ │ │ ├── kmeans_index.h │ │ │ │ ├── linear_index.h │ │ │ │ ├── logger.h │ │ │ │ ├── lsh_index.h │ │ │ │ ├── lsh_table.h │ │ │ │ ├── matrix.h │ │ │ │ ├── miniflann.hpp │ │ │ │ ├── nn_index.h │ │ │ │ ├── object_factory.h │ │ │ │ ├── params.h │ │ │ │ ├── random.h │ │ │ │ ├── result_set.h │ │ │ │ ├── sampling.h │ │ │ │ ├── saving.h │ │ │ │ ├── simplex_downhill.h │ │ │ │ └── timer.h │ │ │ ├── flann.hpp │ │ │ ├── fuzzy/ │ │ │ │ ├── fuzzy_F0_math.hpp │ │ │ │ ├── fuzzy_image.hpp │ │ │ │ └── types.hpp │ │ │ ├── fuzzy.hpp │ │ │ ├── highgui/ │ │ │ │ ├── highgui.hpp │ │ │ │ └── highgui_c.h │ │ │ ├── highgui.hpp │ │ │ ├── imgcodecs/ │ │ │ │ ├── imgcodecs.hpp │ │ │ │ ├── imgcodecs_c.h │ │ │ │ └── ios.h │ │ │ ├── imgcodecs.hpp │ │ │ ├── imgproc/ │ │ │ │ ├── detail/ │ │ │ │ │ └── distortion_model.hpp │ │ │ │ ├── imgproc.hpp │ │ │ │ ├── imgproc_c.h │ │ │ │ └── types_c.h │ │ │ ├── imgproc.hpp │ │ │ ├── line_descriptor/ │ │ │ │ └── descriptor.hpp │ │ │ ├── line_descriptor.hpp │ │ │ ├── ml/ │ │ │ │ └── ml.hpp │ │ │ ├── ml.hpp │ │ │ ├── objdetect/ │ │ │ │ ├── detection_based_tracker.hpp │ │ │ │ ├── objdetect.hpp │ │ │ │ └── objdetect_c.h │ │ │ ├── objdetect.hpp │ │ │ ├── opencv.hpp │ │ │ ├── opencv_modules.hpp │ │ │ ├── optflow/ │ │ │ │ └── motempl.hpp │ │ │ ├── optflow.hpp │ │ │ ├── photo/ │ │ │ │ ├── cuda.hpp │ │ │ │ ├── photo.hpp │ │ │ │ └── photo_c.h │ │ │ ├── photo.hpp │ │ │ ├── plot.hpp │ │ │ ├── reg/ │ │ │ │ ├── map.hpp │ │ │ │ ├── mapaffine.hpp │ │ │ │ ├── mapper.hpp │ │ │ │ ├── mappergradaffine.hpp │ │ │ │ ├── mappergradeuclid.hpp │ │ │ │ ├── mappergradproj.hpp │ │ │ │ ├── mappergradshift.hpp │ │ │ │ ├── mappergradsimilar.hpp │ │ │ │ ├── mapperpyramid.hpp │ │ │ │ ├── mapprojec.hpp │ │ │ │ └── mapshift.hpp │ │ │ ├── rgbd/ │ │ │ │ └── linemod.hpp │ │ │ ├── rgbd.hpp │ │ │ ├── saliency/ │ │ │ │ ├── saliencyBaseClasses.hpp │ │ │ │ └── saliencySpecializedClasses.hpp │ │ │ ├── saliency.hpp │ │ │ ├── shape/ │ │ │ │ ├── emdL1.hpp │ │ │ │ ├── hist_cost.hpp │ │ │ │ ├── shape.hpp │ │ │ │ ├── shape_distance.hpp │ │ │ │ └── shape_transformer.hpp │ │ │ ├── shape.hpp │ │ │ ├── stereo/ │ │ │ │ ├── descriptor.hpp │ │ │ │ ├── matching.hpp │ │ │ │ └── stereo.hpp │ │ │ ├── stereo.hpp │ │ │ ├── stitching/ │ │ │ │ ├── detail/ │ │ │ │ │ ├── autocalib.hpp │ │ │ │ │ ├── blenders.hpp │ │ │ │ │ ├── camera.hpp │ │ │ │ │ ├── exposure_compensate.hpp │ │ │ │ │ ├── matchers.hpp │ │ │ │ │ ├── motion_estimators.hpp │ │ │ │ │ ├── seam_finders.hpp │ │ │ │ │ ├── timelapsers.hpp │ │ │ │ │ ├── util.hpp │ │ │ │ │ ├── util_inl.hpp │ │ │ │ │ ├── warpers.hpp │ │ │ │ │ └── warpers_inl.hpp │ │ │ │ └── warpers.hpp │ │ │ ├── stitching.hpp │ │ │ ├── structured_light/ │ │ │ │ ├── graycodepattern.hpp │ │ │ │ └── structured_light.hpp │ │ │ ├── structured_light.hpp │ │ │ ├── superres/ │ │ │ │ └── optical_flow.hpp │ │ │ ├── superres.hpp │ │ │ ├── surface_matching/ │ │ │ │ ├── icp.hpp │ │ │ │ ├── pose_3d.hpp │ │ │ │ ├── ppf_helpers.hpp │ │ │ │ ├── ppf_match_3d.hpp │ │ │ │ └── t_hash_int.hpp │ │ │ ├── surface_matching.hpp │ │ │ ├── text/ │ │ │ │ ├── erfilter.hpp │ │ │ │ └── ocr.hpp │ │ │ ├── text.hpp │ │ │ ├── tracking/ │ │ │ │ ├── feature.hpp │ │ │ │ ├── kalman_filters.hpp │ │ │ │ ├── onlineBoosting.hpp │ │ │ │ ├── onlineMIL.hpp │ │ │ │ ├── tldDataset.hpp │ │ │ │ ├── tracker.hpp │ │ │ │ └── tracking.hpp │ │ │ ├── tracking.hpp │ │ │ ├── video/ │ │ │ │ ├── background_segm.hpp │ │ │ │ ├── tracking.hpp │ │ │ │ ├── tracking_c.h │ │ │ │ └── video.hpp │ │ │ ├── video.hpp │ │ │ ├── videoio/ │ │ │ │ ├── cap_ios.h │ │ │ │ ├── videoio.hpp │ │ │ │ └── videoio_c.h │ │ │ ├── videoio.hpp │ │ │ ├── videostab/ │ │ │ │ ├── deblurring.hpp │ │ │ │ ├── fast_marching.hpp │ │ │ │ ├── fast_marching_inl.hpp │ │ │ │ ├── frame_source.hpp │ │ │ │ ├── global_motion.hpp │ │ │ │ ├── inpainting.hpp │ │ │ │ ├── log.hpp │ │ │ │ ├── motion_core.hpp │ │ │ │ ├── motion_stabilizing.hpp │ │ │ │ ├── optical_flow.hpp │ │ │ │ ├── outlier_rejection.hpp │ │ │ │ ├── ring_buffer.hpp │ │ │ │ ├── stabilizer.hpp │ │ │ │ └── wobble_suppression.hpp │ │ │ ├── videostab.hpp │ │ │ ├── xfeatures2d/ │ │ │ │ ├── cuda.hpp │ │ │ │ └── nonfree.hpp │ │ │ ├── xfeatures2d.hpp │ │ │ ├── ximgproc/ │ │ │ │ ├── disparity_filter.hpp │ │ │ │ ├── edge_filter.hpp │ │ │ │ ├── estimated_covariance.hpp │ │ │ │ ├── fast_hough_transform.hpp │ │ │ │ ├── lsc.hpp │ │ │ │ ├── seeds.hpp │ │ │ │ ├── segmentation.hpp │ │ │ │ ├── slic.hpp │ │ │ │ ├── sparse_match_interpolator.hpp │ │ │ │ └── structured_edge_detection.hpp │ │ │ ├── ximgproc.hpp │ │ │ ├── xobjdetect.hpp │ │ │ ├── xphoto/ │ │ │ │ ├── dct_image_denoising.hpp │ │ │ │ ├── inpainting.hpp │ │ │ │ └── white_balance.hpp │ │ │ └── xphoto.hpp │ │ └── lib/ │ │ ├── vs2010/ │ │ │ ├── opencv_aruco310.lib │ │ │ ├── opencv_bgsegm310.lib │ │ │ ├── opencv_bioinspired310.lib │ │ │ ├── opencv_calib3d310.lib │ │ │ ├── opencv_ccalib310.lib │ │ │ ├── opencv_core310.lib │ │ │ ├── opencv_datasets310.lib │ │ │ ├── opencv_dnn310.lib │ │ │ ├── opencv_dpm310.lib │ │ │ ├── opencv_face310.lib │ │ │ ├── opencv_features2d310.lib │ │ │ ├── opencv_flann310.lib │ │ │ ├── opencv_fuzzy310.lib │ │ │ ├── opencv_highgui310.lib │ │ │ ├── opencv_imgcodecs310.lib │ │ │ ├── opencv_imgproc310.lib │ │ │ ├── opencv_line_descriptor310.lib │ │ │ ├── opencv_ml310.lib │ │ │ ├── opencv_objdetect310.lib │ │ │ ├── opencv_optflow310.lib │ │ │ ├── opencv_photo310.lib │ │ │ ├── opencv_plot310.lib │ │ │ ├── opencv_reg310.lib │ │ │ ├── opencv_rgbd310.lib │ │ │ ├── opencv_saliency310.lib │ │ │ ├── opencv_shape310.lib │ │ │ ├── opencv_stereo310.lib │ │ │ ├── opencv_stitching310.lib │ │ │ ├── opencv_structured_light310.lib │ │ │ ├── opencv_superres310.lib │ │ │ ├── opencv_surface_matching310.lib │ │ │ ├── opencv_text310.lib │ │ │ ├── opencv_tracking310.lib │ │ │ ├── opencv_video310.lib │ │ │ ├── opencv_videoio310.lib │ │ │ ├── opencv_videostab310.lib │ │ │ ├── opencv_xfeatures2d310.lib │ │ │ ├── opencv_ximgproc310.lib │ │ │ ├── opencv_xobjdetect310.lib │ │ │ └── opencv_xphoto310.lib │ │ ├── vs2012/ │ │ │ ├── opencv_aruco310.lib │ │ │ ├── opencv_bgsegm310.lib │ │ │ ├── opencv_bioinspired310.lib │ │ │ ├── opencv_calib3d310.lib │ │ │ ├── opencv_ccalib310.lib │ │ │ ├── opencv_core310.lib │ │ │ ├── opencv_datasets310.lib │ │ │ ├── opencv_dnn310.lib │ │ │ ├── opencv_dpm310.lib │ │ │ ├── opencv_face310.lib │ │ │ ├── opencv_features2d310.lib │ │ │ ├── opencv_flann310.lib │ │ │ ├── opencv_fuzzy310.lib │ │ │ ├── opencv_highgui310.lib │ │ │ ├── opencv_imgcodecs310.lib │ │ │ ├── opencv_imgproc310.lib │ │ │ ├── opencv_line_descriptor310.lib │ │ │ ├── opencv_ml310.lib │ │ │ ├── opencv_objdetect310.lib │ │ │ ├── opencv_optflow310.lib │ │ │ ├── opencv_photo310.lib │ │ │ ├── opencv_plot310.lib │ │ │ ├── opencv_reg310.lib │ │ │ ├── opencv_rgbd310.lib │ │ │ ├── opencv_saliency310.lib │ │ │ ├── opencv_shape310.lib │ │ │ ├── opencv_stereo310.lib │ │ │ ├── opencv_stitching310.lib │ │ │ ├── opencv_structured_light310.lib │ │ │ ├── opencv_superres310.lib │ │ │ ├── opencv_surface_matching310.lib │ │ │ ├── opencv_text310.lib │ │ │ ├── opencv_tracking310.lib │ │ │ ├── opencv_video310.lib │ │ │ ├── opencv_videoio310.lib │ │ │ ├── opencv_videostab310.lib │ │ │ ├── opencv_xfeatures2d310.lib │ │ │ ├── opencv_ximgproc310.lib │ │ │ ├── opencv_xobjdetect310.lib │ │ │ └── opencv_xphoto310.lib │ │ ├── vs2013/ │ │ │ ├── opencv_aruco310.lib │ │ │ ├── opencv_bgsegm310.lib │ │ │ ├── opencv_bioinspired310.lib │ │ │ ├── opencv_calib3d310.lib │ │ │ ├── opencv_ccalib310.lib │ │ │ ├── opencv_core310.lib │ │ │ ├── opencv_datasets310.lib │ │ │ ├── opencv_dnn310.lib │ │ │ ├── opencv_dpm310.lib │ │ │ ├── opencv_face310.lib │ │ │ ├── opencv_features2d310.lib │ │ │ ├── opencv_flann310.lib │ │ │ ├── opencv_fuzzy310.lib │ │ │ ├── opencv_highgui310.lib │ │ │ ├── opencv_imgcodecs310.lib │ │ │ ├── opencv_imgproc310.lib │ │ │ ├── opencv_line_descriptor310.lib │ │ │ ├── opencv_ml310.lib │ │ │ ├── opencv_objdetect310.lib │ │ │ ├── opencv_optflow310.lib │ │ │ ├── opencv_photo310.lib │ │ │ ├── opencv_plot310.lib │ │ │ ├── opencv_reg310.lib │ │ │ ├── opencv_rgbd310.lib │ │ │ ├── opencv_saliency310.lib │ │ │ ├── opencv_shape310.lib │ │ │ ├── opencv_stereo310.lib │ │ │ ├── opencv_stitching310.lib │ │ │ ├── opencv_structured_light310.lib │ │ │ ├── opencv_superres310.lib │ │ │ ├── opencv_surface_matching310.lib │ │ │ ├── opencv_text310.lib │ │ │ ├── opencv_tracking310.lib │ │ │ ├── opencv_video310.lib │ │ │ ├── opencv_videoio310.lib │ │ │ ├── opencv_videostab310.lib │ │ │ ├── opencv_xfeatures2d310.lib │ │ │ ├── opencv_ximgproc310.lib │ │ │ ├── opencv_xobjdetect310.lib │ │ │ └── opencv_xphoto310.lib │ │ └── vs2015/ │ │ ├── opencv_aruco310.lib │ │ ├── opencv_bgsegm310.lib │ │ ├── opencv_bioinspired310.lib │ │ ├── opencv_calib3d310.lib │ │ ├── opencv_ccalib310.lib │ │ ├── opencv_core310.lib │ │ ├── opencv_datasets310.lib │ │ ├── opencv_dnn310.lib │ │ ├── opencv_dpm310.lib │ │ ├── opencv_face310.lib │ │ ├── opencv_features2d310.lib │ │ ├── opencv_flann310.lib │ │ ├── opencv_fuzzy310.lib │ │ ├── opencv_highgui310.lib │ │ ├── opencv_imgcodecs310.lib │ │ ├── opencv_imgproc310.lib │ │ ├── opencv_line_descriptor310.lib │ │ ├── opencv_ml310.lib │ │ ├── opencv_objdetect310.lib │ │ ├── opencv_optflow310.lib │ │ ├── opencv_photo310.lib │ │ ├── opencv_plot310.lib │ │ ├── opencv_reg310.lib │ │ ├── opencv_rgbd310.lib │ │ ├── opencv_saliency310.lib │ │ ├── opencv_shape310.lib │ │ ├── opencv_stereo310.lib │ │ ├── opencv_stitching310.lib │ │ ├── opencv_structured_light310.lib │ │ ├── opencv_superres310.lib │ │ ├── opencv_surface_matching310.lib │ │ ├── opencv_text310.lib │ │ ├── opencv_tracking310.lib │ │ ├── opencv_video310.lib │ │ ├── opencv_videoio310.lib │ │ ├── opencv_videostab310.lib │ │ ├── opencv_xfeatures2d310.lib │ │ ├── opencv_ximgproc310.lib │ │ ├── opencv_xobjdetect310.lib │ │ └── opencv_xphoto310.lib │ ├── packtpub/ │ │ ├── BGRAVideoFrame.h │ │ ├── CameraCalibration.hpp │ │ ├── DebugHelpers.hpp │ │ ├── GeometryTypes.hpp │ │ ├── Marker.hpp │ │ ├── MarkerDetector.hpp │ │ └── TinyLA.hpp │ └── pthread/ │ ├── include/ │ │ ├── pthread.h │ │ ├── sched.h │ │ └── semaphore.h │ └── lib/ │ └── pthreadVC2.lib ├── ardrone/ │ ├── ardrone.cpp │ ├── ardrone.h │ ├── command.cpp │ ├── config.cpp │ ├── navdata.cpp │ ├── tcp.cpp │ ├── udp.cpp │ ├── uvlc.h │ ├── version.cpp │ └── video.cpp ├── main.cpp └── resource/ ├── resource.rc └── test.exe.manifest ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.ncb *.suo *.user *.sdf *.ipch *.opensdf *.o *.a obj *.iobj *.ipdb *.exe ================================================ FILE: build/cleanup.bat ================================================ echo Let's clean them up. echo Cleaning vs2005\... del vs2005\*.ncb del vs2005\*.user del vs2005\*.suo /a:h rmdir vs2005\obj /s /q echo Cleaning vs2008\... del vs2008\*.ncb del vs2008\*.user del vs2008\*.suo /a:h rmdir vs2008\obj /s /q echo Cleaning vs2010\... del vs2010\*.sdf del vs2010\*.user del vs2010\*.suo /a:h rmdir vs2010\ipch /s /q rmdir vs2010\obj /s /q echo Cleaning vs2012\... del vs2012\*.sdf del vs2012\*.user del vs2012\*.suo /a:h rmdir vs2012\ipch /s /q rmdir vs2012\obj /s /q echo Cleaning vs2013\... del vs2013\*.sdf del vs2013\*.user del vs2013\*.suo /a:h rmdir vs2013\ipch /s /q rmdir vs2013\obj /s /q echo Cleaning vs2015\... del vs2015\*.sdf del vs2015\*.user del vs2015\*.suo /a:h rmdir vs2015\.vs /s /q rmdir vs2015\obj /s /q echo Finished. Yeah ! ================================================ FILE: build/unix/makefile ================================================ #sudo apt-get install build-essential #sudo apt-get install ffmpeg #sudo apt-get install libav-tools #sudo apt-get install libopencv-dev CXX = g++ CXXFLAGS = -O2 -Wall -D__STDC_CONSTANT_MACROS `pkg-config --libs --cflags opencv` LIBS = -lm \ -lpthread \ -lavutil \ -lavformat \ -lavcodec \ -lswscale OBJS = ../../src/ardrone/ardrone.o \ ../../src/ardrone/command.o \ ../../src/ardrone/config.o \ ../../src/ardrone/udp.o \ ../../src/ardrone/tcp.o \ ../../src/ardrone/navdata.o \ ../../src/ardrone/version.o \ ../../src/ardrone/video.o \ ../../src/main.o PROGRAM = test.a $(PROGRAM): $(OBJS) $(CXX) $(OBJS) -o $(PROGRAM) $(CXXFLAGS) $(LDFLAGS) $(LIBS) clean:; rm -f *.o *~ $(PROGRAM) $(OBJS) install: $(PROGRAM) install -s $(PROGRAM) $(DEST) ================================================ FILE: build/vs2010/test.sln ================================================  Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test.vcxproj", "{81224E4A-C4B9-418E-B87E-224D1ACD2FF1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.ActiveCfg = Release|Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: build/vs2010/test.vcxproj ================================================  Release Win32 Debug Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1} player Win32Proj Application false MultiByte true Application false MultiByte <_ProjectFileVersion>10.0.30319.1 ..\..\bin\vs2010\ .\obj\debug\ true ..\..\bin\vs2010\ .\obj\release\ false ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;NDEBUG;_CONSOLE;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) MultiThreadedDLL Level3 ProgramDatabase 4244;4819;4996;%(DisableSpecificWarnings) wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2010;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) false true .\obj\release\release.pdb Console 0 0 true true MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) Disabled ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;_DEBUG;_CONSOLE;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL Level3 EditAndContinue wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2010;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) true .\obj\debug\debug.pdb Console MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) ================================================ FILE: build/vs2010/test.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {550b0fc4-8368-48d8-b626-03df6c7d9121} {06e2d9e1-74fe-4d29-9e94-f3ea80429740} {19ba6cc5-e937-4c72-8c33-8d3581893111} {4cceaaea-23b5-4465-aeec-3b00075be422} Source Files Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Header Files\ardrone Resource Files ================================================ FILE: build/vs2012/test.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Express 2012 for Windows Desktop Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test.vcxproj", "{81224E4A-C4B9-418E-B87E-224D1ACD2FF1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.ActiveCfg = Release|Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: build/vs2012/test.vcxproj ================================================  Debug Win32 Release Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1} Win32Proj Application false MultiByte true v110 Application false MultiByte v110 <_ProjectFileVersion>10.0.30319.1 ..\..\bin\vs2012\ .\obj\debug\ true ..\..\bin\vs2012\ .\obj\release\ false Disabled ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;_DEBUG;_CONSOLE;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL Level3 EditAndContinue wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2012;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) true .\obj\debug\debug.pdb Console MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;NDEBUG;_CONSOLE;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) MultiThreadedDLL Level3 ProgramDatabase 4244;4819;4996;%(DisableSpecificWarnings) wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2012;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) false true .\obj\release\release.pdb Console 0 0 true true MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) ================================================ FILE: build/vs2012/test.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {550b0fc4-8368-48d8-b626-03df6c7d9121} {06e2d9e1-74fe-4d29-9e94-f3ea80429740} {19ba6cc5-e937-4c72-8c33-8d3581893111} {4cceaaea-23b5-4465-aeec-3b00075be422} Source Files Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Header Files\ardrone Resource Files ================================================ FILE: build/vs2013/test.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Express 2013 for Windows Desktop VisualStudioVersion = 12.0.30110.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test.vcxproj", "{81224E4A-C4B9-418E-B87E-224D1ACD2FF1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.ActiveCfg = Release|Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: build/vs2013/test.vcxproj ================================================  Debug Win32 Release Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1} Win32Proj Application false MultiByte true v120 Application false MultiByte v120 <_ProjectFileVersion>10.0.30319.1 ..\..\bin\vs2013\ .\obj\debug\ true ..\..\bin\vs2013\ .\obj\release\ false Disabled ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;_DEBUG;_CONSOLE;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL Level3 EditAndContinue wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2013;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) true .\obj\debug\debug.pdb Console MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;NDEBUG;_CONSOLE;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) MultiThreadedDLL Level3 ProgramDatabase 4244;4819;4996;%(DisableSpecificWarnings) wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2013;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) false true .\obj\release\release.pdb Console 0 0 true true MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) ================================================ FILE: build/vs2013/test.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {550b0fc4-8368-48d8-b626-03df6c7d9121} {06e2d9e1-74fe-4d29-9e94-f3ea80429740} {19ba6cc5-e937-4c72-8c33-8d3581893111} {4cceaaea-23b5-4465-aeec-3b00075be422} Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files Header Files\ardrone Resource Files ================================================ FILE: build/vs2015/test.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.24720.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test.vcxproj", "{81224E4A-C4B9-418E-B87E-224D1ACD2FF1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.ActiveCfg = Release|Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: build/vs2015/test.vcxproj ================================================  Debug Win32 Release Win32 {81224E4A-C4B9-418E-B87E-224D1ACD2FF1} Win32Proj 8.1 Application false MultiByte true v140 Application false MultiByte v140 <_ProjectFileVersion>10.0.30319.1 ..\..\bin\vs2015\ .\obj\debug\ true ..\..\bin\vs2015\ .\obj\release\ false Disabled ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;_DEBUG;_CONSOLE;_TIMESPEC_DEFINED;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL Level3 EditAndContinue wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2015;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) true .\obj\debug\debug.pdb Console MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) ..\..\src\3rdparty\opencv\include;..\..\src\3rdparty\ffmpeg\include;..\..\src\3rdparty\pthread\include;..\..\src\3rdparty\glut\include;%(AdditionalIncludeDirectories) WIN32;NOMINMAX;NDEBUG;_CONSOLE;_TIMESPEC_DEFINED;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions) MultiThreadedDLL Level3 ProgramDatabase 4244;4819;4996;%(DisableSpecificWarnings) wsock32.lib;opencv_aruco310.lib;opencv_bgsegm310.lib;opencv_bioinspired310.lib;opencv_calib3d310.lib;opencv_ccalib310.lib;opencv_core310.lib;opencv_datasets310.lib;opencv_dnn310.lib;opencv_dpm310.lib;opencv_face310.lib;opencv_features2d310.lib;opencv_flann310.lib;opencv_fuzzy310.lib;opencv_highgui310.lib;opencv_imgcodecs310.lib;opencv_imgproc310.lib;opencv_line_descriptor310.lib;opencv_ml310.lib;opencv_objdetect310.lib;opencv_optflow310.lib;opencv_photo310.lib;opencv_plot310.lib;opencv_reg310.lib;opencv_rgbd310.lib;opencv_saliency310.lib;opencv_shape310.lib;opencv_stereo310.lib;opencv_stitching310.lib;opencv_structured_light310.lib;opencv_superres310.lib;opencv_surface_matching310.lib;opencv_text310.lib;opencv_tracking310.lib;opencv_video310.lib;opencv_videoio310.lib;opencv_videostab310.lib;opencv_xfeatures2d310.lib;opencv_ximgproc310.lib;opencv_xobjdetect310.lib;opencv_xphoto310.lib;avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;pthreadVC2.lib;glut32.lib;%(AdditionalDependencies) ..\..\src\3rdparty\opencv\lib\vs2015;..\..\src\3rdparty\ffmpeg\lib;..\..\src\3rdparty\pthread\lib;..\..\src\3rdparty\glut\lib;%(AdditionalLibraryDirectories) false true .\obj\release\release.pdb Console 0 0 true true MachineX86 ..\..\src\resource\test.exe.manifest;%(AdditionalManifestFiles) ================================================ FILE: build/vs2015/test.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {550b0fc4-8368-48d8-b626-03df6c7d9121} {06e2d9e1-74fe-4d29-9e94-f3ea80429740} {19ba6cc5-e937-4c72-8c33-8d3581893111} {4cceaaea-23b5-4465-aeec-3b00075be422} Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files\ardrone Source Files Header Files\ardrone Resource Files ================================================ FILE: cvdrone-license-BSD.txt ================================================ CV Drone (= OpenCV + AR.Drone) Copyright (C) 2013-2015 puku0x Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the "CV Drone" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: cvdrone-license-LGPL.txt ================================================ GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ================================================ FILE: licenses/FFmpeg-LGPLv2.1.txt ================================================ GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ================================================ FILE: licenses/ffmpeg.txt ================================================ This is a FFmpeg Win32 Shared build by puku0x. ffmpeg version 2.2.1 Copyright (c) 2000-2014 the FFmpeg developers built on Apr 17 2014 00:33:55 with gcc 4.7.2 (GCC) configuration: --enable-shared --disable-gpl libavutil 52. 66.100 / 52. 66.100 libavcodec 55. 52.102 / 55. 52.102 libavformat 55. 33.100 / 55. 33.100 libavdevice 55. 10.100 / 55. 10.100 libavfilter 4. 2.100 / 4. 2.100 libswscale 2. 5.102 / 2. 5.102 libswresample 0. 18.100 / 0. 18.100 ffmpeg is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. ffmpeg is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ffmpeg; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ================================================ FILE: licenses/glut.txt ================================================ GLUT for Win32 README --------------------- VERSION/INFO: This is GLUT for Win32 version 3.7.6 as of Nov 8th 2001. See the COPYRIGHT section for distribution and copyright notices. Send all bug reports and questions for this version of GLUT to Nate Robins [nate@pobox.com]. For more information about GLUT for Win32, see the web page: www.pobox.com/~nate/glut.html or subscribe to the GLUT for Win32 mailing list by sending e-mail to majordomo@perp.com with "subscribe glut" in the body of the message. For general information about GLUT, see the GLUT web page: http://reality.sgi.com/opengl/glut3/glut3.html and be sure to check the GLUT FAQ first for any questions that you may have: http://reality.sgi.com/opengl/glut3/glut-faq.html COMPILING/INSTALLATION: o Precompiled versions of the DLL and import library can be found on the GLUT for Win32 web page mentioned above. o Microsoft Developer Studio 6 workspace and project files have been included in the source code distribution. To build the glut dll: First, open Microsoft Developer Studio. Then, select File -> Open Workspace and find the glut.dsw file in the file dialog and double-click on it. Finally, select Build -> Build glut32.dll. When the build is finished, it will copy: glut32.dll to %WinDir%\System, glut32.lib to $(MSDevDir)\..\..\VC98\lib, and glut.h to $(MSDevDir)\..\..\VC98\include\GL. Additional workspace files have been included in the progs, test and lib directories to build the progs, tests and libs respectively. BORLAND NOTES: From what I understand, Borland supplies a utility that converts Microsoft Visual C++ .libs into Borland compatible files. Therefore, the best method for Borland users is probably to get the precompiled versions of the library and convert the library. To create an import library for Borland from the DLLs, use the following command (from a command prompt): IMPLIB glut32.lib glut32.dll If IMPLIB crashes when called this way, try IMPLIB glut32.lib glut32.def using the glut32.def file in this distribution. FORTRAN NOTES: Bill Mitchell [william.mitchell@nist.gov] has put considerable effort into getting GLUT to work with different compilers for Fortran 90. He indicates that you should copy the f90glut.h file to your $(MSDevDir)\..\..\VC98\include\GL directory. Then, just build GLUT as usual. The Fortran 90 interface, f90gl, can be obtained at http://math.nist.gov/f90gl and contains installation instructions and usage examples. MISC NOTES: o Overlay support is not implemented, nor are there any plans to implement it in the near future. o To customize the windows icon, you can use the resource name GLUT_ICON. For example, create an icon named "glut.ico", and create a file called glut.rc that contains the following: GLUT_ICON ICON glut.ico then compile the glut.rc file with the following: rc /r glut and link the resulting glut.res file into your executable (just like you would an object file). Alternatively, you can simply add the glut.rc file to your project if you are using Microsoft Developer Studio. IMPLEMENTATION DEPENDENT DIFFERENCES: There are a few differences between the Win32 version of GLUT and the X11 version of GLUT. Those are outlined here. Note that MOST of these differences are allowed by the GLUT specification. Bugs and unsupported features are outlined in the UNSUPPORTED/BUGS section. o glutInit: The following command line options have no meaning (and are ignored) in GLUT for Win32: -display, -indirect, -direct, -sync. o glutInitWindowPosition, glutPositionWindow: Win32 has two different coordinate systems for windows. One is in terms of client space and the other is the whole window space (including the decorations). If you glutPositionWindow(0, 0), GLUT for Win32 will place the window CLIENT area at 0, 0. This will cause the window decorations (title bar and left edge) to be OFF-SCREEN, but it gives the user the most flexibility in positioning. HOWEVER, if the user specifies glutInitWindowPosition(0, 0), the window is placed relative to window space at 0, 0. This will cause the window to be opened in the upper left corner with all the decorations showing. This behaviour is acceptable under the current GLUT specification. o glutSetIconTitle, glutSetWindowTitle: There is no separation between Icon title and Window title in Win32. Therefore, setting an icon title in Win32 has no effect. o glutSetCursor: As indicated in the GLUT specification, cursors may be different on different platforms. This is the case in GLUT for Win32. For the most part, the cursors will match the meaning, but not necessarily the shape. Notable exceptions are the GLUT_CURSOR_INFO & GLUT_CURSOR_SPRAY which use the crosshair cursor and the GLUT_CURSOR_CYCLE which uses the 'no' or 'destroy' cursor in Win32. o glutVisibilityFunc: Win32 seems to be unable to determine if a window is fully obscured. Therefore, the visibility of a GLUT window is only reflected by its Iconic, Hidden or Shown state. That is, even if a window is fully obscured, in GLUT for Win32, it is still "visible". o glutEntryFunc: Window Focus is handled differently in Win32 and X. Specifically, the "window manager" in Win32 uses a "click to focus" policy. That is, in order for a window to receive focus, a mouse button must be clicked in it. Likewise, in order for a window to loose focus, a mouse button must be clicked outside the window (or in another window). Therefore, the Enter and Leave notification provided by GLUT may behave differently in the Win32 and in X11 versions. There is a viable workaround for this. A program called "Tweak UI" is provided by Microsoft which can be used to change the focus policy in Win32 to "focus follows mouse". It is available from the Microsoft Web Pages: http://www.microsoft.com/windows/software/PowerToy.htm o glutCopyColormap: GLUT for Win32 always copies the colormap. There is never any sharing of colormaps. This is probably okay, since Win32 merges the logical palette and the physical palette anyway, so even if there are two windows with totally different colors in their colormaps, Win32 will find a (hopefully) good match between them. o glutIdleFunc + menus: The glut idle function will NOT be called when a menu is active. This causes all animation to stop when a menu is active (in general, this is probably okay). Timer functions will still fire, however. If the timer callback draws into the rendering context, the drawing will not show up until after the menu has finished, though. UNSUPPORTED/BUGS: o glutAttachMenu: Win32 only likes to work with left and right mouse buttons. Especially so with popup menus. Therefore, when attaching the menu to the middle mouse button, the LEFT mouse button must be used to select from the menu. o glutSpaceball*, glutButtonBox*, glutTablet*, glutDials*: None of the special input devices are supported at this time. o When resizing or moving a GLUT for Win32 window, no updating is performed. This causes the window to leave "tracks" on the screen when getting bigger or when previously obscured parts are being revealed. I put in a bit of a kludgy workaround for those that absolutely can't have the weird lines. The reshape callback is called multiple times for reshapes. Therefore, in the reshape callback, some drawing can be done. It should probably be limited to a color buffer clear. o The video resizing capabilities of GLUT 3.3+ for X11 is currently unimplemented (this is probably ok, since it really isn't part of the spec until 4.0). I doubt that this will ever be part of GLUT for Win32, since there is no hardware to support it. A hack could simply change the resolution of the desktop. CHANGES/FIXES: (Nov 8, '01) x Released 3.7.6 (Nov 8, '01) x Changed fullscreen mode from TOPMOST back to simply TOP, since (it turns out) many people use windows atop a GLUT window. (Nov 8, '01) x Added code to prevent CPU spiking when no idle function is registered. Otherwise, if an idle function is registered, spike CPU so that the idle function gets all the attention it needs and if this is a problem on the program side, the user can stick a sleep() in their idle function. I believe that this strikes the best balance betweeen GLUT being fast, and also being "nice" to other processes. Thanks to James Wright for reporting this bug. (Nov 8, '01) x Fixed bug in motion callback handler which wasn't setting the current window, so multiple window apps (e.g., any GLUI app) wouldn't get the callback correctly. (Oct 4, '01) x Fixed bug in glutEnterGameMode() that caused new windows to not be in "fullscreen" mode, so they got window decorations. (Oct 4, '01) x Fixed bug in glutEnterGameMode() that caused new windows to not be in "fullscreen" mode, so they got window decorations. (Oct 3, '01) x Fixed bug in getVisualInfoFromString(): visuals not reloaded on display mode change. Reload visuals each time they are queried. This fixes a problem with Win32 because the list of availabe Visuals (Pixelformats) changes after a change in displaymode. The problem occurs when switching to gamemode and back. Thanks to Michael Wimmer for pointing this out & providing the fix. (Oct 3, '01) x Fixed bug in XGetVisualInfo(): pixelformats enumerated incorrectly. Passing 0 as a pixelformat index to DescribePixelFormat gives unpredictible results (e.g., this fails on the Voodoo opengl32.dll and always reports 0 as the last available pixelformat index). Thanks to Michael Wimmer for pointing this out & providing the fix. (Oct 3, '01) x Fixed bug in glXGetConfig(): pixelformats enumerated incorrectly. The test was OpenGL support OR draw to window, but should be AND. Thanks to Michael Wimmer for pointing this out & providing the fix. (Sep 28, '01) x Fixed glutChangeToSubMenu()/glutChangeToMenuEntry() bug where if you went back and forth between a submenu and a plain entry, the submenu wouldn't be updated properly. (Sep 28, '01) x glutSetIconTitle() is now a nop. (Sep 28, '01) x glutFullScreen() now sets the window as TOPMOST, therefore, the window will always be on top (this essentially disables alt-tabbing). (Sep 28, '01) x The key repeat ignore flag is now honored correctly. (Sep 28, '01) x Key presses are now reported more accurately and fully, in particular, modified up events (i.e., SHIFT-2) are now reported correctly. (Sep 28, '01) x Subwindows nested arbitrarily deep get their keyboard callbacks correctly now. (Sep 28, '01) x Major rewrite of the window procedure code to clean it up and make way for other bug fixes. (Sep 23, '01) x Fixed noof example program to use RAND_MAX instead of assumed max of 2147483647.0. (Now it looks _much_ better!) (Sep 22, '01) x Fixed sunlight example program. globe.raw data file was corrupt, added a new one. (Sep 22, '01) x Fixed zcomposite example program to print message if overlay support is not found (instead of crashing). (Jan 22, '01) x Fixed malloc(0) bug in Win32 version of XGetVisualInfo. Thanks to Kekoa Proudfoot for bringing this to my attention. (Dec 12, '00) x Added data files for the advanced & advanced97 programs. (Dec 12, '00) x Added Developer Studio 6 project and workspace files for pretty much everything (the stuff left out was usually unix specific). (Dec 7, '00) x Fixed several compilation problems & corrupt files. Thanks to Alexander Stohr for bringing these to my attention and providing detailed fixes. (Dec 6, '00) x Fixed compiler support for lcc. Thanks to Gordon for bringing this to my attention and debugging fixes. (Nov 8, '00) x Fixed submenu problem (sometimes the menu callback was not called for valid items). Thanks to Michael Keeley. (Oct 16, '00) x Corrected corrupt duck.iv file. Thanks to Jon Willeke for finding this problem. (Sept 27, '00) x Fixed bug in processWorkList that could cause a hang. Thanks to Bill Volz & Daniel Azuma. (Sept 26, '00) x Added mui DLL project file (thanks to DMWeldy@ugsolutions.com). (Sept 9, '00) x Fixed Delete key bug (crash when no keyboard callback was registered, but a special key callback was). Thanks to Kent Bowling (kent_bowling@hotmail.com) for finding this bug. (May 18, '00) x Fixed subwindow keyboard callbacks. (May 22, '97) o Menus don't work under Windows 95 x Fixed! Added a unique identifier to each menu item, and a search function to grab a menu item given the unique identifier. (May 21, '97) o A few minor bug fixes here and there. x Thanks to Bruce Silberman and Chris Vale for their help with this. We now have a DLL! (Apr 25, '97) o DLL version of the library is coming (as soon as I figure out how to do it -- if you know, let me know). x Thanks to Bruce Silberman and Chris Vale for their help with this. We now have a DLL! (Apr 24, '97) x Added returns to KEY_DOWN etc messages so that the F10 key doesn't toggle the system menu anymore. (Apr 7, '97) o Palette is incorrect for modes other than TrueColor. x Fixed this by forcing a default palette in modes that aren't Truecolor in order to 'simulate' it. The applications program shouldn't have to do this IMHO, but I guess we can't argue with Microsoft (well, we can, but what good will it do?). (Apr 2, '97) x Added glut.ide file for Borland users. (Apr 2, '97) x Fixed a bug in the WM_QUERYNEWPALETTE message. Wasn't checking for a null colormap, then de-ref'd it. Oops. (Mar 13, '97) o glutTimerFunc: Currently, GLUT for Win32 programs busy waits when there is an outstanding timer event (i.e., there is no select() call). I haven't found this to be a problem, but I plan to fix it just because I can't bear the thought of a busy wait. x Added a timer event and a wait in the main loop. This fixes the CPU spike. (Mar 11, '97) x Fixed subwindow visibility. The visibility callback of subwindows wasn't being called, now it is. (Mar 11, '97) o glutGetHDC, glutGetHWND: In order to support additional dialog boxes, wgl fonts, and a host of other Win32 dependent structures, two functions have been added that operate on the current window in GLUT. The first (glutGetHDC) returns a handle to the current windows device context. The second (glutGetHWND) returns handle to the current window. x Took these out to preserve GLUT portability. (Mar 11, '97) x Fixed the glutWarpPointer() coordinates. Were relative to the screen, now relative to window (client area) origin (which is what they're supposed to be). (Mar 11, '97) o glutCreateMenu, glutIdleFunc: Menu's are modal in Win32. That is, they don't allow any messages to be processed while they are up. Therefore, if an idle function exists, it will not be called while processing a menu. x Fixed! I've put in a timer function that fires every millisecond while a menu is up. The timer function handles idle and timer events only (which should be the only functions that are firing when a menu is up anyway). (Mar 7 '97) x Fixed minor bugs tracked down by the example programs. (Mar 6, '97) x Merged 3.3 GLUT for X11 into 3.2 GLUT for Win32. New code structure allows for EASY merging! o In Win32, the parent gets the right to set the cursor of any of its children. Therefore, a child windows cursor will 'blink' between its cursor and its parent. x Fixed this by checking whether the cursor is in a child window or not. (Feb 28 '97) o On initial bringup apps are getting 2 display callbacks. x Fixed by the Fev 28 re-write. o Some multiple window (not subwindow) functionality is messed up. See the sphere.exe program. x Fixed by the Feb 28 re-write. o GLUT for Win32 supports color index mode ONLY in a paletted display mode (i.e., 256 or 16 color mode). x Fixed this in the re-write. If you can get a color index visual (pixel format) you can use color index mode. (Feb 28 '97) o Quite a few bugs (and incompatibilities) were being caused by the structure that I used in the previous port of GLUT. Therefore I decided that it would be best to "get back to the roots". I re-implemented most of glut trying to stick with the structure layed out by Mark. The result is a much more stable version that passes ALL (!) (except overlay) the tests provided by Mark. In addition, this new structure will allow future enhancements by Mark to be integrated much more quickly into the Win32 version. Also, I'm now ordering the bugs in reverse, so that the most recently fixed appear at the top of the list. (9/8/96) o Changed the glutGetModifiers code to produce an error if not called in the core input callbacks. (9/11/96) o If the alt key is pressed with more than one other modifier key it acts as if it is stuck -- it stays selected until pressed and released again. x Fixed. (9/12/96) o When a submenu is attached to a menu, sometimes a GPF occurs. Fixed. Needed to set the submenu before referencing it's members. o Kenny: Also, one little problem, I attached the menu to the right-button, but when the left-button is pressed I detach it to give the right-button new meaning; if I pop-up the menu and I don't want to select anything, like most users, I click off of the menu to make it disappear. When I do this, I get a GLUT error and the program terminates because I am altering the menu attachment from within the button press while the menu is active. x Fixed. Needed to finish the menu when the user presses the button, not just when a button is released. o GLUT for Win32 emulates a middle mouse button by checking if both mouse buttons are down. This causes a lot of problems with the menu and other multiple mouse button things. x Fixed. No more middle mouse button emulation. Perhaps it would be a good idea to emulate the middle mouse button (if not present) with a key? (9/15/96) o Added code to accept a user defined icon. If no icon is provided, a default icon is loaded. (9/19/96) o Shane: Command line options seem to be screwed up. (9/13) x Fixed. The geometry command line was broken, and so was the gldebug command line. o Fixed a bug in the default glut reshape. It was looking for the parent of the current window and GPF'ing if there wasn't a parent. Put in a check for a parent, and if none is there, use the child. o Idle function sucks up all processor cycles. (9/8/96) x I don't know if this is avoidable. If you have a tight rendering loop, it may be that the processor time is going to be sucked up no matter what. You can add a sleep() to the end of your render loop if you would like to yeild to other processes and you don't care too much about the speed of your rendering loop. If you have Hardware that supports OpenGL (like a 3Dpro card, or GLint card) then this should be less of a problem, since it won't be rendering in software. (9/11/96) o If a window is fully obscured by another window, the visibility callback is NOT called. As far as I can tell, this is a limitation of the Win32 api, but a workaround is being searched for. (9/8/96) x Limitation of the Win32 API o Fixed the entry functions. They only work if the keyboard focus changes. Therefore, in most Win32 systems, the mouse must be pressed outside of the window to get a GLUT_LEFT message and then pressed inside the window for a GLUT_ENTERED message. o Alt modifier key doesn't work with keyboard callback. (9/8/96) x Probably okay, because the glut spec says that these keys can be intercepted by the system (which the alt key is...) (9/11/96) (11/17/96) o glutRemoveMenuItem() not working properly. x Thanks to Gary (grc@maple.civeng.rutgers.edu) for the fix to this one. o Timer functions are messed up. x Thanks to Joseph Galbraith for the fix to this one. (12/9/96) o One (minor) difference came up between the X version of glut and the nt one which you should know about. It is not a new problem, and it concerns co-ords returned to the pointer callbacks. (glutMotionFunc, glutMouseFunc) Under X, you get co-ords in the range 0 +/- 2^15, under NT you get 0..2^16. This is only really a problem when moving above or to the left of the window. eg dragging one pixel ABOVE the window will give :- under x11 : y = -1 under nt : y = 2^16 -1 x Put in fix provided by Shane Clauson. (12/17/96) o Idle functions not working properly for multiple windows. x Fixed this by posting an idle message to every window in the window list when idle. (12/18/96) o glutSetCursor() was misbehaving (lthomas@cco.caltech.edu). x Win32 requires that the hCursor member of the window class be set to NULL when the class is registered or whenever the mouse is moved, the original cursor is replaced (go figure!). Now sets the cursor whenever a WM_MOUSEMOVE message is received, because the WM_SETCURSOR event resets the cursor even when in the decoration area. o Geometry is not being handled quite right. The numbers don't take into account the window decorations. That is, if I say make a window 100x100, then the WHOLE window (not just the client area) is 100x100. Therefore, the client (opengl) area is smaller than 100x100. (9/8/96) x Fixed. Added code to subtract the decoration size on glutGet() and add the decoration size on glutReshapeWindow(). o Multiple glutPostRedisplay() calls are NOT being combined. To get round the "coalesce" problem on glutPostRedisplay, the easiest solution is to roll-your-own coalesce by keeping a global "dirty" flag in the app (eg replace all calls to glutPostRedisplay with image_dirty=TRUE;), and to handle image_dirty with a single glutPostRedisplay in the idle callback when required. (erk - but increases performance for my particular app (a rendering engine on the end of a pipleine with a stream of graphics updates) by a couple of orders of magnitude ! ) (9/8/96) x Added code to coalesce redisplays. Every idle cycle, a check is made to see which windows need redisplay, if they need it, a redisplay is posted. The glutPostRedisplay() call is just a stub that sets a flag. THANKS: Special thanks to the following people for extensive testing, suggestions, fixes and help: Alexander Stohr Shane Clauson Kenny Hoff Richard Readings Paul McQuesten Philip Winston JaeWoo Ahn Joseph Galbraith Paula Higgins Sam Fortin Chris Vale Bill Mitchell and of course, the original author of GLUT: Mark Kilgard. and many others... COPYRIGHT: The OpenGL Utility Toolkit distribution for Win32 (Windows NT & Windows 95) contains source code modified from the original source code for GLUT version 3.3 which was developed by Mark J. Kilgard. The original source code for GLUT is Copyright 1997 by Mark J. Kilgard. GLUT for Win32 is Copyright 1997 by Nate Robins and is not in the public domain, but it is freely distributable without licensing fees. It is provided without guarantee or warrantee expressed or implied. It was ported with the permission of Mark J. Kilgard by Nate Robins. THIS SOURCE CODE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. OpenGL (R) is a registered trademark of Silicon Graphics, Inc. ================================================ FILE: licenses/opencv.txt ================================================ By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2000-2015, Intel Corporation, all rights reserved. Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. Copyright (C) 2009-2015, NVIDIA Corporation, all rights reserved. Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. Copyright (C) 2015, OpenCV Foundation, all rights reserved. Copyright (C) 2015, Itseez Inc., all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. ================================================ FILE: licenses/parrot.txt ================================================ IMPORTANT: INSTRUCTION TO USE AND TO APPLY THE TERMS OF THE LICENSE TO ANY NEW PROGRAM READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING Copyright (C) 2007-2011, PARROT SA, all rights reserved. You may use, copy, modify the PARROT AR.Drone SDK and APIs or any portion of it, and thus form a work based on Parrot SDK and APIs, and copy and redistribute in source code and binary forms, with or without modification, provided that you comply with following conditions: Redistribution in source code, with or without modification, must retain Parrot copyright notice, the following disclaimer and the license to develop and use in a text file named Parrot License. Redistribution in binary form must reproduce Parrot copyright notice, the following disclaimer in the product documentation or legal notice. The name of Parrot may not be used to endorse or promote products derived from the APIs without specific prior written permission. DISCLAIMER The APIs is provided by PARROT and contributors "AS IS" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall PARROT and contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. DEVELOPMENT LICENSE OF THE PARROT AR.DRONE SDK and APIs V2.0 (Creation of games for the Parrot AR.DRONE) Article 1: Purpose The purpose of the present Development License is to define the terms and conditions under which the Developer is authorized to use the source codes of the PARROT SDK and APIs to create under its own responsibility a Game for the AR.Drone and to market it for free or against payment. Article 2: Definitions The terms defined hereunder, used in singular or plural, shall have the following meaning: - PARROT SDK and APIs : means the AR.Drone software development kit and AR.Drone APIs and associated documentation, allowing to pilot the PARROT AR.Drone, from a mobile phone, a console game, a computer or any other electronic device, and which source codes are provided for free to the Developer; - Developer means a physical person, of age, having the capacity to accept the terms of the present License or a person, representing a company and having all powers to that effect to bind the company; - PARROT AR.Drone or PARROT AR.Drone or PARROT Drone means the augmented reality drone developed by PARROT, without pilot, remote-controlled by a mobile phone, a console game, a computer or any other electronic device; - Interoperability : means the ability of an application to exchange information with the Parrot AR.Drone or any its accessories; - Game for AR.Drone : means a software or a video game, created by the Developer from the PARROT SDK and APIs or any modified version, and which functionalities shall exclusively be dedicated to the use of the PARROT AR.Drone for entertaining, game, leisure or training purpose or any other purpose compatible with the terms of the present license; - License means the present license of development and use of the APIs; - User Account means the information relating to the identification of a Developer, such as first name, surname, email address, login, password, company, title; - User : means any physical person using the PARROT Drone or a Game for AR.Drone. ARTICLE 3 Identification 3.1 The downloading of the APIs is subject to the Identification of the Developer by filling in the online registration form and accept the terms of the License by clicking the acceptance box on https://projects.ardrone.org . 3.2 The Developer commits to provide accurate information and to update the information, if necessary. 3.3 The User Account is personal and confidential; it cannot be assigned to a third party. 3.4 The Developer commits to inform PARROT immediately of any disclosure, non authorized use by a third party of the login and/or password of its User Account. In such case, PARROT shall be entitled to invalid the login and the password. ARTICLE 4 Conditions of Use Notwithstanding the limitation and restrictions mentioned in article 5, PARROT grants to the Developer, who accepts, a personal, non-assignable, non-exclusive, worldwide, free license of development of the PARROT SDK and APIs authorizing the Developer to: reproduce, without number limitation, the APIs on any device under its responsibility, and necessary to create the Game for AR.Drone; translate, adapt, arrange, modify the APIs in order to create a Game for AR.Drone in the software and hardware environment chosen by the Developer; to market, for free or against fees, copies of the Game for AR.Drone created ; to grant licenses of the Game for AR.Drone to the Users of the PARROT Drone. ARTICLE 5 Restrictions to the license 5.1 The License of development and use of the APIs is subject to the acceptance and to the respect by the Developer without any reserves of all restrictions and limitations listed hereafter: Consequently, PARROT expressly forbids the Developer: (i) To access or use of the PARROT SDK and APIs from a technology or means others than those provided with the APIs; (ii) To market copies of the APIs, for free or against fees, and to distribute, sub-license, rent, sell, transfer, commercialize, publish or generally put the APIs to a third party disposal; (iii) To do reverse engineering, decompile or attempt to extract the Source Codes of the PARROT Drone; under special legal conditions, necessary information for interoperability purpose might be requested from PARROT ; (iv) To destroy, or alter any warning and copyrights notices; (v) To use the PARROT SDK and APIs to develop an application other than a Game for AR.Drone. The Game for AR.Drone, shall have for sole purpose to be used by a User for entertaining, game, leisure or training. The creation of applications for the use of the PARROT Drone for professional use or use such as but not limited to military, and, without limitation, security, watching, spying, defence, cartography, is strictly forbidden. (vi) To use the PARROT SDK and APIs or to create a Game for AR.Drone breaching the terms of: (1) The License; (2) Third party rights; (3) Applicable laws and regulations; (4) Any instruction provided by PARROT. 5.2 Therefore, and without limitation, the Developer commits when using the APIs or when creating a Game for AR.Drone: a) not to infringe any applicable laws and regulation which the Developer shall determine whatever the country where he intends to develop and/or market the Game for AR.Drone ; b) not to reproduce, represent, put contents which infringe copyrights, patents, trademarks, design, model, know-how, commercial secret and any intellectual property rights belonging to PARROT or to third parties ; c) not to falsify or remove copyrights, trademarks notices of any other proprietary rights of PARROT figuring in the Application; d) not to display a Game for AR.Drone which falsely or implied would suggest an endorsement or any approbation from PARROT ; e) not to collect or treat, or store, with the Game for AR.Drone, personal data from third, especially User of the Game for AR.Drone without having previously asked for their consent. Shall the Game for AR.Drone store personal data, it should be in compliance with the applicable law 5.3 PARROT is sole judge of the compliance of the Game for AR.Drone with the terms and conditions of the present License. 5.4 PARROT reserves the right to correct or modify the PARROT SDK and APIs during the License duration. ARTICLE 6 Duration of the License The License of the PARROT SDK and APIs is granted for the duration of the intellectual property rights of the Game for AR.Drone. It enters into force upon acceptance by the Developers by clicking the acceptance box or using a modified release of the PARROT SDK and APIs. ARTICLE 7 Termination of the License 7.1 PARROT reserves the right to terminate the present License, without notice, in following cases: i. The Developer has created a Game for AR.Drone in violation of the present License terms, any applicable law and regulation or PARROT has objective reasons to believe that the Game for AR.Drone is infringing the License or any applicable law and regulation ; ii. The Developer has created a Game for AR.Drone in violation of PARROTs intellectual property rights or PARROT has objective reasons to believe that the Game for AR.Drone is infringing its rights ; iii. The Developer has created a Game for AR.Drone in violation of a third partys intellectual property rights or PARROT has objective reasons to believe that the Game for AR.Drone is infringing a third partys rights ; iv. The Developer has created a Game for AR.Drone containing bugs, viruses, worms, defects, Trojan horses, or any items of a destructive nature or PARROT has objective reasons to believe that the Game for AR.Drone contains of this item; 7.2 Termination of the License shall be notified by email to any user breaching the terms of the License. 7.3 In case of closing of a User Account or termination of the License, for whatever reason, articles which by their nature shall survive shall continue to be applicable, in particular articles 11.RIGHTS OF PARROT; 12.DISCLAIMER; 13.LIMITATION OF RESPONSIBILITY; 14.INDEMNITY; 17.GENERALS PROVISIONS. ARTICLE 8 Specific Development Upon request of a video game editor, PARROT may perform specific development of the PARROT SDK and APIs, in order to enable the creation of a Game for AR.Drone for commercial purpose by such editor. The development services provide by PARROT shall be subject to a separate agreement between PARROT and the editor. PARROT and the editor shall share the revenues gained from the sale of games created thanks to the specific development for an amount to be determined by agreement between the parties. ARTICLE 9 Upgrade of the APIs 9.1 Due to technological innovations and for quality and/ or security reasons, the Developer acknowledges and agrees that PARROT may at any time modify the APIs, namely by adjunction, removal, improvement of functionalities, or that PARROT may temporarily or definitely suspend the access to the APIs, at its sole discretion and without notice. PARROT warrants as far as possible and with no result obligation, the ascendant compatibility of the APIs. 9.2 PARROT shall notify any modification by publication on https://projects.ardrone.org, or per email, or by any other appropriate mean in PARROT judgment. From the notification, the use of the APIs by the Developer to create new Game for AR.Drone shall be deemed as the acceptance by the Developer of the modified License of the PARROT SDK and APIs. ARTICLE 10 License granted to Parrot by the Developper 10.1 The Developer is owner of all copyrights and other intellectual property rights on the Game for AR.Drone that he creates. If the Developer is posting his Game for AR.Drone on https://projects.ardrone.org , he grants PARROT a perpetual, irrevocable, worldwide, free and non-exclusive license to reproduce, represent, adapt, arrange , modify, translate, publish, operate and display the Game for AR.Drone by any means of communication, numerical, analogical, electronic..to the public and namely by any network(internet, intranet), wireless or not, by mobile phone, email, by satellite, par optical fibre, par television and on any media. 10.2 This license shall be granted in order to allow PARROT to display, promote, and distribute the PARROT SDK and APIs and/or the PARROT AR.Drone. 10.3 This license includes the right for PARROT to make the Game for AR.Drone available totally or partially to any Users of the AR.DRONE PARROT or to any person with who PARROT is in relationship, and to use the Game for AR.Drone for information or advertisement purpose. 10.4 The Developer agrees that PARROT for technical or for improvement purpose, may (a) transmit or communicate the Game for AR.Drone on public network others than internet (wireless or not, namely mobile telephony) and various media (graphic, magnetic, optical, numerical, analogical); and (b) make any modification necessary to adapt and make the Game for AR.Drone compliant to technical specifications so to make it interoperable with networks or devices. 10.5 The Developer warrants PARROT that he has the rights to grant the license. ARTICLE 11: Parrot Rights 11.1 Intellectual and industrial property rights. PARROT is and remains the owner of all rights and interests on the PARROT SDK and APIs and on the PARROT AR.Drone, including without limitation all rights of intellectual and industrial property (copyrights, database rights, patents, trademark, design and model, semi-conductor topography) and/or any rights on the know-how, schemes, plans, algorythme, technologies, ideas, concepts. It is expressly specified that PARROT is owner of patents on the PARROT AR.Drone and that a right to use such patent is granted within the frame of the present License. No other rights on the patents are granted to the Developer who commits no to use the technologies issued from those patents for purpose not in the scope of the present License. 11.2 Trademarks and logos. 11.2.1 PARROT is owner of the intellectual property rights on its commercial trade name, trademarks, logos, domain names and any others brand features. PARROT grants the Developer a non-exclusive, non assignable, non transferable, non sub-licensable, free license to use PARROT trademarks and logos for the sole purpose of mentioning that he uses the PARROT SDK and APIs. 11.2.2 When using PARROTs trademarks and logos, the Developer undertakes: i. Not to display a trademark or a logo in any manner that implies a relationship or affiliation with, sponsorship, or endorsement by PARROT or that can be reasonably interpreted to suggest editorial content has been authored by, or represents the views or opinions of PARROT; ii. Not to use PARROT brand features to disparage PARROT or its products; iii. Not to display a trademark or a logo on its website if it contains or displays adult content or promotes illegal activities, gambling, or the sale of tobacco or alcohol to persons under eighteen (18) years of age; iv. Not to display the PARROT trademark and logo as the most prominent element in any part of the Game for AR.Drone created by the Developer or its packaging; v. Not to display the PARROT logo as the most prominent logo in the Game for AR.Drone ; vi. Not to display PARROT trademark or logo in a manner that is misleading, defamatory, infringing, libelous, disparaging, obscene or otherwise objectionable to PARROT; vii. Not to display a PARROT trademark or logo on a site that violates any law or regulation ; viii. Not to remove, distort or alter any element of a PARROT brand feature (including squeezing, stretching, inverting, discoloring, etc.). 11.3 The Developer undertakes during the term of the License and after its expiration, not to register or attempt to register any trademark, logo, domain name similar to or confusing with PARROT trademark or logo, in any manner (phonetic, intellectual, visual). PARROT reserves the right to sue for counterfeiting and unfair competition, any Developer who would not respect this commitment and use the trademarks and/or domain name PARROT AR.DRONE OU AR.DRONE in breach of the License. 11.4 The Developer undertakes to immediately remedy to any breach notified by PARROT per email or any other mean concerning any infringement to PARROT intellectual property rights. 11.5 The Developer, company or physical person, is owner, as applicable, on the intellectual property rights on his name, commercial name, trademarks, logos and any other brand features. He expressly grants PARROT a non exclusive, worldwide and free license to mention his name, commercial name, trademarks, logos, as applicable, to mention that he uses the PARROT SDK and APIs and/or that he has created a Game for AR.Drone. ARTICLE 12: DISCLAIMER 12.1 THE PARROT SDK AND APIs IS PROVIDED AS IS . IN PARTICULAR, PARROT, ITS SUBSIDIARIES, LICENSORS AND THEIR SUPPLIERS, DO NOT REPRESENT OR WARRANT THE DEVELOPER THAT: 1. ITS USE OF THE APIs WILL MEET ITS REQUIREMENTS; 2. ITS USE OF THE APIs WILL BE UNINTERRUPTED, TIMELY, SECURE OR FREE FROM ERROR OR WILL OFFER CONSTANT PERFORMANCE; 3. THAT DEFECTS OR ERRORS WILL BE CORRECTED OR THAT THE APIs WILL BE UPGRADE, PARROT HAVING NO OBLIGATION TO PROVIDE CURATIVE OR EVOLUTIVE SUPPORT; 4. THE APIs IS COMPLIANT TO ANY SPECIFICATIONS; 5. ANY UPGRADE OF THE PARROT SDK AND APIs WILL BE COMPATIBLE WITH PREVIOUS RELEASE. 12.2 PARROT, ITS SUBSIDIARIES, LICENSORS AND THEIR SUPPLIERS, DO NOT REPRESENT OR WARRANT THE DEVELOPER THAT ITS USER ACCOUNT WILL BE AVAILABLE WITHOUT INTERRUPTION. 12.3 NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY THE DEVELOPER FROM PARROT, ITS SUBSIDIARERIES, OR THROUGH THE APIs, SHALL BE CONSTRUED A WARRANTY PROVIDED BY PARROT. 12.4 PARROT, ITS SUBSIDIARIES, ITS LICENSORS DO NOT WARRANT, ANY RESULT, EXPRESS OR IMPLIED, OF ANY NATURE (TECHNICAL, COMMERCIAL, FINANCIAL OR OTHER) FROM THE USE OF THE APPLICATION. 12.5 PARROT DECLARES THAT TO THE BEST OF ITS KNOWLEDGE THE PARROT SDK AND APIs DOES NOT INFRINGE ANY THIRD PARTY INTELLECTUAL PROPERTY RIGHTS. ARTICLE 13: LIMITATION OF RESPONSABILITY 13.1 THE PROVISION EXCLUSING OR LIMITING PARROTS LIABILITY SHALL ONLY BE APPLICABLE IN COUNTRIES WHERE SUCH PROVISIONS ARE LEGAL. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF CERTAIN WARRANTIES OR THE LIMITATION OR EXCLUSION OF LIABILITY FOR CERTAIN TYPES OF LOSS OR DAMAGES. ACCORDINGLY, PARROTS LIABILITY WILL BE LIMITED TO THE MAXIMUM EXTENT PERMITTED BY LAW. 13.2 THE DEVELOPER EXPRESSLY ACKNOWLEDGES AND AGREES THAT THE USE HE DOES OF ITS USER ACCOUNT, THE APIs, THE GAME FOR AR.DRONE THAT HE CREATES, ARE AT ITS SOLE RISK AND RESPONSABILITY. IN PARTICULAR, THE DEVELOPER SHALL BE SOLELY RESPONSIBLE FOR ANY DAMAGE TO ITS COMPUTER SYSTEM OR OTHER DEVICE, LOSS OF DATA, OR ANY OTHER DAMAGE OR INJURY THAT RESULTS FROM THE DOWNLOAD OR USE OF THE APIs. 13.3 THE DEVELOPER EXPRESSLY ACKNOWLEDGES AND AGREES THAT HE SHALL BE SOLELY RESPONSIBLE FOR ALL COSTS, EXPENSES INCURRING FOR THE USE OF ITEMS MENTIONED ABOVE AS WELL AS ANY DEVELOPMENT AND PRODUCTION COSTS ASSOCIATED TO THE GAME OF AR.DRONE THAT HE IS CREATING. 13.4 PARROT, ITS SUPPLIERS, LICENSORS, AFFILIATES, ARE NOT RESPONSIBLE FOR ANY DIRECTS OR INDIRECTS, MATERIALS OR IMMATERIALS, CONSECUTIVES OR NON CONSECUTIVES DAMAGES, INCLUDING, BUT NOT BE LIMITED TO, ANY LOSS OF PROFIT (WHETHER INCURRED DIRECTLY OR INDIRECTLY), ANY LOSS OF GOODWILL OR BUSINESS REPUTATION, ANY LOSS OF DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR OTHER INTANGIBLE LOSS, THAT DEVELOPER OR A THIRD PARTY MAY INCURR FROM: 1- THE USE BY THE DEVELOPER OF ITS USER ACCOUNT, THE PARROT SDK AND APIs, THE GAME FOR AR.DRONE THAT HE CREATES; 2- THE MARKETING OF THE GAME FOR AR.DRONE FOR FREE OR AGAINST FEES; 3- THE MODIFICATION OF THE APIs BY PARROT; 4- THE CLOSING OF THE USER ACCOUNT, THE MODIFICATION OR THE EXPIRATION OR TERMINATION OF THE LICENSE; 5- ANY NON ACCURATE OR NON UPDATED INFORMATION PROVIDED BY PARROT, ARTICLE 14: INDEMNITY The Developer warrants and hereby agrees to indemnify, defend and hold PARROT harmless from and against any claim or liability arising out of: (a) the use of the APIs in breach of the License and/or any instruction provided by PARROT; (b) the Game for AR.Drone; (c) any use by Users of the Game for AR.Drone; (d) any claim that the Game for AR.Drone breaches laws or infringes third party rights; consequently, assume all costs and damages to which PARROT could be condemned by a jurisdiction on such a basis. The Developer shall cooperate as fully as reasonably required in the defence of any claim and PARROT reserves the right, at its own expense, to assume the exclusive defence and control of any matter subject to indemnification by the Developer. And if necessary, to seek equitable relief, including but not limited to preliminary injunction and injunction, in addition to all other remedies. ARTICLE 15: Hyperlinks 15.1. The https://project.ardrone.org ardrone.org website may include hyperlinks to other web sites or content or resources provided by third parties and companies. PARROT has no control or authority over any web sites, resources, third parties. The Developer acknowledges and agrees that PARROT is not responsible for the availability of any such external sites or resources, and does not endorse any advertising, products or other materials on or available from such web sites or resources. 15.2. The Developer acknowledges and agrees that PARROT is not liable for any loss or damage that may be incurred by the Developer as a result of the availability of those external sites or resources, or as a result of any reliance placed by you on the completeness, accuracy or existence of any advertising, products, or other materials on, or available from, such web sites or resources. ARTICLE 16: Language and interpretation 16.1 The English version of the License shall prevail over any translation, which might only be provided for convenience purpose. Therefore any translation might be provided only for convenience purpose. 16.2 If there is any contradiction between the English language version of the License and a translation of the License, the English language version will take precedence. 16.3 Titles are provided for convenience purpose only; the content of an article shall have precedence on the title. ARTICLE 17: General provisions 17.1 The License constitutes the entire legal agreement between Parrot and the Developer and completely replace and supersede any prior agreements between PARROT and the Developer. 17.2 The waiver by PARROT to prevail itself from a provision of the License shall not be construed as a waiver to prevail itself of any right obligation under the License in the future. 17.3 If any court of law having jurisdiction rules that any provision of this License is invalid, then that provision will be removed from the License without affecting the rest of the License. The remaining provisions of the License will continue to be valid and enforceable. 17.4 Any notice sent by PARROT to the Developer or exchange between the Parties will be validly delivered per email at the address provided by the Developer in its User Account and at legal@ardrone.org for PARROT. ARTICLE 18: Applicable law and jurisdiction The License is governed by French Law, without regard to its conflict of Laws provisions. Any dispute arising out of its interpretation, execution or termination shall be submitted to the exclusive jurisdiction of the relevant court of Paris, even for urgency proceedings or plurality of defendants. Notwithstanding this, PARROT shall be allowed to apply for injunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction ARTICLE 19 - Privacy 19.1 All information about our privacy policy are provided on www.parrot.com . This policy explains how PARROT treats any personal data which are disclosed to her and protect your privacy. 19.2 The Developer agrees that PARROT may use its personal data in compliance with its privacy policy. ARTICLE 20 Acceptance of the license By clicking the acceptance box, downloading or using the PARROT SDK and APIs or an adapted or modified release of the PARROT SDK and APIs, the Developer or any user accepts without reserve all terms and conditions of the License concluded between him and PARROT SA registered under N 394 149 496 and located 174 quai de Jemmapes FRANCE - which he commits to respect. Last update: November 2010 Document revision V2.0 ================================================ FILE: licenses/parrotdisclaimer.txt ================================================ Copyright (C) 2007-2011, PARROT SA, all rights reserved. DISCLAIMER The APIs is provided by PARROT and contributors "AS IS" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall PARROT and contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. ================================================ FILE: licenses/pthreads-w32.txt ================================================ pthreads-win32 - a POSIX threads library for Microsoft Windows This file is Copyrighted ------------------------ This file is covered under the following Copyright: Copyright (C) 2001 Ross P. Johnson All rights reserved. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Pthreads-win32 is covered by the GNU Lesser General Public License ------------------------------------------------------------------ Pthreads-win32 is open software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation version 2.1 of the License. Pthreads-win32 is several binary link libraries, several modules, associated interface definition files and scripts used to control its compilation and installation. Pthreads-win32 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. A copy of the GNU Lesser General Public License is distributed with pthreads-win32 under the filename: COPYING.LIB You should have received a copy of the version 2.1 GNU Lesser General Public License with pthreads-win32; if not, write to: Free Software Foundation, Inc. 59 Temple Place Suite 330 Boston, MA 02111-1307 USA The contact addresses for pthreads-win32 is as follows: Web: http://sources.redhat.com/pthreads-win32 Email: Ross Johnson , or Ross.Johnson@canberra.edu.au Pthreads-win32 copyrights and exception files --------------------------------------------- With the exception of the files listed below, Pthreads-win32 is covered under the following GNU Lesser General Public License Copyrights: Pthreads-win32 - POSIX Threads Library for Win32 Copyright(C) 1998 John E. Bossom Copyright(C) 1999,2002 Pthreads-win32 contributors The current list of contributors is contained in the file CONTRIBUTORS included with the source code distribution. The current list of CONTRIBUTORS can also be seen at the following WWW location: http://sources.redhat.com/pthreads-win32/contributors.html Contact Email: rpj@ise.canberra.edu.au These files are not covered under one of the Copyrights listed above: COPYING COPYING.LIB tests/rwlock7.c This file, COPYING, is distributed under the Copyright found at the top of this file. It is important to note that you may distribute verbatim copies of this file but you may not modify this file. The file COPYING.LIB, which contains a copy of the version 2.1 GNU Lesser General Public License, is itself copyrighted by the Free Software Foundation, Inc. Please note that the Free Software Foundation, Inc. does NOT have a copyright over Pthreads-win32, only the COPYING.LIB that is supplied with pthreads-win32. The file tests/rwlock7.c is derived from code written by Dave Butenhof for his book 'Programming With POSIX(R) Threads'. The original code was obtained by free download from his website http://home.earthlink.net/~anneart/family/Threads/source.html and did not contain a copyright or author notice. It is assumed to be freely distributable. In all cases one may use and distribute these exception files freely. And because one may freely distribute the LGPL covered files, the entire pthreads-win32 source may be freely used and distributed. General Copyleft and License info --------------------------------- For general information on Copylefts, see: http://www.gnu.org/copyleft/ For information on GNU Lesser General Public Licenses, see: http://www.gnu.org/copyleft/lesser.html http://www.gnu.org/copyleft/lesser.txt Why pthreads-win32 did not use the GNU General Public License ------------------------------------------------------------- The goal of the pthreads-win32 project has been to provide a quality and complete implementation of the POSIX threads API for Microsoft Windows within the limits imposed by virtue of it being a stand-alone library and not linked directly to other POSIX compliant libraries. For example, some functions and features, such as those based on POSIX signals, are missing. Pthreads-win32 is a library, available in several different versions depending on supported compilers, and may be used as a dynamically linked module or a statically linked set of binary modules. It is not an application on it's own. It was fully intended that pthreads-win32 be usable with commercial software not covered by either the GPL or the LGPL licenses. Pthreads-win32 has many contributors to it's code base, many of whom have done so because they have used the library in commercial or proprietry software projects. Releasing pthreads-win32 under the LGPL ensures that the library can be used widely, while at the same time ensures that bug fixes and improvements to the pthreads-win32 code itself is returned to benefit all current and future users of the library. Although pthreads-win32 makes it possible for applications that use POSIX threads to be ported to Win32 platforms, the broader goal of the project is to encourage the use of open standards, and in particular, to make it just a little easier for developers writing Win32 applications to consider widening the potential market for their products. ================================================ FILE: readme.txt ================================================ ----------------------------------------------------------------- CV Drone (= OpenCV + AR.Drone) Copyright (C) 2016 puku0x https://github.com/puku0x/cvdrone ----------------------------------------------------------------- INTRODUCTION CV Drone is free software; you can redistribute it and/or modify it under the terms of EITHER: (1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the GNU Lesser General Public License is included with this library in the file cvdrone-license-LGPL.txt. (2) The BSD-style license that is included with this library in the file cvdrone-license-BSD.txt. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files cvdrone-license-LGPL.txt and cvdrone-license-BSD.txt for more details. HOW TO INSTALL Please unzip "cvdrone-master.zip" into an arbitrary directory. HOW TO UNINSTALL Please delete the cvdrone folder. BEFORE YOU BUILD You should install Visual Studio before you build CV Drone. CV Drone supports VC++2010/2012/2013/2015. To download VS, please see http://www.microsoft.com/visualstudio/eng/downloads . HOW TO USE 1. Open \build\vs20xx\test.sln 2. Press F7 to build. 3. Press F5 (or Ctrl+F5) to run. 4. You can play around with OpenCV. Sample codes are in "src\samples". FOR AR.DRONE 1.0 USERS Please update your AR.Drone's firmware to 1.11.5. FOR AR.DRONE 2.0 USERS Please update your AR.Drone's firmware to 2.4.8. FOR VS2010 USERS You can not build CV Drone by VS2010 after you installed VS2012. To build VS2010, 1) You should install "Visual Studio 2010 SP1". [Recommended] or, 2) You should uninstall ".Net Framework 4.5" and re-install "4.0". LIBRARY DEPENDENCIES CV Drone uses following libraries. - OpenCV 3.1.0 <3-clause BSD license> http://opencv.org/ - FFmpeg 2.2.3 http://www.ffmpeg.org/ - stdint.h/inttypes.h for Microsoft Visual Studio r26 https://code.google.com/p/msinttypes/ - POSIX Threads for Win32 2.9.1 http://www.sourceware.org/pthreads-win32/ Marker-based AR sample uses following libraries adding to the above. - GLUT for Win32 3.7.6 http://user.xmission.com/~nate/glut.html - MarkerDetector https://github.com/MasteringOpenCV/code/tree/master/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR License files for each library can be found in the 'licenses' folder. Thank you. ================================================ FILE: samples/camera.xml ================================================ 3 3
f
5.81399719e+002 0. 3.17410492e+002 0. 5.78456116e+002 1.37808365e+002 0. 0. 1.
1 4
f
-5.16806960e-001 2.71592855e-001 4.40666080e-003 -1.29973365e-003
================================================ FILE: samples/old/sample_camera_calibration.cpp ================================================ #include "ardrone/ardrone.h" // Execute calibration #define CALIB_MODE 1 // ON:1 OFF:0 // Parameter for calibration pattern #define PAT_ROW (7) // Rows of pattern #define PAT_COL (10) // Columns of pattern #define PAT_SIZE (PAT_ROW*PAT_COL) #define CHESS_SIZE (24.0) // Size of a pattern [mm] // -------------------------------------------------------------------------- // cvDrawText(Image, Drowing point, Messages) // Description : Draw the specified text. // Return value : NONE // -------------------------------------------------------------------------- inline void cvDrawText(IplImage *image, CvPoint point, const char *fmt, ...) { // Font static CvFont font = cvFont(1.0); // Apply format char text[256]; va_list ap; va_start(ap, fmt); vsprintf(text, fmt, ap); va_end(ap); // Draw the text cvPutText(image, text, point, &font, CV_RGB(0, 255, 0)); } // -------------------------------------------------------------------------- // cvAsk(Message) // Description : Show a question. // Return value : NO:0 YES:1 // -------------------------------------------------------------------------- inline int cvAsk(const char *message, ...) { char *arg; char str[256]; // Apply format va_start(arg, message); vsprintf(str, message, arg); va_end(arg); // Show message box #ifndef _WIN32 //return (MessageBox(NULL, str, "QUESTION", MB_YESNO|MB_ICONQUESTION|MB_TOPMOST|MB_SETFOREGROUND) == IDYES); #else char c = 'n'; printf(str); scanf("%c", &c); return (c == 'y' || c == 'Y'); #endif } #if CALIB_MODE // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Images std::vector images; printf("Press space key to take a sample picture !\n"); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // Convert the camera image to grayscale IplImage *gray = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); cvCvtColor(image, gray, CV_BGR2GRAY); // Detect the chessboard int corner_count = 0; CvSize size = cvSize(PAT_COL, PAT_ROW); CvPoint2D32f corners[PAT_SIZE]; int found = cvFindChessboardCorners(gray, size, corners, &corner_count, CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE|CV_CALIB_CB_FAST_CHECK); // Chessboard detected if (found) { // Draw corners cvDrawChessboardCorners(image, size, corners, corner_count, found); // If you push Space key if (key == ' ') { // Add to buffer images.push_back(gray); } else { // Release the image cvReleaseImage(&gray); } } // Failed to detect else { // Release the image cvReleaseImage(&gray); } // Display the image cvDrawText(image, cvPoint(15, 20), "NUM = %d", (int)images.size()); cvShowImage("camera", image); } // Destroy the window cvDestroyWindow("camera"); // At least one image was taken if (!images.empty()) { // Total number of images const int num = (int)images.size(); //// For debug //for (int i = 0; i < num; i++) { // char name[256]; // sprintf(name, "images[%d/%d]", i+1, num); // cvShowImage(name, images[i]); // cvWaitKey(0); // cvDestroyWindow(name); //} // Ask save parameters or not if (cvAsk("Do you save the camera parameters ? (y/n)\n")) { // Detect coners int *p_count = (int*)malloc(sizeof(int) * num); CvPoint2D32f *corners = (CvPoint2D32f*)cvAlloc(sizeof(CvPoint2D32f) * num * PAT_SIZE); for (int i = 0; i < num; i++) { // Detect chessboard int corner_count = 0; CvSize size = cvSize(PAT_COL, PAT_ROW); int found = cvFindChessboardCorners(images[i], size, &corners[i * PAT_SIZE], &corner_count); // Convert the corners to sub-pixel cvFindCornerSubPix(images[i], &corners[i * PAT_SIZE], corner_count, cvSize(3, 3), cvSize(-1, -1), cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 20, 0.03)); p_count[i] = corner_count; } // Set the 3D position of patterns CvPoint3D32f *objects = (CvPoint3D32f*)cvAlloc(sizeof(CvPoint3D32f) * num * PAT_SIZE); for (int i = 0; i < num; i++) { for (int j = 0; j < PAT_ROW; j++) { for (int k = 0; k < PAT_COL; k++) { objects[i * PAT_SIZE + j * PAT_COL + k].x = j * CHESS_SIZE; objects[i * PAT_SIZE + j * PAT_COL + k].y = k * CHESS_SIZE; objects[i * PAT_SIZE + j * PAT_COL + k].z = 0.0; } } } // Create matrices CvMat object_points, image_points, point_counts; cvInitMatHeader(&object_points, num * PAT_SIZE, 3, CV_32FC1, objects); cvInitMatHeader(&image_points, num * PAT_SIZE, 1, CV_32FC2, corners); cvInitMatHeader(&point_counts, num, 1, CV_32SC1, p_count); // Estimate intrinsic parameters and distortion coefficients printf("Calicurating parameters..."); CvMat *intrinsic = cvCreateMat(3, 3, CV_32FC1); CvMat *distortion = cvCreateMat(1, 4, CV_32FC1); cvCalibrateCamera2(&object_points, &image_points, &point_counts, cvGetSize(images[0]), intrinsic, distortion); printf("Finished !\n"); // Output a file printf("Generating a XML file..."); CvFileStorage *fs = cvOpenFileStorage("camera.xml", 0, CV_STORAGE_WRITE); cvWrite(fs, "intrinsic", intrinsic); cvWrite(fs, "distortion", distortion); cvReleaseFileStorage(&fs); printf("Finished !\n"); // Release the matrices free(p_count); cvFree(&corners); cvFree(&objects); cvReleaseMat(&intrinsic); cvReleaseMat(&distortion); } // Release the images for (int i = 0; i < num; i++) cvReleaseImage(&images[i]); } // See you ardrone.close(); return 0; } #else // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Image of AR.Drone's camera IplImage *image = ardrone.getImage(); // Read intrincis camera parameters CvFileStorage *fs = cvOpenFileStorage("camera.xml", 0, CV_STORAGE_READ); CvMat *intrinsic = (CvMat*)cvRead(fs, cvGetFileNodeByName(fs, NULL, "intrinsic")); CvMat *distortion = (CvMat*)cvRead(fs, cvGetFileNodeByName(fs, NULL, "distortion")); // Initialize undistortion maps CvMat *mapx = cvCreateMat(image->height, image->width, CV_32FC1); CvMat *mapy = cvCreateMat(image->height, image->width, CV_32FC1); cvInitUndistortMap(intrinsic, distortion, mapx, mapy); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image image = ardrone.getImage(); // Remap the image cvRemap(image, image, mapx, mapy); // Display the image cvShowImage("camera", image); } // Release the matrices cvReleaseMat(&mapx); cvReleaseMat(&mapy); cvReleaseFileStorage(&fs); // See you ardrone.close(); return 0; } #endif ================================================ FILE: samples/old/sample_condens_tracking.cpp ================================================ #include "ardrone/ardrone.h" #include "opencv2/legacy/legacy.hpp" #include "opencv2/legacy/compat.hpp" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Particle filter CvConDensation *con = cvCreateConDensation(4, 0, 3000); // Setup CvMat *lowerBound = cvCreateMat(4, 1, CV_32FC1); CvMat *upperBound = cvCreateMat(4, 1, CV_32FC1); cvmSet(lowerBound, 0, 0, 0); cvmSet(lowerBound, 1, 0, 0); cvmSet(lowerBound, 2, 0, -10); cvmSet(lowerBound, 3, 0, -10); cvmSet(upperBound, 0, 0, ardrone.getImage()->width); cvmSet(upperBound, 1, 0, ardrone.getImage()->height); cvmSet(upperBound, 2, 0, 10); cvmSet(upperBound, 3, 0, 10); // Initialize particle filter cvConDensInitSampleSet(con, lowerBound, upperBound); // Linear system con->DynamMatr[0] = 1.0; con->DynamMatr[1] = 0.0; con->DynamMatr[2] = 1.0; con->DynamMatr[3] = 0.0; con->DynamMatr[4] = 0.0; con->DynamMatr[5] = 1.0; con->DynamMatr[6] = 0.0; con->DynamMatr[7] = 1.0; con->DynamMatr[8] = 0.0; con->DynamMatr[9] = 0.0; con->DynamMatr[10] = 1.0; con->DynamMatr[11] = 0.0; con->DynamMatr[12] = 0.0; con->DynamMatr[13] = 0.0; con->DynamMatr[14] = 0.0; con->DynamMatr[15] = 1.0; // Noises cvRandInit(&(con->RandS[0]), -25, 25, (int)cvGetTickCount()); cvRandInit(&(con->RandS[1]), -25, 25, (int)cvGetTickCount()); cvRandInit(&(con->RandS[2]), -5, 5, (int)cvGetTickCount()); cvRandInit(&(con->RandS[3]), -5, 5, (int)cvGetTickCount()); // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // Create a window cvNamedWindow("binalized"); cvCreateTrackbar("H max", "binalized", &maxH, 255); cvCreateTrackbar("H min", "binalized", &minH, 255); cvCreateTrackbar("S max", "binalized", &maxS, 255); cvCreateTrackbar("S min", "binalized", &minS, 255); cvCreateTrackbar("V max", "binalized", &maxV, 255); cvCreateTrackbar("V min", "binalized", &minV, 255); cvResizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // HSV image IplImage *hsv = cvCloneImage(image); cvCvtColor(image, hsv, CV_RGB2HSV_FULL); // Binalized image IplImage *binalized = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); // Binalize CvScalar lower = cvScalar(minH, minS, minV); CvScalar upper = cvScalar(maxH, maxS, maxV); cvInRangeS(hsv, lower, upper, binalized); // Show result cvShowImage("binalized", binalized); // De-noising cvMorphologyEx(binalized, binalized, NULL, NULL, CV_MOP_CLOSE); // Detect contours CvSeq *contour = NULL, *maxContour = NULL; CvMemStorage *contourStorage = cvCreateMemStorage(); cvFindContours(binalized, contourStorage, &contour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // Find largest contour double max_area = 0.0; while (contour) { double area = fabs(cvContourArea(contour)); if ( area > max_area) { maxContour = contour; max_area = area; } contour = contour->h_next; } // Object detected if (maxContour) { // Draw a contour cvZero(binalized); cvDrawContours(binalized, maxContour, cvScalarAll(255), cvScalarAll(255), 0, CV_FILLED); // Calculate the moments CvMoments moments; cvMoments(binalized, &moments, 1); int my = (int)(moments.m01/moments.m00); int mx = (int)(moments.m10/moments.m00); cvCircle(image, cvPoint(mx, my), 10, CV_RGB(255,0,0)); // Calculate confidences for (int i = 0; i < con->SamplesNum; i++) { // Sample points float x = (con->flSamples[i][0]); float y = (con->flSamples[i][1]); // Valid sample point if (x > 0 && x < image->width && y > 0 && y < image->height) { // Assume as gauss distribution double sigma = 50.0; double dist = hypot(x - mx, y - my); // Distance to moment con->flConfidence[i] = 1.0 / (sqrt (2.0 * CV_PI) * sigma) * expf (-dist*dist / (2.0 * sigma*sigma)); } else con->flConfidence[i] = 0.0; cvCircle(image, cvPointFrom32f(cvPoint2D32f(x, y)), 3, CV_RGB(0,128,con->flConfidence[i] * 50000)); } } // Update phase cvConDensUpdateByTime(con); // Sum of positions and confidences for calcurate weighted mean value double sumX = 0, sumY = 0, sumConf = 0; for (int i = 0; i < con->SamplesNum; i++) { sumX += con->flConfidence[i] * con->flSamples[i][0]; sumY += con->flConfidence[i] * con->flSamples[i][1]; sumConf += con->flConfidence[i]; } // Estimated value if (sumConf > 0.0) { float x = sumX / sumConf; float y = sumY / sumConf; cvCircle(image, cvPointFrom32f(cvPoint2D32f(x, y)), 10, CV_RGB(0,255,0)); } // Display the image cvShowImage("camera", image); // Release memories cvReleaseImage(&hsv); cvReleaseImage(&binalized); cvReleaseMemStorage(&contourStorage); } // Release the particle filter cvReleaseMat(&lowerBound); cvReleaseMat(&upperBound); cvReleaseConDensation(&con); // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_deadreckoning.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Battery printf("Battery = %d%%\n", ardrone.getBatteryPercentage()); // Map IplImage *map = cvCreateImage(cvSize(500, 500), IPL_DEPTH_8U, 3); cvZero(map); // Position matrix cv::Mat P = cv::Mat::zeros(3, 1, CV_64FC1); // Main loop while (1) { // Key input int key = cvWaitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // Orientation double roll = ardrone.getRoll(); double pitch = ardrone.getPitch(); double yaw = ardrone.getYaw(); // Velocity double vx, vy, vz; double velocity = ardrone.getVelocity(&vx, &vy, &vz); // Rotation matrices double _RX[] = { 1.0, 0.0, 0.0, 0.0, cos(roll), -sin(roll), 0.0, sin(roll), cos(roll)}; double _RY[] = { cos(pitch), 0.0, sin(pitch), 0.0, 1.0, 0.0, -sin(pitch), 0.0, cos(pitch)}; double _RZ[] = { cos(yaw), -sin(yaw), 0.0, sin(yaw), cos(yaw), 0.0, 0.0, 0.0, 1.0}; cv::Mat RX(3, 3, CV_64FC1, _RX); cv::Mat RY(3, 3, CV_64FC1, _RY); cv::Mat RZ(3, 3, CV_64FC1, _RZ); // Time static int64 last = cv::getTickCount(); double dt = (cv::getTickCount() - last) / cv::getTickFrequency(); last = cv::getTickCount(); // Local movement double _M[] = {vx * dt, vy * dt, vz * dt}; cv::Mat M(3, 1, CV_64FC1, _M); // Dead reckoning P = P + RZ * RY * RX * M; // Position (x, y, z) double pos[3] = {P.at(0,0), P.at(1,0), P.at(2,0)}; printf("x = %3.2f, y = %3.2f, z = %3.2f", pos[0], pos[1], pos[2]); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double x = 0.0, y = 0.0, z = 0.0, r = 0.0; if (key == 0x260000) x = 1.0; if (key == 0x280000) x = -1.0; if (key == 0x250000) r = 1.0; if (key == 0x270000) r = -1.0; if (key == 'q') z = 1.0; if (key == 'a') z = -1.0; ardrone.move3D(x, y, z, r); // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode%4); // Display the image cvDrawCircle(map, cvPoint(-pos[1]*30.0 + map->width/2, -pos[0]*30.0 + map->height/2), 2, CV_RGB(255,0,0)); cvShowImage("map", map); cvShowImage("camera", image); } // See you ardrone.close(); cvReleaseImage(&map); return 0; } ================================================ FILE: samples/old/sample_default.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Battery printf("Battery = %d%%\n", ardrone.getBatteryPercentage()); // Instructions printf("***************************************\n"); printf("* CV Drone sample program *\n"); printf("* - How to Play - *\n"); printf("***************************************\n"); printf("* *\n"); printf("* - Controls - *\n"); printf("* 'Space' -- Takeoff/Landing *\n"); printf("* 'Up' -- Move forward *\n"); printf("* 'Down' -- Move backward *\n"); printf("* 'Left' -- Turn left *\n"); printf("* 'Right' -- Turn right *\n"); printf("* 'Q' -- Move upward *\n"); printf("* 'A' -- Move downward *\n"); printf("* *\n"); printf("* - Others - *\n"); printf("* 'C' -- Change camera *\n"); printf("* 'Esc' -- Exit *\n"); printf("* *\n"); printf("***************************************\n\n"); while (1) { // Key input int key = cvWaitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 0x260000) vx = 1.0; if (key == 0x280000) vx = -1.0; if (key == 0x250000) vr = 1.0; if (key == 0x270000) vr = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; ardrone.move3D(vx, vy, vz, vr); // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode%4); // Display the image cvShowImage("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_default2.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Battery std::cout << "Battery = " << ardrone.getBatteryPercentage() << "%" << std::endl; // Instructions std::cout << "***************************************" << std::endl; std::cout << "* CV Drone sample program *" << std::endl; std::cout << "* - How to Play - *" << std::endl; std::cout << "***************************************" << std::endl; std::cout << "* *" << std::endl; std::cout << "* - Controls - *" << std::endl; std::cout << "* 'Space' -- Takeoff/Landing *" << std::endl; std::cout << "* 'Up' -- Move forward *" << std::endl; std::cout << "* 'Down' -- Move backward *" << std::endl; std::cout << "* 'Left' -- Turn left *" << std::endl; std::cout << "* 'Right' -- Turn right *" << std::endl; std::cout << "* 'Q' -- Move upward *" << std::endl; std::cout << "* 'A' -- Move downward *" << std::endl; std::cout << "* *" << std::endl; std::cout << "* - Others - *" << std::endl; std::cout << "* 'C' -- Change camera *" << std::endl; std::cout << "* 'Esc' -- Exit *" << std::endl; std::cout << "* *" << std::endl; std::cout << "***************************************\n" << std::endl; while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image cv::Mat image = ardrone.getImage(); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 0x260000) vx = 1.0; if (key == 0x280000) vx = -1.0; if (key == 0x250000) vr = 1.0; if (key == 0x270000) vr = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; ardrone.move3D(vx, vy, vz, vr); // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode%4); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_detection.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // Create a window cvNamedWindow("binalized"); cvCreateTrackbar("H max", "binalized", &maxH, 255); cvCreateTrackbar("H min", "binalized", &minH, 255); cvCreateTrackbar("S max", "binalized", &maxS, 255); cvCreateTrackbar("S min", "binalized", &minS, 255); cvCreateTrackbar("V max", "binalized", &maxV, 255); cvCreateTrackbar("V min", "binalized", &minV, 255); cvResizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cvWaitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // HSV image IplImage *hsv = cvCloneImage(image); cvCvtColor(image, hsv, CV_RGB2HSV_FULL); // Binalized image IplImage *binalized = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); // Binalize CvScalar lower = cvScalar(minH, minS, minV); CvScalar upper = cvScalar(maxH, maxS, maxV); cvInRangeS(hsv, lower, upper, binalized); // Show result cvShowImage("binalized", binalized); // De-noising cvMorphologyEx(binalized, binalized, NULL, NULL, CV_MOP_CLOSE); // Detect contours CvSeq *contour = NULL, *maxContour = NULL; CvMemStorage *contourStorage = cvCreateMemStorage(); cvFindContours(binalized, contourStorage, &contour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // Find largest contour double max_area = 0.0; while (contour) { double area = fabs(cvContourArea(contour)); if (area > max_area) { maxContour = contour; max_area = area; } contour = contour->h_next; } // Object detected if (maxContour) { // Show result CvRect rect = cvBoundingRect(maxContour); CvPoint minPoint, maxPoint; minPoint.x = rect.x; minPoint.y = rect.y; maxPoint.x = rect.x + rect.width; maxPoint.y = rect.y + rect.height; cvRectangle(image, minPoint, maxPoint, CV_RGB(0,255,0)); } // Release memory cvReleaseMemStorage(&contourStorage); // Display the image cvShowImage("camera", image); // Release images cvReleaseImage(&hsv); cvReleaseImage(&binalized); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_detection2.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // Create a window cv::namedWindow("binalized"); cv::createTrackbar("H max", "binalized", &maxH, 255); cv::createTrackbar("H min", "binalized", &minH, 255); cv::createTrackbar("S max", "binalized", &maxS, 255); cv::createTrackbar("S min", "binalized", &minS, 255); cv::createTrackbar("V max", "binalized", &maxV, 255); cv::createTrackbar("V min", "binalized", &minV, 255); cv::resizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image cv::Mat image = ardrone.getImage(); // HSV image cv::Mat hsv; cv::cvtColor(image, hsv, cv::COLOR_BGR2HSV_FULL); // Binalize cv::Mat binalized; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, binalized); // Show result cv::imshow("binalized", binalized); // De-noising cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel); //cv::imshow("morphologyEx", binalized); // Detect contours std::vector> contours; cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); // Find largest contour int contour_index = -1; double max_area = 0.0; for (int i = 0; i < contours.size(); i++) { double area = fabs(cv::contourArea(contours[i])); if (area > max_area) { contour_index = i; max_area = area; } } // Object detected if (contour_index >= 0) { // Show result cv::Rect rect = cv::boundingRect(contours[contour_index]); cv::rectangle(image, rect, cv::Scalar(0,255,0)); //cv::drawContours(image, contours, contour_index, cv::Scalar(0,255,0)); } // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_flight_animation.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Battery printf("Battery = %d%%\n", ardrone.getBatteryPercentage()); // Instructions printf(" Q - ARDRONE_ANIM_PHI_M30_DEG\n"); printf(" A - ARDRONE_ANIM_PHI_30_DEG\n"); printf(" Z - ARDRONE_ANIM_THETA_M30_DEG\n"); printf(" W - ARDRONE_ANIM_THETA_30_DEG\n"); printf(" S - ARDRONE_ANIM_THETA_20DEG_YAW_200DEG\n"); printf(" X - ARDRONE_ANIM_THETA_20DEG_YAW_M200DEG\n"); printf(" E - ARDRONE_ANIM_TURNAROUND\n"); printf(" D - ARDRONE_ANIM_TURNAROUND_GODOWN\n"); printf(" C - ARDRONE_ANIM_YAW_SHAKE\n"); printf(" R - ARDRONE_ANIM_YAW_DANCE\n"); printf(" F - ARDRONE_ANIM_PHI_DANCE\n"); printf(" V - ARDRONE_ANIM_THETA_DANCE\n"); printf(" T - ARDRONE_ANIM_VZ_DANCE\n"); printf(" G - ARDRONE_ANIM_WAVE\n"); printf(" B - ARDRONE_ANIM_PHI_THETA_MIXED\n"); printf(" Y - ARDRONE_ANIM_DOUBLE_PHI_THETA_MIXED\n"); printf(" H - ARDRONE_ANIM_FLIP_AHEAD\n"); printf(" N - ARDRONE_ANIM_FLIP_BEHIND\n"); printf(" U - ARDRONE_ANIM_FLIP_LEFT\n"); printf(" J - ARDRONE_ANIM_FLIP_RIGHT\n"); // Main loop while (1) { // Key input int key = cvWaitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Flight animations if (key == 'q') ardrone.setAnimation(ARDRONE_ANIM_PHI_M30_DEG, 1000); if (key == 'a') ardrone.setAnimation(ARDRONE_ANIM_PHI_30_DEG, 1000); if (key == 'z') ardrone.setAnimation(ARDRONE_ANIM_THETA_M30_DEG, 1000); if (key == 'w') ardrone.setAnimation(ARDRONE_ANIM_THETA_30_DEG, 1000); if (key == 's') ardrone.setAnimation(ARDRONE_ANIM_THETA_20DEG_YAW_200DEG, 1000); if (key == 'x') ardrone.setAnimation(ARDRONE_ANIM_THETA_20DEG_YAW_M200DEG, 1000); if (key == 'e') ardrone.setAnimation(ARDRONE_ANIM_TURNAROUND, 5000); if (key == 'd') ardrone.setAnimation(ARDRONE_ANIM_TURNAROUND_GODOWN, 5000); if (key == 'c') ardrone.setAnimation(ARDRONE_ANIM_YAW_SHAKE, 2000); if (key == 'r') ardrone.setAnimation(ARDRONE_ANIM_YAW_DANCE, 5000); if (key == 'f') ardrone.setAnimation(ARDRONE_ANIM_PHI_DANCE, 5000); if (key == 'v') ardrone.setAnimation(ARDRONE_ANIM_THETA_DANCE, 5000); if (key == 't') ardrone.setAnimation(ARDRONE_ANIM_VZ_DANCE, 5000); if (key == 'g') ardrone.setAnimation(ARDRONE_ANIM_WAVE, 5000); if (key == 'b') ardrone.setAnimation(ARDRONE_ANIM_PHI_THETA_MIXED, 5000); if (key == 'y') ardrone.setAnimation(ARDRONE_ANIM_DOUBLE_PHI_THETA_MIXED, 5000); if (key == 'h') ardrone.setAnimation(ARDRONE_ANIM_FLIP_AHEAD, 15); if (key == 'n') ardrone.setAnimation(ARDRONE_ANIM_FLIP_BEHIND, 15); if (key == 'u') ardrone.setAnimation(ARDRONE_ANIM_FLIP_LEFT, 15); if (key == 'j') ardrone.setAnimation(ARDRONE_ANIM_FLIP_RIGHT, 15); // Display the image cvShowImage("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_hog.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Initialize detector cv::HOGDescriptor hog; hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector()); // Main loop while (1) { // Key input int key = cv::waitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image cv::Mat img = ardrone.getImage(); // Detect std::vector found; hog.detectMultiScale(img, found, 0, cv::Size(4,4), cv::Size(0, 0), 1.5, 2.0); // Show bounding rect std::vector::const_iterator it; for (it = found.begin(); it != found.end(); ++it) { cv::Rect r = *it; cv::rectangle(img, r.tl(), r.br(), cv::Scalar(255,0,0), 2); } // Display the image cv::imshow("hog", img); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_kalman_tracking.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Kalman filter CvKalman *kalman = cvCreateKalman(4, 2); // Setup cvSetIdentity(kalman->measurement_matrix, cvRealScalar(1.0)); cvSetIdentity(kalman->process_noise_cov, cvRealScalar(1e-5)); cvSetIdentity(kalman->measurement_noise_cov, cvRealScalar(0.1)); cvSetIdentity(kalman->error_cov_post, cvRealScalar(1.0)); // Linear system kalman->DynamMatr[0] = 1.0; kalman->DynamMatr[1] = 0.0; kalman->DynamMatr[2] = 1.0; kalman->DynamMatr[3] = 0.0; kalman->DynamMatr[4] = 0.0; kalman->DynamMatr[5] = 1.0; kalman->DynamMatr[6] = 0.0; kalman->DynamMatr[7] = 1.0; kalman->DynamMatr[8] = 0.0; kalman->DynamMatr[9] = 0.0; kalman->DynamMatr[10] = 1.0; kalman->DynamMatr[11] = 0.0; kalman->DynamMatr[12] = 0.0; kalman->DynamMatr[13] = 0.0; kalman->DynamMatr[14] = 0.0; kalman->DynamMatr[15] = 1.0; // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // Create a window cvNamedWindow("binalized"); cvCreateTrackbar("H max", "binalized", &maxH, 255); cvCreateTrackbar("H min", "binalized", &minH, 255); cvCreateTrackbar("S max", "binalized", &maxS, 255); cvCreateTrackbar("S min", "binalized", &minS, 255); cvCreateTrackbar("V max", "binalized", &maxV, 255); cvCreateTrackbar("V min", "binalized", &minV, 255); cvResizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // HSV image IplImage *hsv = cvCloneImage(image); cvCvtColor(image, hsv, CV_RGB2HSV_FULL); // Binalized image IplImage *binalized = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); // Binalize CvScalar lower = cvScalar(minH, minS, minV); CvScalar upper = cvScalar(maxH, maxS, maxV); cvInRangeS(hsv, lower, upper, binalized); // Show result cvShowImage("binalized", binalized); // De-noising cvMorphologyEx(binalized, binalized, NULL, NULL, CV_MOP_CLOSE); // Detect contours CvSeq *contour = NULL, *maxContour = NULL; CvMemStorage *contourStorage = cvCreateMemStorage(); cvFindContours(binalized, contourStorage, &contour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // Find largest contour double max_area = 0.0; while (contour) { double area = fabs(cvContourArea(contour)); if ( area > max_area) { maxContour = contour; max_area = area; } contour = contour->h_next; } // Object detected if (maxContour) { // Draw a contour cvZero(binalized); cvDrawContours(binalized, maxContour, cvScalarAll(255), cvScalarAll(255), 0, CV_FILLED); // Calculate the moments CvMoments moments; cvMoments(binalized, &moments, 1); int my = (int)(moments.m01/moments.m00); int mx = (int)(moments.m10/moments.m00); // Measurements float m[] = {mx, my}; CvMat measurement = cvMat(2, 1, CV_32FC1, m); // Correct phase const CvMat *correction = cvKalmanCorrect(kalman, &measurement); } // Prediction phase const CvMat *prediction = cvKalmanPredict(kalman); // Display the image cvCircle(image, cvPointFrom32f(cvPoint2D32f(prediction->data.fl[0], prediction->data.fl[1])), 10, CV_RGB(0,255,0)); cvShowImage("camera", image); // Release the memories cvReleaseImage(&hsv); cvReleaseImage(&binalized); cvReleaseMemStorage(&contourStorage); } // Release the kalman filter cvReleaseKalman(&kalman); // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_led_animation.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Instructions printf(" Q - BLINK_GREEN_RED\n"); printf(" A - BLINK_GREEN\n"); printf(" Z - BLINK_RED\n"); printf(" W - BLINK_ORANGE\n"); printf(" S - SNAKE_GREEN_RED\n"); printf(" X - FIRE\n"); printf(" E - STANDARD\n"); printf(" D - RED\n"); printf(" C - GREEN\n"); printf(" R - RED_SNAKE\n"); printf(" F - BLANK\n"); printf(" V - RIGHT_MISSILE\n"); printf(" T - LEFT_MISSILE\n"); printf(" G - DOUBLE_MISSILE\n"); printf(" B - FRONT_LEFT_GREEN_OTHERS_RED\n"); printf(" Y - FRONT_RIGHT_GREEN_OTHERS_RED\n"); printf(" H - REAR_RIGHT_GREEN_OTHERS_RED\n"); printf(" N - REAR_LEFT_GREEN_OTHERS_RED\n"); printf(" U - LEFT_GREEN_RIGHT_RED\n"); printf(" J - LEFT_RED_RIGHT_GREEN\n"); printf(" M - BLINK_STANDARD\n"); // Main loop while (1) { // Key input int key = cvWaitKey(100); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // LED animations if (key == 'q') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_GREEN_RED, 0.5, 5); if (key == 'a') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_GREEN, 0.5, 5); if (key == 'z') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_RED, 0.5, 5); if (key == 'w') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_ORANGE, 0.5, 5); if (key == 's') ardrone.setLED(ARDRONE_LED_ANIM_SNAKE_GREEN_RED, 0.5, 5); if (key == 'x') ardrone.setLED(ARDRONE_LED_ANIM_FIRE, 0.5, 5); if (key == 'e') ardrone.setLED(ARDRONE_LED_ANIM_STANDARD, 0.5, 5); if (key == 'd') ardrone.setLED(ARDRONE_LED_ANIM_RED, 0.5, 5); if (key == 'c') ardrone.setLED(ARDRONE_LED_ANIM_GREEN, 0.5, 5); if (key == 'r') ardrone.setLED(ARDRONE_LED_ANIM_RED_SNAKE, 0.5, 5); if (key == 'f') ardrone.setLED(ARDRONE_LED_ANIM_BLANK, 0.5, 5); if (key == 'v') ardrone.setLED(ARDRONE_LED_ANIM_RIGHT_MISSILE, 0.5, 5); if (key == 't') ardrone.setLED(ARDRONE_LED_ANIM_LEFT_MISSILE, 0.5, 5); if (key == 'g') ardrone.setLED(ARDRONE_LED_ANIM_DOUBLE_MISSILE, 0.5, 5); if (key == 'b') ardrone.setLED(ARDRONE_LED_ANIM_FRONT_LEFT_GREEN_OTHERS_RED, 0.5, 5); if (key == 'y') ardrone.setLED(ARDRONE_LED_ANIM_FRONT_RIGHT_GREEN_OTHERS_RED, 0.5, 5); if (key == 'h') ardrone.setLED(ARDRONE_LED_ANIM_REAR_RIGHT_GREEN_OTHERS_RED, 0.5, 5); if (key == 'n') ardrone.setLED(ARDRONE_LED_ANIM_REAR_LEFT_GREEN_OTHERS_RED, 0.5, 5); if (key == 'u') ardrone.setLED(ARDRONE_LED_ANIM_LEFT_GREEN_RIGHT_RED, 0.5, 5); if (key == 'j') ardrone.setLED(ARDRONE_LED_ANIM_LEFT_RED_RIGHT_GREEN, 0.5, 5); if (key == 'm') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_STANDARD, 0.5, 5); // Display the image cvShowImage("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_marker_based_ar.cpp ================================================ // C++ STL #include #include // OpenCV #include // OpenGL #include // AR.Drone #include "ardrone/ardrone.h" // Marker detector #include ".\3rdparty\packtpub\MarkerDetector.hpp" // Parameter for calibration pattern #define PAT_ROWS (7) // Rows of pattern #define PAT_COLS (10) // Columns of pattern #define CHESS_SIZE (24.0) // Size of a pattern [mm] // Global variables ARDrone ardrone; cv::Mat mapx, mapy; CameraCalibration calibration; // -------------------------------------------------------------------------- // buildProjectionMatrix(Camera matrix, Screen width, Screen height) // Description : Calculate projection matrix from camera and screen paremeters. // Return value : Projection matrix // -------------------------------------------------------------------------- Matrix44 buildProjectionMatrix(Matrix33 cameraMatrix, int screen_width, int screen_height) { float d_near = 0.01; // Near clipping distance float d_far = 100; // Far clipping distance // Camera parameters float f_x = cameraMatrix.data[0]; // Focal length in x axis float f_y = cameraMatrix.data[4]; // Focal length in y axis (usually the same?) float c_x = cameraMatrix.data[2]; // Camera primary point x float c_y = cameraMatrix.data[5]; // Camera primary point y Matrix44 projectionMatrix; projectionMatrix.data[0] = -2.0 * f_x / screen_width; projectionMatrix.data[1] = 0.0; projectionMatrix.data[2] = 0.0; projectionMatrix.data[3] = 0.0; projectionMatrix.data[4] = 0.0; projectionMatrix.data[5] = 2.0 * f_y / screen_height; projectionMatrix.data[6] = 0.0; projectionMatrix.data[7] = 0.0; projectionMatrix.data[8] = 2.0 * c_x / screen_width - 1.0; projectionMatrix.data[9] = 2.0 * c_y / screen_height - 1.0; projectionMatrix.data[10] = -(d_far + d_near) / (d_far - d_near); projectionMatrix.data[11] = -1.0; projectionMatrix.data[12] = 0.0; projectionMatrix.data[13] = 0.0; projectionMatrix.data[14] = -2.0 * d_far * d_near / (d_far - d_near); projectionMatrix.data[15] = 0.0; return projectionMatrix; } // -------------------------------------------------------------------------- // idle() // Description : Idle function. // Return value : NONE // -------------------------------------------------------------------------- void idle(void) { // Redisplay glutPostRedisplay(); } // -------------------------------------------------------------------------- // display() // Description : Displaying function. // Return value : NONE // -------------------------------------------------------------------------- void display(void) { // Clear the buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Get an image cv::Mat image_raw = ardrone.getImage(); cv::Mat image; cv::remap(image_raw, image, mapx, mapy, cv::INTER_LINEAR); // Show the image cv::Mat rgb; cv::cvtColor(image, rgb, cv::COLOR_BGR2RGB); cv::flip(rgb, rgb, 0); glDepthMask(GL_FALSE); glDrawPixels(rgb.cols, rgb.rows, GL_RGB, GL_UNSIGNED_BYTE, rgb.data); // Convert to BGRA cv::Mat bgra; cv::cvtColor(image, bgra, cv::COLOR_BGR2BGRA); // Prepare for marker detection BGRAVideoFrame frame; frame.width = bgra.cols; frame.height = bgra.rows; frame.data = bgra.data; frame.stride = bgra.step; // Detect marker(s) MarkerDetector detector(calibration); detector.processFrame(frame); std::vector transformations = detector.getTransformations(); // Calculate projection matrix Matrix44 projectionMatrix = buildProjectionMatrix(calibration.getIntrinsic(), frame.width, frame.height); // Apply the projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(projectionMatrix.data); // Change to model view matrix mode glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Enable depth mask glDepthMask(GL_TRUE); // Enable vertex array glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); // Push current model view matrix glPushMatrix(); // Set line width glLineWidth(3.0f); // Vertex arrays float lineX[] = { 0, 0, 0, 1, 0, 0 }; float lineY[] = { 0, 0, 0, 0, 1, 0 }; float lineZ[] = { 0, 0, 0, 0, 0, 1 }; // 2D plane const GLfloat squareVertices[] = {-0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f}; // 2D plane color (RGBA) const GLubyte squareColors[] = {255, 255, 0, 255, 0, 255, 255, 255, 0, 0, 0, 0, 255, 0, 255, 255}; // Draw AR for (size_t i = 0; i < transformations.size(); i++) { // Get transformation const Transformation &transformation = transformations[i]; Matrix44 glMatrix = transformation.getMat44(); // Load it glLoadMatrixf(reinterpret_cast(&glMatrix.data[0])); // Draw 2D plane glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(2, GL_FLOAT, 0, squareVertices); glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableClientState(GL_COLOR_ARRAY); // Scale of coordinate axes float scale = 0.5; glScalef(scale, scale, scale); // Move it a little glTranslatef(0, 0, 0.1f); // X axis glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glVertexPointer(3, GL_FLOAT, 0, lineX); glDrawArrays(GL_LINES, 0, 2); // Y axis glColor4f(0.0f, 1.0f, 0.0f, 1.0f); glVertexPointer(3, GL_FLOAT, 0, lineY); glDrawArrays(GL_LINES, 0, 2); // Z axis glColor4f(0.0f, 0.0f, 1.0f, 1.0f); glVertexPointer(3, GL_FLOAT, 0, lineZ); glDrawArrays(GL_LINES, 0, 2); } // Disable vertex array glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); // Pop the model view matrix glPopMatrix(); // Swap the buffer glutSwapBuffers(); } // -------------------------------------------------------------------------- // key(Key pressed, X position of cursor, Y position of cursor) // Description : Key input function. // Return value : NONE // -------------------------------------------------------------------------- void key(unsigned char key, int x, int y) { switch (key) { case 0x1b: exit(1); break; default: break; } } // -------------------------------------------------------------------------- // resize(Width of window, Height of window) // Description : Resizing function. // Return value : NONE // -------------------------------------------------------------------------- void resize(int w, int h) { // Set viewport glViewport(0, 0, w, h); // Set projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(30.0, (double)w / (double)h, 0.01, 100.0); } // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Images cv::Mat frame = ardrone.getImage(); // Open XML file std::string filename("camera_ardrone.xml"); std::fstream file(filename.c_str(), std::ios::in); // Not found if (!file.is_open()) { // Image buffer std::vector images; std::cout << "Press Space key to capture an image" << std::endl; std::cout << "Press Esc to exit" << std::endl; // Main loop while (1) { // Key iput int key = cv::waitKey(1); if (key == 0x1b) break; // Get an image frame = ardrone.getImage(); // Convert to grayscale cv::Mat gray; cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY); // Detect a chessboard cv::Size size(PAT_COLS, PAT_ROWS); std::vector corners; bool found = cv::findChessboardCorners(gray, size, corners, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_FAST_CHECK); // Chessboard detected if (found) { // Draw it cv::drawChessboardCorners(frame, size, corners, found); // Space key was pressed if (key == ' ') { // Add to buffer images.push_back(gray); } } // Show the image std::ostringstream stream; stream << "Captured " << images.size() << " image(s)."; cv::putText(frame, stream.str(), cv::Point(10, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1, CV_AA); cv::imshow("Camera Calibration", frame); } // We have enough samples if (images.size() > 4) { cv::Size size(PAT_COLS, PAT_ROWS); std::vector< std::vector > corners2D; std::vector< std::vector > corners3D; for (size_t i = 0; i < images.size(); i++) { // Detect a chessboard std::vector tmp_corners2D; bool found = cv::findChessboardCorners(images[i], size, tmp_corners2D); // Chessboard detected if (found) { // Convert the corners to sub-pixel cv::cornerSubPix(images[i], tmp_corners2D, cvSize(11, 11), cvSize(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS | cv::TermCriteria::COUNT, 30, 0.1)); corners2D.push_back(tmp_corners2D); // Set the 3D position of patterns const float squareSize = CHESS_SIZE; std::vector tmp_corners3D; for (int j = 0; j < size.height; j++) { for (int k = 0; k < size.width; k++) { tmp_corners3D.push_back(cv::Point3f((float)(k*squareSize), (float)(j*squareSize), 0.0)); } } corners3D.push_back(tmp_corners3D); } } // Estimate camera parameters cv::Mat cameraMatrix, distCoeffs; std::vector rvec, tvec; cv::calibrateCamera(corners3D, corners2D, images[0].size(), cameraMatrix, distCoeffs, rvec, tvec, CV_CALIB_FIX_PRINCIPAL_POINT); std::cout << cameraMatrix << std::endl; std::cout << distCoeffs << std::endl; // Save them cv::FileStorage fs(filename, cv::FileStorage::WRITE); fs << "intrinsic" << cameraMatrix; fs << "distortion" << distCoeffs; } // Destroy windows cv::destroyAllWindows(); } // Open XML file cv::FileStorage rfs(filename, cv::FileStorage::READ); if (!rfs.isOpened()) { std::cout << "Failed to open the XML file" << std::endl; return -1; } // Load camera parameters cv::Mat cameraMatrix, distCoeffs; rfs["intrinsic"] >> cameraMatrix; rfs["distortion"] >> distCoeffs; // Create undistort map cv::initUndistortRectifyMap(cameraMatrix, distCoeffs, cv::Mat(), cameraMatrix, frame.size(), CV_32FC1, mapx, mapy); // Set camera parameters float fx = cameraMatrix.at(0, 0); float fy = cameraMatrix.at(1, 1); float cx = cameraMatrix.at(0, 2); float cy = cameraMatrix.at(1, 2); calibration = CameraCalibration(fx, fy, cx, cy); // Initialize GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(frame.cols, frame.rows); glutCreateWindow("Mastering OpenCV with Practical Computer Vision Project"); glutDisplayFunc(display); glutKeyboardFunc(key); glutIdleFunc(idle); // Clea scene glClearColor(0.0, 0.0, 1.0, 1.0); glEnable(GL_DEPTH_TEST); // Start main loop glutMainLoop(); return 0; } ================================================ FILE: samples/old/sample_minimal.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone("192.168.1.1"); // Main loop while (1) { // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // Display the image cvShowImage("camera", image); // Press Esc to exit if (cvWaitKey(1) == 0x1b) break; } return 0; } ================================================ FILE: samples/old/sample_navdata.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Main loop while (1) { // Key input int key = cvWaitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // Orientation double roll = ardrone.getRoll(); double pitch = ardrone.getPitch(); double yaw = ardrone.getYaw(); printf("ardrone.roll = %3.2f [deg]\n", roll * RAD_TO_DEG); printf("ardrone.pitch = %3.2f [deg]\n", pitch * RAD_TO_DEG); printf("ardrone.yaw = %3.2f [deg]\n", yaw * RAD_TO_DEG); // Altitude double altitude = ardrone.getAltitude(); printf("ardrone.altitude = %3.2f [m]\n", altitude); // Velocity double vx, vy, vz; double velocity = ardrone.getVelocity(&vx, &vy, &vz); printf("ardrone.vx = %3.2f [m/s]\n", vx); printf("ardrone.vy = %3.2f [m/s]\n", vy); printf("ardrone.vz = %3.2f [m/s]\n", vz); // Battery int battery = ardrone.getBatteryPercentage(); printf("ardrone.battery = %d [%%]\n", battery); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double x = 0.0, y = 0.0, z = 0.0, r = 0.0; if (key == 0x260000) x = 1.0; if (key == 0x280000) x = -1.0; if (key == 0x250000) r = 1.0; if (key == 0x270000) r = -1.0; ardrone.move3D(x, y, z, r); // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode%4); // Display the image cvShowImage("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_optical_flow.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Image of AR.Drone's camera IplImage *image = ardrone.getImage(); // Variables for optical flow int corner_count = 50; IplImage *gray = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); IplImage *prev = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); cvCvtColor(image, prev, CV_BGR2GRAY); IplImage *eig_img = cvCreateImage(cvGetSize(image), IPL_DEPTH_32F, 1); IplImage *tmp_img = cvCreateImage(cvGetSize(image), IPL_DEPTH_32F, 1); IplImage *prev_pyramid = cvCreateImage(cvSize(image->width+8, image->height/3), IPL_DEPTH_8U, 1); IplImage *curr_pyramid = cvCreateImage(cvSize(image->width+8, image->height/3), IPL_DEPTH_8U, 1); CvPoint2D32f *corners1 = (CvPoint2D32f*)malloc(corner_count * sizeof(CvPoint2D32f)); CvPoint2D32f *corners2 = (CvPoint2D32f*)malloc(corner_count * sizeof(CvPoint2D32f)); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image image = ardrone.getImage(); // Convert the camera image to grayscale cvCvtColor(image, gray, CV_BGR2GRAY); // Detect features int corner_count = 50; cvGoodFeaturesToTrack(prev, eig_img, tmp_img, corners1, &corner_count, 0.1, 5.0, NULL); // Corner detected if (corner_count > 0) { char *status = (char*)malloc(corner_count * sizeof(char)); // Calicurate optical flows CvTermCriteria criteria = cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 20, 0.3); cvCalcOpticalFlowPyrLK(prev, gray, prev_pyramid, curr_pyramid, corners1, corners2, corner_count, cvSize(10, 10), 3, status, NULL, criteria, 0); // Drow the optical flows for (int i = 0; i < corner_count; i++) { cvCircle(image, cvPointFrom32f(corners1[i]), 1, CV_RGB (255, 0, 0)); if (status[i]) cvLine(image, cvPointFrom32f(corners1[i]), cvPointFrom32f(corners2[i]), CV_RGB (0, 0, 255), 1, CV_AA, 0); } // Release the memory free(status); } // Save the last frame cvCopy(gray, prev); // Display the image cvShowImage("camera", image); } // Release the images cvReleaseImage(&gray); cvReleaseImage(&prev); cvReleaseImage(&eig_img); cvReleaseImage(&tmp_img); cvReleaseImage(&prev_pyramid); cvReleaseImage(&curr_pyramid); free(corners1); free(corners2); // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_video_record.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Recording flag bool rec = false; printf("Press 'R' to start/stop recording."); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Video recording start / stop if (key == 'r') { rec = !rec; ardrone.setVideoRecord(rec); } // Get an image IplImage *image = ardrone.getImage(); // Show recording state if (rec) { static CvFont font = cvFont(1.0); cvPutText(image, "REC", cvPoint(10, 20), &font, CV_RGB(255,0,0)); } // Display the image cvShowImage("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/old/sample_video_writer.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Image of AR.Drone's camera IplImage *image = ardrone.getImage(); // Name of video char filename[256]; SYSTEMTIME st; GetLocalTime(&st); sprintf(filename, "cam%d%02d%02d%02d%02d%02d.avi", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); // Create a video writer CvVideoWriter *video = cvCreateVideoWriter(filename, CV_FOURCC('D','I','B',' '), 30, cvGetSize(image)); // Main loop while (1) { // Key input int key = cvWaitKey(33); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image image = ardrone.getImage(); // Write a frame cvWriteFrame(video, image); // Display the image cvShowImage("camera", image); } // Save the video cvReleaseVideoWriter(&video); // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_camera_calibration.cpp ================================================ #include "ardrone/ardrone.h" // Parameter for calibration pattern #define PAT_ROWS (7) // Rows of pattern #define PAT_COLS (10) // Columns of pattern #define CHESS_SIZE (24.0) // Size of a pattern [mm] // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Images cv::Mat frame = ardrone.getImage(); // Open XML file std::string filename("camera.xml"); cv::FileStorage fs(filename, cv::FileStorage::READ); // Not found if (!fs.isOpened()) { // Image buffer std::vector images; std::cout << "Press Space key to capture an image" << std::endl; std::cout << "Press Esc to exit" << std::endl; // Calibration loop while (1) { // Key iput int key = cv::waitKey(1); if (key == 0x1b) break; // Get an image frame = ardrone.getImage(); // Convert to grayscale cv::Mat gray; cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY); // Detect a chessboard cv::Size size(PAT_COLS, PAT_ROWS); std::vector corners; bool found = cv::findChessboardCorners(gray, size, corners, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_FAST_CHECK); // Chessboard detected if (found) { // Draw it cv::drawChessboardCorners(frame, size, corners, found); // Space key was pressed if (key == ' ') { // Add to buffer images.push_back(gray); } } // Show the image std::ostringstream stream; stream << "Captured " << images.size() << " image(s)."; cv::putText(frame, stream.str(), cv::Point(10, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1, cv::LINE_AA); cv::imshow("Camera Calibration", frame); } // We have enough samples if (images.size() > 4) { cv::Size size(PAT_COLS, PAT_ROWS); std::vector< std::vector > corners2D; std::vector< std::vector > corners3D; for (size_t i = 0; i < images.size(); i++) { // Detect a chessboard std::vector tmp_corners2D; bool found = cv::findChessboardCorners(images[i], size, tmp_corners2D); // Chessboard detected if (found) { // Convert the corners to sub-pixel cv::cornerSubPix(images[i], tmp_corners2D, cvSize(11, 11), cvSize(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS | cv::TermCriteria::COUNT, 30, 0.1)); corners2D.push_back(tmp_corners2D); // Set the 3D position of patterns const float squareSize = CHESS_SIZE; std::vector tmp_corners3D; for (int j = 0; j < size.height; j++) { for (int k = 0; k < size.width; k++) { tmp_corners3D.push_back(cv::Point3f((float)(k*squareSize), (float)(j*squareSize), 0.0)); } } corners3D.push_back(tmp_corners3D); } } // Estimate camera parameters cv::Mat cameraMatrix, distCoeffs; std::vector rvec, tvec; cv::calibrateCamera(corners3D, corners2D, images[0].size(), cameraMatrix, distCoeffs, rvec, tvec); std::cout << cameraMatrix << std::endl; std::cout << distCoeffs << std::endl; // Save them cv::FileStorage tmp(filename, cv::FileStorage::WRITE); tmp << "intrinsic" << cameraMatrix; tmp << "distortion" << distCoeffs; tmp.release(); // Reload fs.open(filename, cv::FileStorage::READ); } // Destroy windows cv::destroyAllWindows(); } // Load camera parameters cv::Mat cameraMatrix, distCoeffs; fs["intrinsic"] >> cameraMatrix; fs["distortion"] >> distCoeffs; // Create undistort map cv::Mat mapx, mapy; cv::initUndistortRectifyMap(cameraMatrix, distCoeffs, cv::Mat(), cameraMatrix, frame.size(), CV_32FC1, mapx, mapy); // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image_raw = ardrone.getImage(); // Undistort cv::Mat image; cv::remap(image_raw, image, mapx, mapy, cv::INTER_LINEAR); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_deadreckoning.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Battery std::cout << "Battery = " << ardrone.getBatteryPercentage() << " [%]" << std::endl; // Map cv::Mat map = cv::Mat::zeros(500, 500, CV_8UC3); // Position matrix cv::Mat P = cv::Mat::zeros(3, 1, CV_64FC1); // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // Altitude double altitude = ardrone.getAltitude(); // Orientations double roll = ardrone.getRoll(); double pitch = ardrone.getPitch(); double yaw = ardrone.getYaw(); // Velocities double vx, vy, vz; double velocity = ardrone.getVelocity(&vx, &vy, &vz); cv::Mat V = (cv::Mat1f(3, 1) << vx, vy, vz); // Rotation matrices cv::Mat RZ = (cv::Mat1f(3, 3) << cos(yaw), -sin(yaw), 0.0, sin(yaw), cos(yaw), 0.0, 0.0, 0.0, 1.0); cv::Mat RY = (cv::Mat1f(3, 3) << cos(pitch), 0.0, sin(pitch), 0.0, 1.0, 0.0, -sin(pitch), 0.0, cos(pitch)); cv::Mat RX = (cv::Mat1f(3, 3) << 1.0, 0.0, 0.0, 0.0, cos(roll), -sin(roll), 0.0, sin(roll), cos(roll)); // Time [s] static int64 last = cv::getTickCount(); double dt = (cv::getTickCount() - last) / cv::getTickFrequency(); last = cv::getTickCount(); // Dead-reckoning P = P + RZ * RY * RX * V * dt; // Position (x, y, z) double pos[3] = { P.at(0, 0), P.at(1, 0), P.at(2, 0) }; std::cout << "x = " << pos[0] << "[m], " << "y = " << pos[1] << "[m], " << "z = " << pos[2] << "[m]" << std::endl; // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double x = 0.0, y = 0.0, z = 0.0, r = 0.0; if (key == 'i' || key == CV_VK_UP) vx = 1.0; if (key == 'k' || key == CV_VK_DOWN) vx = -1.0; if (key == 'u' || key == CV_VK_LEFT) vr = 1.0; if (key == 'o' || key == CV_VK_RIGHT) vr = -1.0; if (key == 'j') vy = 1.0; if (key == 'l') vy = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; ardrone.move3D(x, y, z, r); // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode % 4); // Display the image cv::circle(map, cv::Point(-pos[1] * 100.0 + map.cols / 2, -pos[0] * 100.0 + map.rows / 2), 2, CV_RGB(255, 0, 0)); cv::imshow("map", map); cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_default.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Battery std::cout << "Battery = " << ardrone.getBatteryPercentage() << "[%]" << std::endl; // Instructions std::cout << "***************************************" << std::endl; std::cout << "* CV Drone sample program *" << std::endl; std::cout << "* - How to play - *" << std::endl; std::cout << "***************************************" << std::endl; std::cout << "* *" << std::endl; std::cout << "* - Controls - *" << std::endl; std::cout << "* 'Space' -- Takeoff/Landing *" << std::endl; std::cout << "* 'Up' -- Move forward *" << std::endl; std::cout << "* 'Down' -- Move backward *" << std::endl; std::cout << "* 'Left' -- Turn left *" << std::endl; std::cout << "* 'Right' -- Turn right *" << std::endl; std::cout << "* 'Q' -- Move upward *" << std::endl; std::cout << "* 'A' -- Move downward *" << std::endl; std::cout << "* *" << std::endl; std::cout << "* - Others - *" << std::endl; std::cout << "* 'C' -- Change camera *" << std::endl; std::cout << "* 'Esc' -- Exit *" << std::endl; std::cout << "* *" << std::endl; std::cout << "***************************************" << std::endl; while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 'i' || key == CV_VK_UP) vx = 1.0; if (key == 'k' || key == CV_VK_DOWN) vx = -1.0; if (key == 'u' || key == CV_VK_LEFT) vr = 1.0; if (key == 'o' || key == CV_VK_RIGHT) vr = -1.0; if (key == 'j') vy = 1.0; if (key == 'l') vy = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; ardrone.move3D(vx, vy, vz, vr); // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode % 4); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_detection.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // XML save data std::string filename("thresholds.xml"); cv::FileStorage fs(filename, cv::FileStorage::READ); // If there is a save file then read it if (fs.isOpened()) { maxH = fs["H_MAX"]; minH = fs["H_MIN"]; maxS = fs["S_MAX"]; minS = fs["S_MIN"]; maxV = fs["V_MAX"]; minV = fs["V_MIN"]; fs.release(); } // Create a window cv::namedWindow("binalized"); cv::createTrackbar("H max", "binalized", &maxH, 255); cv::createTrackbar("H min", "binalized", &minH, 255); cv::createTrackbar("S max", "binalized", &maxS, 255); cv::createTrackbar("S min", "binalized", &minS, 255); cv::createTrackbar("V max", "binalized", &maxV, 255); cv::createTrackbar("V min", "binalized", &minV, 255); cv::resizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // HSV image cv::Mat hsv; cv::cvtColor(image, hsv, cv::COLOR_BGR2HSV_FULL); // Binalize cv::Mat binalized; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, binalized); // Show result cv::imshow("binalized", binalized); // De-noising cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel); //cv::imshow("morphologyEx", binalized); // Detect contours std::vector< std::vector > contours; cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); // Find largest contour int contour_index = -1; double max_area = 0.0; for (size_t i = 0; i < contours.size(); i++) { double area = fabs(cv::contourArea(contours[i])); if (area > max_area) { contour_index = i; max_area = area; } } // Object detected if (contour_index >= 0) { // Show result cv::Rect rect = cv::boundingRect(contours[contour_index]); cv::rectangle(image, rect, cv::Scalar(0,255,0)); //cv::drawContours(image, contours, contour_index, cv::Scalar(0,255,0)); } // Display the image cv::imshow("camera", image); } // Save thresholds fs.open(filename, cv::FileStorage::WRITE); if (fs.isOpened()) { cv::write(fs, "H_MAX", maxH); cv::write(fs, "H_MIN", minH); cv::write(fs, "S_MAX", maxS); cv::write(fs, "S_MIN", minS); cv::write(fs, "V_MAX", maxV); cv::write(fs, "V_MIN", minV); fs.release(); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_flight_animation.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Battery std::cout << "Battery = " << ardrone.getBatteryPercentage() << "%" << std::endl; // Instructions std::cout << " Q - ARDRONE_ANIM_PHI_M30_DEG " << std::endl; std::cout << " A - ARDRONE_ANIM_PHI_30_DEG " << std::endl; std::cout << " Z - ARDRONE_ANIM_THETA_M30_DEG " << std::endl; std::cout << " W - ARDRONE_ANIM_THETA_30_DEG " << std::endl; std::cout << " S - ARDRONE_ANIM_THETA_20DEG_YAW_200DEG " << std::endl; std::cout << " X - ARDRONE_ANIM_THETA_20DEG_YAW_M200DEG" << std::endl; std::cout << " E - ARDRONE_ANIM_TURNAROUND " << std::endl; std::cout << " D - ARDRONE_ANIM_TURNAROUND_GODOWN " << std::endl; std::cout << " C - ARDRONE_ANIM_YAW_SHAKE " << std::endl; std::cout << " R - ARDRONE_ANIM_YAW_DANCE " << std::endl; std::cout << " F - ARDRONE_ANIM_PHI_DANCE " << std::endl; std::cout << " V - ARDRONE_ANIM_THETA_DANCE " << std::endl; std::cout << " T - ARDRONE_ANIM_VZ_DANCE " << std::endl; std::cout << " G - ARDRONE_ANIM_WAVE " << std::endl; std::cout << " B - ARDRONE_ANIM_PHI_THETA_MIXED " << std::endl; std::cout << " Y - ARDRONE_ANIM_DOUBLE_PHI_THETA_MIXED " << std::endl; std::cout << " H - ARDRONE_ANIM_FLIP_AHEAD " << std::endl; std::cout << " N - ARDRONE_ANIM_FLIP_BEHIND " << std::endl; std::cout << " U - ARDRONE_ANIM_FLIP_LEFT " << std::endl; std::cout << " J - ARDRONE_ANIM_FLIP_RIGHT " << std::endl; // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Flight animations if (key == 'q') ardrone.setAnimation(ARDRONE_ANIM_PHI_M30_DEG); if (key == 'a') ardrone.setAnimation(ARDRONE_ANIM_PHI_30_DEG); if (key == 'z') ardrone.setAnimation(ARDRONE_ANIM_THETA_M30_DEG); if (key == 'w') ardrone.setAnimation(ARDRONE_ANIM_THETA_30_DEG); if (key == 's') ardrone.setAnimation(ARDRONE_ANIM_THETA_20DEG_YAW_200DEG); if (key == 'x') ardrone.setAnimation(ARDRONE_ANIM_THETA_20DEG_YAW_M200DEG); if (key == 'e') ardrone.setAnimation(ARDRONE_ANIM_TURNAROUND); if (key == 'd') ardrone.setAnimation(ARDRONE_ANIM_TURNAROUND_GODOWN); if (key == 'c') ardrone.setAnimation(ARDRONE_ANIM_YAW_SHAKE); if (key == 'r') ardrone.setAnimation(ARDRONE_ANIM_YAW_DANCE); if (key == 'f') ardrone.setAnimation(ARDRONE_ANIM_PHI_DANCE); if (key == 'v') ardrone.setAnimation(ARDRONE_ANIM_THETA_DANCE); if (key == 't') ardrone.setAnimation(ARDRONE_ANIM_VZ_DANCE); if (key == 'g') ardrone.setAnimation(ARDRONE_ANIM_WAVE); if (key == 'b') ardrone.setAnimation(ARDRONE_ANIM_PHI_THETA_MIXED); if (key == 'y') ardrone.setAnimation(ARDRONE_ANIM_DOUBLE_PHI_THETA_MIXED); if (key == 'h') ardrone.setAnimation(ARDRONE_ANIM_FLIP_AHEAD); if (key == 'n') ardrone.setAnimation(ARDRONE_ANIM_FLIP_BEHIND); if (key == 'u') ardrone.setAnimation(ARDRONE_ANIM_FLIP_LEFT); if (key == 'j') ardrone.setAnimation(ARDRONE_ANIM_FLIP_RIGHT); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_hog.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Initialize detector cv::HOGDescriptor hog; hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector()); // Main loop while (1) { // Key input int key = cv::waitKey(1); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // Detect std::vector found; hog.detectMultiScale(image, found, 0, cv::Size(4, 4), cv::Size(0, 0), 1.5, 2.0); // Show bounding rect std::vector::const_iterator it; for (it = found.begin(); it != found.end(); ++it) { cv::Rect r = *it; cv::rectangle(image, r.tl(), r.br(), cv::Scalar(255, 0, 0), 2); } // Display the image cv::imshow("hog", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_kalman_tracking.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // XML save data std::string filename("thresholds.xml"); cv::FileStorage fs(filename, cv::FileStorage::READ); // If there is a save file then read it if (fs.isOpened()) { maxH = fs["H_MAX"]; minH = fs["H_MIN"]; maxS = fs["S_MAX"]; minS = fs["S_MIN"]; maxV = fs["V_MAX"]; minV = fs["V_MIN"]; fs.release(); } // Create a window cv::namedWindow("binalized"); cv::createTrackbar("H max", "binalized", &maxH, 255); cv::createTrackbar("H min", "binalized", &minH, 255); cv::createTrackbar("S max", "binalized", &maxS, 255); cv::createTrackbar("S min", "binalized", &minS, 255); cv::createTrackbar("V max", "binalized", &maxV, 255); cv::createTrackbar("V min", "binalized", &minV, 255); cv::resizeWindow("binalized", 0, 0); // Kalman filter cv::KalmanFilter kalman(4, 2, 0); // Sampling time [s] const double dt = 1.0; // Transition matrix (x, y, vx, vy) cv::Mat1f A(4, 4); A << 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0; kalman.transitionMatrix = A; // Measurement matrix (x, y) cv::Mat1f H(2, 4); H << 1, 0, 0, 0, 0, 1, 0, 0; kalman.measurementMatrix = H; // Process noise covariance (x, y, vx, vy) cv::Mat1f Q(4, 4); Q << 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5; kalman.processNoiseCov = Q; // Measurement noise covariance (x, y) cv::Mat1f R(2, 2); R << 1e-1, 0.0, 0.0, 1e-1; kalman.measurementNoiseCov = R; // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // HSV image cv::Mat hsv; cv::cvtColor(image, hsv, cv::COLOR_BGR2HSV_FULL); // Binalize cv::Mat binalized; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, binalized); // Show result cv::imshow("binalized", binalized); // De-noising cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel); //cv::imshow("morphologyEx", binalized); // Detect contours std::vector< std::vector > contours; cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); // Find the largest contour int contour_index = -1; double max_area = 0.0; for (size_t i = 0; i < contours.size(); i++) { double area = fabs(cv::contourArea(contours[i])); if (area > max_area) { contour_index = i; max_area = area; } } // Object detected if (contour_index >= 0) { // Moments cv::Moments moments = cv::moments(contours[contour_index], true); double marker_y = (int)(moments.m01 / moments.m00); double marker_x = (int)(moments.m10 / moments.m00); // Measurements cv::Mat measurement = (cv::Mat1f(2, 1) << marker_x, marker_y); // Correction cv::Mat estimated = kalman.correct(measurement); // Show result cv::Rect rect = cv::boundingRect(contours[contour_index]); cv::rectangle(image, rect, cv::Scalar(0, 255, 0)); } // Prediction cv::Mat1f prediction = kalman.predict(); int radius = 1e+3 * kalman.errorCovPre.at(0, 0); // Show predicted position cv::circle(image, cv::Point(prediction(0, 0), prediction(0, 1)), radius, cv::Scalar(0, 255, 0), 2); // Display the image cv::imshow("camera", image); } // Save thresholds fs.open(filename, cv::FileStorage::WRITE); if (fs.isOpened()) { cv::write(fs, "H_MAX", maxH); cv::write(fs, "H_MIN", minH); cv::write(fs, "S_MAX", maxS); cv::write(fs, "S_MIN", minS); cv::write(fs, "V_MAX", maxV); cv::write(fs, "V_MIN", minV); fs.release(); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_led_animation.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Instructions std::cout << " Q - BLINK_GREEN_RED " << std::endl; std::cout << " A - BLINK_GREEN " << std::endl; std::cout << " Z - BLINK_RED " << std::endl; std::cout << " W - BLINK_ORANGE " << std::endl; std::cout << " S - SNAKE_GREEN_RED " << std::endl; std::cout << " X - FIRE " << std::endl; std::cout << " E - STANDARD " << std::endl; std::cout << " D - RED " << std::endl; std::cout << " C - GREEN " << std::endl; std::cout << " R - RED_SNAKE " << std::endl; std::cout << " F - BLANK " << std::endl; std::cout << " V - RIGHT_MISSILE " << std::endl; std::cout << " T - LEFT_MISSILE " << std::endl; std::cout << " G - DOUBLE_MISSILE " << std::endl; std::cout << " B - FRONT_LEFT_GREEN_OTHERS_RED " << std::endl; std::cout << " Y - FRONT_RIGHT_GREEN_OTHERS_RED" << std::endl; std::cout << " H - REAR_RIGHT_GREEN_OTHERS_RED " << std::endl; std::cout << " N - REAR_LEFT_GREEN_OTHERS_RED " << std::endl; std::cout << " U - LEFT_GREEN_RIGHT_RED " << std::endl; std::cout << " J - LEFT_RED_RIGHT_GREEN " << std::endl; std::cout << " M - BLINK_STANDARD " << std::endl; // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // LED animations if (key == 'q') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_GREEN_RED); if (key == 'a') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_GREEN); if (key == 'z') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_RED); if (key == 'w') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_ORANGE); if (key == 's') ardrone.setLED(ARDRONE_LED_ANIM_SNAKE_GREEN_RED); if (key == 'x') ardrone.setLED(ARDRONE_LED_ANIM_FIRE); if (key == 'e') ardrone.setLED(ARDRONE_LED_ANIM_STANDARD); if (key == 'd') ardrone.setLED(ARDRONE_LED_ANIM_RED); if (key == 'c') ardrone.setLED(ARDRONE_LED_ANIM_GREEN); if (key == 'r') ardrone.setLED(ARDRONE_LED_ANIM_RED_SNAKE); if (key == 'f') ardrone.setLED(ARDRONE_LED_ANIM_BLANK); if (key == 'v') ardrone.setLED(ARDRONE_LED_ANIM_RIGHT_MISSILE); if (key == 't') ardrone.setLED(ARDRONE_LED_ANIM_LEFT_MISSILE); if (key == 'g') ardrone.setLED(ARDRONE_LED_ANIM_DOUBLE_MISSILE); if (key == 'b') ardrone.setLED(ARDRONE_LED_ANIM_FRONT_LEFT_GREEN_OTHERS_RED); if (key == 'y') ardrone.setLED(ARDRONE_LED_ANIM_FRONT_RIGHT_GREEN_OTHERS_RED); if (key == 'h') ardrone.setLED(ARDRONE_LED_ANIM_REAR_RIGHT_GREEN_OTHERS_RED); if (key == 'n') ardrone.setLED(ARDRONE_LED_ANIM_REAR_LEFT_GREEN_OTHERS_RED); if (key == 'u') ardrone.setLED(ARDRONE_LED_ANIM_LEFT_GREEN_RIGHT_RED); if (key == 'j') ardrone.setLED(ARDRONE_LED_ANIM_LEFT_RED_RIGHT_GREEN); if (key == 'm') ardrone.setLED(ARDRONE_LED_ANIM_BLINK_STANDARD); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_marker_based_ar.cpp ================================================ // C++ STL #include #include // OpenCV #include // OpenGL #include // AR.Drone #include "ardrone/ardrone.h" // Marker detector #include ".\3rdparty\packtpub\MarkerDetector.hpp" // Parameter for calibration pattern #define PAT_ROWS (7) // Rows of pattern #define PAT_COLS (10) // Columns of pattern #define CHESS_SIZE (24.0) // Size of a pattern [mm] // Global variables ARDrone ardrone; cv::Mat mapx, mapy; CameraCalibration calibration; // -------------------------------------------------------------------------- // buildProjectionMatrix(Camera matrix, Screen width, Screen height) // Description : Calculate projection matrix from camera and screen paremeters. // Return value : Projection matrix // -------------------------------------------------------------------------- Matrix44 buildProjectionMatrix(Matrix33 cameraMatrix, int screen_width, int screen_height) { float d_near = 0.01; // Near clipping distance float d_far = 100; // Far clipping distance // Camera parameters float f_x = cameraMatrix.data[0]; // Focal length in x axis float f_y = cameraMatrix.data[4]; // Focal length in y axis (usually the same?) float c_x = cameraMatrix.data[2]; // Camera primary point x float c_y = cameraMatrix.data[5]; // Camera primary point y Matrix44 projectionMatrix; projectionMatrix.data[0] = -2.0 * f_x / screen_width; projectionMatrix.data[1] = 0.0; projectionMatrix.data[2] = 0.0; projectionMatrix.data[3] = 0.0; projectionMatrix.data[4] = 0.0; projectionMatrix.data[5] = 2.0 * f_y / screen_height; projectionMatrix.data[6] = 0.0; projectionMatrix.data[7] = 0.0; projectionMatrix.data[8] = 2.0 * c_x / screen_width - 1.0; projectionMatrix.data[9] = 2.0 * c_y / screen_height - 1.0; projectionMatrix.data[10] = -(d_far + d_near) / (d_far - d_near); projectionMatrix.data[11] = -1.0; projectionMatrix.data[12] = 0.0; projectionMatrix.data[13] = 0.0; projectionMatrix.data[14] = -2.0 * d_far * d_near / (d_far - d_near); projectionMatrix.data[15] = 0.0; return projectionMatrix; } // -------------------------------------------------------------------------- // idle() // Description : Idle function. // Return value : NONE // -------------------------------------------------------------------------- void idle(void) { // Redisplay glutPostRedisplay(); } // -------------------------------------------------------------------------- // display() // Description : Displaying function. // Return value : NONE // -------------------------------------------------------------------------- void display(void) { // Clear the buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Get an image cv::Mat image_raw = ardrone.getImage(); cv::Mat image; cv::remap(image_raw, image, mapx, mapy, cv::INTER_LINEAR); // Show the image cv::Mat rgb; cv::cvtColor(image, rgb, cv::COLOR_BGR2RGB); cv::flip(rgb, rgb, 0); glDepthMask(GL_FALSE); glDrawPixels(rgb.cols, rgb.rows, GL_RGB, GL_UNSIGNED_BYTE, rgb.data); // Convert to BGRA cv::Mat bgra; cv::cvtColor(image, bgra, cv::COLOR_BGR2BGRA); // Prepare for marker detection BGRAVideoFrame frame; frame.width = bgra.cols; frame.height = bgra.rows; frame.data = bgra.data; frame.stride = bgra.step; // Detect marker(s) MarkerDetector detector(calibration); detector.processFrame(frame); std::vector transformations = detector.getTransformations(); // Calculate projection matrix Matrix44 projectionMatrix = buildProjectionMatrix(calibration.getIntrinsic(), frame.width, frame.height); // Apply the projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(projectionMatrix.data); // Change to model view matrix mode glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Enable depth mask glDepthMask(GL_TRUE); // Enable vertex array glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); // Push current model view matrix glPushMatrix(); // Set line width glLineWidth(3.0f); // Vertex arrays float lineX[] = { 0, 0, 0, 1, 0, 0 }; float lineY[] = { 0, 0, 0, 0, 1, 0 }; float lineZ[] = { 0, 0, 0, 0, 0, 1 }; // 2D plane const GLfloat squareVertices[] = {-0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f}; // 2D plane color (RGBA) const GLubyte squareColors[] = {255, 255, 0, 255, 0, 255, 255, 255, 0, 0, 0, 0, 255, 0, 255, 255}; // Draw AR for (size_t i = 0; i < transformations.size(); i++) { // Get transformation const Transformation &transformation = transformations[i]; Matrix44 glMatrix = transformation.getMat44(); // Load it glLoadMatrixf(reinterpret_cast(&glMatrix.data[0])); // Draw 2D plane glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(2, GL_FLOAT, 0, squareVertices); glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableClientState(GL_COLOR_ARRAY); // Scale of coordinate axes float scale = 0.5; glScalef(scale, scale, scale); // Move it a little glTranslatef(0, 0, 0.1f); // X axis glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glVertexPointer(3, GL_FLOAT, 0, lineX); glDrawArrays(GL_LINES, 0, 2); // Y axis glColor4f(0.0f, 1.0f, 0.0f, 1.0f); glVertexPointer(3, GL_FLOAT, 0, lineY); glDrawArrays(GL_LINES, 0, 2); // Z axis glColor4f(0.0f, 0.0f, 1.0f, 1.0f); glVertexPointer(3, GL_FLOAT, 0, lineZ); glDrawArrays(GL_LINES, 0, 2); } // Disable vertex array glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); // Pop the model view matrix glPopMatrix(); // Swap the buffer glutSwapBuffers(); } // -------------------------------------------------------------------------- // key(Key pressed, X position of cursor, Y position of cursor) // Description : Key input function. // Return value : NONE // -------------------------------------------------------------------------- void key(unsigned char key, int x, int y) { switch (key) { case 0x1b: exit(1); break; default: break; } } // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Images cv::Mat frame = ardrone.getImage(); // Open XML file std::string filename("camera.xml"); std::fstream file(filename.c_str(), std::ios::in); // Not found if (!file.is_open()) { // Image buffer std::vector images; std::cout << "Press Space key to capture an image" << std::endl; std::cout << "Press Esc to exit" << std::endl; // Main loop while (1) { // Key iput int key = cv::waitKey(1); if (key == 0x1b) break; // Get an image frame = ardrone.getImage(); // Convert to grayscale cv::Mat gray; cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY); // Detect a chessboard cv::Size size(PAT_COLS, PAT_ROWS); std::vector corners; bool found = cv::findChessboardCorners(gray, size, corners, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_FAST_CHECK); // Chessboard detected if (found) { // Draw it cv::drawChessboardCorners(frame, size, corners, found); // Space key was pressed if (key == ' ') { // Add to buffer images.push_back(gray); } } // Show the image std::ostringstream stream; stream << "Captured " << images.size() << " image(s)."; cv::putText(frame, stream.str(), cv::Point(10, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1, cv::LINE_AA); cv::imshow("Camera Calibration", frame); } // We have enough samples if (images.size() > 4) { cv::Size size(PAT_COLS, PAT_ROWS); std::vector> corners2D; std::vector> corners3D; for (size_t i = 0; i < images.size(); i++) { // Detect a chessboard std::vector tmp_corners2D; bool found = cv::findChessboardCorners(images[i], size, tmp_corners2D); // Chessboard detected if (found) { // Convert the corners to sub-pixel cv::cornerSubPix(images[i], tmp_corners2D, cvSize(11, 11), cvSize(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS | cv::TermCriteria::COUNT, 30, 0.1)); corners2D.push_back(tmp_corners2D); // Set the 3D position of patterns const float squareSize = CHESS_SIZE; std::vector tmp_corners3D; for (int j = 0; j < size.height; j++) { for (int k = 0; k < size.width; k++) { tmp_corners3D.push_back(cv::Point3f((float)(k*squareSize), (float)(j*squareSize), 0.0)); } } corners3D.push_back(tmp_corners3D); } } // Estimate camera parameters cv::Mat cameraMatrix, distCoeffs; std::vector rvec, tvec; cv::calibrateCamera(corners3D, corners2D, images[0].size(), cameraMatrix, distCoeffs, rvec, tvec); std::cout << cameraMatrix << std::endl; std::cout << distCoeffs << std::endl; // Save them cv::FileStorage fs(filename, cv::FileStorage::WRITE); fs << "intrinsic" << cameraMatrix; fs << "distortion" << distCoeffs; } // Destroy windows cv::destroyAllWindows(); } // Open XML file cv::FileStorage rfs(filename, cv::FileStorage::READ); if (!rfs.isOpened()) { std::cout << "Failed to open the XML file" << std::endl; return -1; } // Load camera parameters cv::Mat cameraMatrix, distCoeffs; rfs["intrinsic"] >> cameraMatrix; rfs["distortion"] >> distCoeffs; // Create undistort map cv::initUndistortRectifyMap(cameraMatrix, distCoeffs, cv::Mat(), cameraMatrix, frame.size(), CV_32FC1, mapx, mapy); // Set camera parameters float fx = cameraMatrix.at(0, 0); float fy = cameraMatrix.at(1, 1); float cx = cameraMatrix.at(0, 2); float cy = cameraMatrix.at(1, 2); //calibration = CameraCalibration(fx, fy, cx, cy); calibration = CameraCalibration(fx, fy, frame.cols / 2, frame.rows / 2); // Initialize GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(frame.cols, frame.rows); glutCreateWindow("Mastering OpenCV with Practical Computer Vision Project"); glutDisplayFunc(display); glutKeyboardFunc(key); glutIdleFunc(idle); // Clea scene glClearColor(0.0, 0.0, 1.0, 1.0); glEnable(GL_DEPTH_TEST); // Start main loop glutMainLoop(); return 0; } ================================================ FILE: samples/sample_minimal.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone("192.168.1.1"); // Main loop while (1) { // Get an image cv::Mat image = ardrone.getImage(); // Display the image cv::imshow("camera", image); // Press Esc to exit if (cv::waitKey(1) == 0x1b) break; } return 0; } ================================================ FILE: samples/sample_navdata.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image= ardrone.getImage(); // Orientation double roll = ardrone.getRoll(); double pitch = ardrone.getPitch(); double yaw = ardrone.getYaw(); std::cout << "ardrone.roll = " << roll * RAD_TO_DEG << " [deg]" << std::endl; std::cout << "ardrone.pitch = " << pitch * RAD_TO_DEG << " [deg]" << std::endl; std::cout << "ardrone.yaw = " << yaw * RAD_TO_DEG << " [deg]" << std::endl; // Altitude double altitude = ardrone.getAltitude(); std::cout << "ardrone.altitude = " << altitude << " [m]" << std::endl; // Velocity double v_x, v_y, v_z; double velocity = ardrone.getVelocity(&v_x, &v_y, &v_z); std::cout << "ardrone.vx = " << v_x << " [m/s]" << std::endl; std::cout << "ardrone.vy = " << v_y << " [m/s]" << std::endl; std::cout << "ardrone.vz = " << v_z << " [m/s]" << std::endl; // Battery int battery = ardrone.getBatteryPercentage(); std::cout << "ardrone.battery = " << battery << " [%]" << std::endl; // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 'i' || key == CV_VK_UP) vx = 1.0; if (key == 'k' || key == CV_VK_DOWN) vx = -1.0; if (key == 'u' || key == CV_VK_LEFT) vr = 1.0; if (key == 'o' || key == CV_VK_RIGHT) vr = -1.0; if (key == 'j') vy = 1.0; if (key == 'l') vy = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; ardrone.move3D(vx, vy, vz, vr); // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode%4); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_optical_flow.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Get an image cv::Mat prev_image = ardrone.getImage(); while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // Convert the camera image to grayscale cv::Mat prev_gray, new_gray; cv::cvtColor(image, new_gray, cv::COLOR_BGR2GRAY); cv::cvtColor(prev_image, prev_gray, cv::COLOR_BGR2GRAY); // Detect corners int max_corners = 50; std::vector prev_corners; std::vector new_corners; cv::goodFeaturesToTrack(prev_gray, prev_corners, max_corners, 0.1, 5.0); cv::goodFeaturesToTrack(new_gray, new_corners, max_corners, 0.1, 5.0); // Calclate optical flow std::vector status; std::vector errors; cv::calcOpticalFlowPyrLK(prev_gray, new_gray, prev_corners, new_corners, status, errors); // Save the last frame image.copyTo(prev_image); // Draw optical flow for (size_t i = 0; i < status.size(); i++) { cv::Point p0(ceil(prev_corners[i].x), ceil(prev_corners[i].y)); cv::Point p1(ceil(new_corners[i].x), ceil(new_corners[i].y)); cv::line(image, p0, p1, cv::Scalar(0, 255, 0), 2); } // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode % 4); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_tracking.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Battery std::cout << "Battery = " << ardrone.getBatteryPercentage() << "%" << std::endl; // Instructions std::cout << "***************************************" << std::endl; std::cout << "* CV Drone sample program *" << std::endl; std::cout << "* - How to Play - *" << std::endl; std::cout << "***************************************" << std::endl; std::cout << "* *" << std::endl; std::cout << "* - Controls - *" << std::endl; std::cout << "* 'Space' -- Takeoff/Landing *" << std::endl; std::cout << "* 'Up' -- Move forward *" << std::endl; std::cout << "* 'Down' -- Move backward *" << std::endl; std::cout << "* 'Left' -- Turn left *" << std::endl; std::cout << "* 'Right' -- Turn right *" << std::endl; std::cout << "* 'Q' -- Move upward *" << std::endl; std::cout << "* 'A' -- Move downward *" << std::endl; std::cout << "* *" << std::endl; std::cout << "* - Others - *" << std::endl; std::cout << "* 'T' -- Track marker *" << std::endl; std::cout << "* 'C' -- Change camera *" << std::endl; std::cout << "* 'Esc' -- Exit *" << std::endl; std::cout << "* *" << std::endl; std::cout << "***************************************" << std::endl; // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // XML save data std::string filename("thresholds.xml"); cv::FileStorage fs(filename, cv::FileStorage::READ); // If there is a save file then read it if (fs.isOpened()) { maxH = fs["H_MAX"]; minH = fs["H_MIN"]; maxS = fs["S_MAX"]; minS = fs["S_MIN"]; maxV = fs["V_MAX"]; minV = fs["V_MIN"]; fs.release(); } // Create a window cv::namedWindow("binalized"); cv::createTrackbar("H max", "binalized", &maxH, 255); cv::createTrackbar("H min", "binalized", &minH, 255); cv::createTrackbar("S max", "binalized", &maxS, 255); cv::createTrackbar("S min", "binalized", &minS, 255); cv::createTrackbar("V max", "binalized", &maxV, 255); cv::createTrackbar("V min", "binalized", &minV, 255); cv::resizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Take off / Landing if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } // Move double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 'i' || key == CV_VK_UP) vx = 1.0; if (key == 'k' || key == CV_VK_DOWN) vx = -1.0; if (key == 'u' || key == CV_VK_LEFT) vr = 1.0; if (key == 'o' || key == CV_VK_RIGHT) vr = -1.0; if (key == 'j') vy = 1.0; if (key == 'l') vy = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode % 4); // Switch tracking ON/OFF static int track = 0; if (key == 't') track = !track; // Get an image cv::Mat image = ardrone.getImage(); // HSV image cv::Mat hsv; cv::cvtColor(image, hsv, cv::COLOR_BGR2HSV_FULL); // Binalize cv::Mat binalized; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, binalized); // Show result cv::imshow("binalized", binalized); // De-noising cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel); //cv::imshow("morphologyEx", binalized); // Detect contours std::vector< std::vector > contours; cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); // Find largest contour int contour_index = -1; double max_area = 0.0; for (size_t i = 0; i < contours.size(); i++) { double area = fabs(cv::contourArea(contours[i])); if (area > max_area) { contour_index = i; max_area = area; } } // Object detected if (contour_index >= 0) { // Moments cv::Moments moments = cv::moments(contours[contour_index], true); double marker_y = (int)(moments.m01 / moments.m00); double marker_x = (int)(moments.m10 / moments.m00); // Show result cv::Rect rect = cv::boundingRect(contours[contour_index]); cv::rectangle(image, rect, cv::Scalar(0, 255, 0)); // Tracking if (track) { const double kp = 0.005; vx = 0.1; vy = 0.0; vz = kp * (binalized.rows / 2 - marker_y); vr = kp * (binalized.cols / 2 - marker_x); } } // Display the image cv::putText(image, (track) ? "track on" : "track off", cv::Point(10, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, (track) ? cv::Scalar(0, 0, 255) : cv::Scalar(0, 255, 0), 1, cv::LINE_AA); cv::imshow("camera", image); ardrone.move3D(vx, vy, vz, vr); } // Save thresholds fs.open(filename, cv::FileStorage::WRITE); if (fs.isOpened()) { cv::write(fs, "H_MAX", maxH); cv::write(fs, "H_MIN", minH); cv::write(fs, "S_MAX", maxS); cv::write(fs, "S_MIN", minS); cv::write(fs, "V_MAX", maxV); cv::write(fs, "V_MIN", minV); fs.release(); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_video_record.cpp ================================================ #include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Recording flag bool rec = false; std::cout << "Press 'R' to start/stop recording." << std::endl; // Main loop while (1) { // Key input int key = cv::waitKey(1); if (key == 0x1b) break; // Video recording start / stop if (key == 'r') { rec = !rec; ardrone.setVideoRecord(rec); } // Get an image cv::Mat image = ardrone.getImage(); // Show recording state if (rec) cv::putText(image, "REC", cv::Point(10, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 1, cv::LINE_AA); // Display the image cv::imshow("camera", image); } // See you ardrone.close(); return 0; } ================================================ FILE: samples/sample_video_writer.cpp ================================================ #include "ardrone/ardrone.h" // For std::localtime(); #include // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Image of AR.Drone's camera cv::Mat image = ardrone.getImage(); // Video name std::time_t t = std::time(NULL); std::tm *local = std::localtime(&t); std::ostringstream stream; stream << 1900 + local->tm_year << "-" << 1 + local->tm_mon << "-" << local->tm_mday << "-" << local->tm_hour << "-" << local->tm_min << "-" << local->tm_sec << ".avi"; // Create a video writer cv::VideoWriter writer(stream.str(), cv::VideoWriter::fourcc('D', 'I', 'B', ' '), 30, cv::Size(image.cols, image.rows)); // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image image = ardrone.getImage(); // Write a frame writer << image; // Display the image imshow("camera", image); } // Output the video writer.release(); // See you ardrone.close(); return 0; } ================================================ FILE: src/3rdparty/ffmpeg/include/inttypes.h ================================================ // ISO C9x compliant inttypes.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_INTTYPES_H_ // [ #define _MSC_INTTYPES_H_ #if _MSC_VER > 1000 #pragma once #endif #include "stdint.h" // 7.8 Format conversion of integer types typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t; // 7.8.1 Macros for format specifiers #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 // The fprintf macros for signed integers are: #define PRId8 "d" #define PRIi8 "i" #define PRIdLEAST8 "d" #define PRIiLEAST8 "i" #define PRIdFAST8 "d" #define PRIiFAST8 "i" #define PRId16 "hd" #define PRIi16 "hi" #define PRIdLEAST16 "hd" #define PRIiLEAST16 "hi" #define PRIdFAST16 "hd" #define PRIiFAST16 "hi" #define PRId32 "I32d" #define PRIi32 "I32i" #define PRIdLEAST32 "I32d" #define PRIiLEAST32 "I32i" #define PRIdFAST32 "I32d" #define PRIiFAST32 "I32i" #define PRId64 "I64d" #define PRIi64 "I64i" #define PRIdLEAST64 "I64d" #define PRIiLEAST64 "I64i" #define PRIdFAST64 "I64d" #define PRIiFAST64 "I64i" #define PRIdMAX "I64d" #define PRIiMAX "I64i" #define PRIdPTR "Id" #define PRIiPTR "Ii" // The fprintf macros for unsigned integers are: #define PRIo8 "o" #define PRIu8 "u" #define PRIx8 "x" #define PRIX8 "X" #define PRIoLEAST8 "o" #define PRIuLEAST8 "u" #define PRIxLEAST8 "x" #define PRIXLEAST8 "X" #define PRIoFAST8 "o" #define PRIuFAST8 "u" #define PRIxFAST8 "x" #define PRIXFAST8 "X" #define PRIo16 "ho" #define PRIu16 "hu" #define PRIx16 "hx" #define PRIX16 "hX" #define PRIoLEAST16 "ho" #define PRIuLEAST16 "hu" #define PRIxLEAST16 "hx" #define PRIXLEAST16 "hX" #define PRIoFAST16 "ho" #define PRIuFAST16 "hu" #define PRIxFAST16 "hx" #define PRIXFAST16 "hX" #define PRIo32 "I32o" #define PRIu32 "I32u" #define PRIx32 "I32x" #define PRIX32 "I32X" #define PRIoLEAST32 "I32o" #define PRIuLEAST32 "I32u" #define PRIxLEAST32 "I32x" #define PRIXLEAST32 "I32X" #define PRIoFAST32 "I32o" #define PRIuFAST32 "I32u" #define PRIxFAST32 "I32x" #define PRIXFAST32 "I32X" #define PRIo64 "I64o" #define PRIu64 "I64u" #define PRIx64 "I64x" #define PRIX64 "I64X" #define PRIoLEAST64 "I64o" #define PRIuLEAST64 "I64u" #define PRIxLEAST64 "I64x" #define PRIXLEAST64 "I64X" #define PRIoFAST64 "I64o" #define PRIuFAST64 "I64u" #define PRIxFAST64 "I64x" #define PRIXFAST64 "I64X" #define PRIoMAX "I64o" #define PRIuMAX "I64u" #define PRIxMAX "I64x" #define PRIXMAX "I64X" #define PRIoPTR "Io" #define PRIuPTR "Iu" #define PRIxPTR "Ix" #define PRIXPTR "IX" // The fscanf macros for signed integers are: #define SCNd8 "d" #define SCNi8 "i" #define SCNdLEAST8 "d" #define SCNiLEAST8 "i" #define SCNdFAST8 "d" #define SCNiFAST8 "i" #define SCNd16 "hd" #define SCNi16 "hi" #define SCNdLEAST16 "hd" #define SCNiLEAST16 "hi" #define SCNdFAST16 "hd" #define SCNiFAST16 "hi" #define SCNd32 "ld" #define SCNi32 "li" #define SCNdLEAST32 "ld" #define SCNiLEAST32 "li" #define SCNdFAST32 "ld" #define SCNiFAST32 "li" #define SCNd64 "I64d" #define SCNi64 "I64i" #define SCNdLEAST64 "I64d" #define SCNiLEAST64 "I64i" #define SCNdFAST64 "I64d" #define SCNiFAST64 "I64i" #define SCNdMAX "I64d" #define SCNiMAX "I64i" #ifdef _WIN64 // [ # define SCNdPTR "I64d" # define SCNiPTR "I64i" #else // _WIN64 ][ # define SCNdPTR "ld" # define SCNiPTR "li" #endif // _WIN64 ] // The fscanf macros for unsigned integers are: #define SCNo8 "o" #define SCNu8 "u" #define SCNx8 "x" #define SCNX8 "X" #define SCNoLEAST8 "o" #define SCNuLEAST8 "u" #define SCNxLEAST8 "x" #define SCNXLEAST8 "X" #define SCNoFAST8 "o" #define SCNuFAST8 "u" #define SCNxFAST8 "x" #define SCNXFAST8 "X" #define SCNo16 "ho" #define SCNu16 "hu" #define SCNx16 "hx" #define SCNX16 "hX" #define SCNoLEAST16 "ho" #define SCNuLEAST16 "hu" #define SCNxLEAST16 "hx" #define SCNXLEAST16 "hX" #define SCNoFAST16 "ho" #define SCNuFAST16 "hu" #define SCNxFAST16 "hx" #define SCNXFAST16 "hX" #define SCNo32 "lo" #define SCNu32 "lu" #define SCNx32 "lx" #define SCNX32 "lX" #define SCNoLEAST32 "lo" #define SCNuLEAST32 "lu" #define SCNxLEAST32 "lx" #define SCNXLEAST32 "lX" #define SCNoFAST32 "lo" #define SCNuFAST32 "lu" #define SCNxFAST32 "lx" #define SCNXFAST32 "lX" #define SCNo64 "I64o" #define SCNu64 "I64u" #define SCNx64 "I64x" #define SCNX64 "I64X" #define SCNoLEAST64 "I64o" #define SCNuLEAST64 "I64u" #define SCNxLEAST64 "I64x" #define SCNXLEAST64 "I64X" #define SCNoFAST64 "I64o" #define SCNuFAST64 "I64u" #define SCNxFAST64 "I64x" #define SCNXFAST64 "I64X" #define SCNoMAX "I64o" #define SCNuMAX "I64u" #define SCNxMAX "I64x" #define SCNXMAX "I64X" #ifdef _WIN64 // [ # define SCNoPTR "I64o" # define SCNuPTR "I64u" # define SCNxPTR "I64x" # define SCNXPTR "I64X" #else // _WIN64 ][ # define SCNoPTR "lo" # define SCNuPTR "lu" # define SCNxPTR "lx" # define SCNXPTR "lX" #endif // _WIN64 ] #endif // __STDC_FORMAT_MACROS ] // 7.8.2 Functions for greatest-width integer types // 7.8.2.1 The imaxabs function #define imaxabs _abs64 // 7.8.2.2 The imaxdiv function // This is modified version of div() function from Microsoft's div.c found // in %MSVC.NET%\crt\src\div.c #ifdef STATIC_IMAXDIV // [ static #else // STATIC_IMAXDIV ][ _inline #endif // STATIC_IMAXDIV ] imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) { imaxdiv_t result; result.quot = numer / denom; result.rem = numer % denom; if (numer < 0 && result.rem > 0) { // did division wrong; must fix up ++result.quot; result.rem -= denom; } return result; } // 7.8.2.3 The strtoimax and strtoumax functions #define strtoimax _strtoi64 #define strtoumax _strtoui64 // 7.8.2.4 The wcstoimax and wcstoumax functions #define wcstoimax _wcstoi64 #define wcstoumax _wcstoui64 #endif // _MSC_INTTYPES_H_ ] ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/avcodec.h ================================================ /* * copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_AVCODEC_H #define AVCODEC_AVCODEC_H /** * @file * @ingroup libavc * Libavcodec external API header */ #include #include "libavutil/samplefmt.h" #include "libavutil/attributes.h" #include "libavutil/avutil.h" #include "libavutil/buffer.h" #include "libavutil/cpu.h" #include "libavutil/channel_layout.h" #include "libavutil/dict.h" #include "libavutil/frame.h" #include "libavutil/log.h" #include "libavutil/pixfmt.h" #include "libavutil/rational.h" #include "version.h" #if FF_API_FAST_MALLOC // to provide fast_*alloc #include "libavutil/mem.h" #endif /** * @defgroup libavc Encoding/Decoding Library * @{ * * @defgroup lavc_decoding Decoding * @{ * @} * * @defgroup lavc_encoding Encoding * @{ * @} * * @defgroup lavc_codec Codecs * @{ * @defgroup lavc_codec_native Native Codecs * @{ * @} * @defgroup lavc_codec_wrappers External library wrappers * @{ * @} * @defgroup lavc_codec_hwaccel Hardware Accelerators bridge * @{ * @} * @} * @defgroup lavc_internal Internal * @{ * @} * @} * */ /** * @defgroup lavc_core Core functions/structures. * @ingroup libavc * * Basic definitions, functions for querying libavcodec capabilities, * allocating core structures, etc. * @{ */ /** * Identify the syntax and semantics of the bitstream. * The principle is roughly: * Two decoders with the same ID can decode the same streams. * Two encoders with the same ID can encode compatible streams. * There may be slight deviations from the principle due to implementation * details. * * If you add a codec ID to this list, add it so that * 1. no value of a existing codec ID changes (that would break ABI), * 2. Give it a value which when taken as ASCII is recognized uniquely by a human as this specific codec. * This ensures that 2 forks can independently add AVCodecIDs without producing conflicts. * * After adding new codec IDs, do not forget to add an entry to the codec * descriptor list and bump libavcodec minor version. */ enum AVCodecID { AV_CODEC_ID_NONE, /* video codecs */ AV_CODEC_ID_MPEG1VIDEO, AV_CODEC_ID_MPEG2VIDEO, ///< preferred ID for MPEG-1/2 video decoding #if FF_API_XVMC AV_CODEC_ID_MPEG2VIDEO_XVMC, #endif /* FF_API_XVMC */ AV_CODEC_ID_H261, AV_CODEC_ID_H263, AV_CODEC_ID_RV10, AV_CODEC_ID_RV20, AV_CODEC_ID_MJPEG, AV_CODEC_ID_MJPEGB, AV_CODEC_ID_LJPEG, AV_CODEC_ID_SP5X, AV_CODEC_ID_JPEGLS, AV_CODEC_ID_MPEG4, AV_CODEC_ID_RAWVIDEO, AV_CODEC_ID_MSMPEG4V1, AV_CODEC_ID_MSMPEG4V2, AV_CODEC_ID_MSMPEG4V3, AV_CODEC_ID_WMV1, AV_CODEC_ID_WMV2, AV_CODEC_ID_H263P, AV_CODEC_ID_H263I, AV_CODEC_ID_FLV1, AV_CODEC_ID_SVQ1, AV_CODEC_ID_SVQ3, AV_CODEC_ID_DVVIDEO, AV_CODEC_ID_HUFFYUV, AV_CODEC_ID_CYUV, AV_CODEC_ID_H264, AV_CODEC_ID_INDEO3, AV_CODEC_ID_VP3, AV_CODEC_ID_THEORA, AV_CODEC_ID_ASV1, AV_CODEC_ID_ASV2, AV_CODEC_ID_FFV1, AV_CODEC_ID_4XM, AV_CODEC_ID_VCR1, AV_CODEC_ID_CLJR, AV_CODEC_ID_MDEC, AV_CODEC_ID_ROQ, AV_CODEC_ID_INTERPLAY_VIDEO, AV_CODEC_ID_XAN_WC3, AV_CODEC_ID_XAN_WC4, AV_CODEC_ID_RPZA, AV_CODEC_ID_CINEPAK, AV_CODEC_ID_WS_VQA, AV_CODEC_ID_MSRLE, AV_CODEC_ID_MSVIDEO1, AV_CODEC_ID_IDCIN, AV_CODEC_ID_8BPS, AV_CODEC_ID_SMC, AV_CODEC_ID_FLIC, AV_CODEC_ID_TRUEMOTION1, AV_CODEC_ID_VMDVIDEO, AV_CODEC_ID_MSZH, AV_CODEC_ID_ZLIB, AV_CODEC_ID_QTRLE, AV_CODEC_ID_TSCC, AV_CODEC_ID_ULTI, AV_CODEC_ID_QDRAW, AV_CODEC_ID_VIXL, AV_CODEC_ID_QPEG, AV_CODEC_ID_PNG, AV_CODEC_ID_PPM, AV_CODEC_ID_PBM, AV_CODEC_ID_PGM, AV_CODEC_ID_PGMYUV, AV_CODEC_ID_PAM, AV_CODEC_ID_FFVHUFF, AV_CODEC_ID_RV30, AV_CODEC_ID_RV40, AV_CODEC_ID_VC1, AV_CODEC_ID_WMV3, AV_CODEC_ID_LOCO, AV_CODEC_ID_WNV1, AV_CODEC_ID_AASC, AV_CODEC_ID_INDEO2, AV_CODEC_ID_FRAPS, AV_CODEC_ID_TRUEMOTION2, AV_CODEC_ID_BMP, AV_CODEC_ID_CSCD, AV_CODEC_ID_MMVIDEO, AV_CODEC_ID_ZMBV, AV_CODEC_ID_AVS, AV_CODEC_ID_SMACKVIDEO, AV_CODEC_ID_NUV, AV_CODEC_ID_KMVC, AV_CODEC_ID_FLASHSV, AV_CODEC_ID_CAVS, AV_CODEC_ID_JPEG2000, AV_CODEC_ID_VMNC, AV_CODEC_ID_VP5, AV_CODEC_ID_VP6, AV_CODEC_ID_VP6F, AV_CODEC_ID_TARGA, AV_CODEC_ID_DSICINVIDEO, AV_CODEC_ID_TIERTEXSEQVIDEO, AV_CODEC_ID_TIFF, AV_CODEC_ID_GIF, AV_CODEC_ID_DXA, AV_CODEC_ID_DNXHD, AV_CODEC_ID_THP, AV_CODEC_ID_SGI, AV_CODEC_ID_C93, AV_CODEC_ID_BETHSOFTVID, AV_CODEC_ID_PTX, AV_CODEC_ID_TXD, AV_CODEC_ID_VP6A, AV_CODEC_ID_AMV, AV_CODEC_ID_VB, AV_CODEC_ID_PCX, AV_CODEC_ID_SUNRAST, AV_CODEC_ID_INDEO4, AV_CODEC_ID_INDEO5, AV_CODEC_ID_MIMIC, AV_CODEC_ID_RL2, AV_CODEC_ID_ESCAPE124, AV_CODEC_ID_DIRAC, AV_CODEC_ID_BFI, AV_CODEC_ID_CMV, AV_CODEC_ID_MOTIONPIXELS, AV_CODEC_ID_TGV, AV_CODEC_ID_TGQ, AV_CODEC_ID_TQI, AV_CODEC_ID_AURA, AV_CODEC_ID_AURA2, AV_CODEC_ID_V210X, AV_CODEC_ID_TMV, AV_CODEC_ID_V210, AV_CODEC_ID_DPX, AV_CODEC_ID_MAD, AV_CODEC_ID_FRWU, AV_CODEC_ID_FLASHSV2, AV_CODEC_ID_CDGRAPHICS, AV_CODEC_ID_R210, AV_CODEC_ID_ANM, AV_CODEC_ID_BINKVIDEO, AV_CODEC_ID_IFF_ILBM, AV_CODEC_ID_IFF_BYTERUN1, AV_CODEC_ID_KGV1, AV_CODEC_ID_YOP, AV_CODEC_ID_VP8, AV_CODEC_ID_PICTOR, AV_CODEC_ID_ANSI, AV_CODEC_ID_A64_MULTI, AV_CODEC_ID_A64_MULTI5, AV_CODEC_ID_R10K, AV_CODEC_ID_MXPEG, AV_CODEC_ID_LAGARITH, AV_CODEC_ID_PRORES, AV_CODEC_ID_JV, AV_CODEC_ID_DFA, AV_CODEC_ID_WMV3IMAGE, AV_CODEC_ID_VC1IMAGE, AV_CODEC_ID_UTVIDEO, AV_CODEC_ID_BMV_VIDEO, AV_CODEC_ID_VBLE, AV_CODEC_ID_DXTORY, AV_CODEC_ID_V410, AV_CODEC_ID_XWD, AV_CODEC_ID_CDXL, AV_CODEC_ID_XBM, AV_CODEC_ID_ZEROCODEC, AV_CODEC_ID_MSS1, AV_CODEC_ID_MSA1, AV_CODEC_ID_TSCC2, AV_CODEC_ID_MTS2, AV_CODEC_ID_CLLC, AV_CODEC_ID_MSS2, AV_CODEC_ID_VP9, AV_CODEC_ID_AIC, AV_CODEC_ID_ESCAPE130_DEPRECATED, AV_CODEC_ID_G2M_DEPRECATED, AV_CODEC_ID_WEBP_DEPRECATED, AV_CODEC_ID_HNM4_VIDEO, AV_CODEC_ID_HEVC_DEPRECATED, AV_CODEC_ID_FIC, AV_CODEC_ID_BRENDER_PIX= MKBETAG('B','P','I','X'), AV_CODEC_ID_Y41P = MKBETAG('Y','4','1','P'), AV_CODEC_ID_ESCAPE130 = MKBETAG('E','1','3','0'), AV_CODEC_ID_EXR = MKBETAG('0','E','X','R'), AV_CODEC_ID_AVRP = MKBETAG('A','V','R','P'), AV_CODEC_ID_012V = MKBETAG('0','1','2','V'), AV_CODEC_ID_G2M = MKBETAG( 0 ,'G','2','M'), AV_CODEC_ID_AVUI = MKBETAG('A','V','U','I'), AV_CODEC_ID_AYUV = MKBETAG('A','Y','U','V'), AV_CODEC_ID_TARGA_Y216 = MKBETAG('T','2','1','6'), AV_CODEC_ID_V308 = MKBETAG('V','3','0','8'), AV_CODEC_ID_V408 = MKBETAG('V','4','0','8'), AV_CODEC_ID_YUV4 = MKBETAG('Y','U','V','4'), AV_CODEC_ID_SANM = MKBETAG('S','A','N','M'), AV_CODEC_ID_PAF_VIDEO = MKBETAG('P','A','F','V'), AV_CODEC_ID_AVRN = MKBETAG('A','V','R','n'), AV_CODEC_ID_CPIA = MKBETAG('C','P','I','A'), AV_CODEC_ID_XFACE = MKBETAG('X','F','A','C'), AV_CODEC_ID_SGIRLE = MKBETAG('S','G','I','R'), AV_CODEC_ID_MVC1 = MKBETAG('M','V','C','1'), AV_CODEC_ID_MVC2 = MKBETAG('M','V','C','2'), AV_CODEC_ID_SNOW = MKBETAG('S','N','O','W'), AV_CODEC_ID_WEBP = MKBETAG('W','E','B','P'), AV_CODEC_ID_SMVJPEG = MKBETAG('S','M','V','J'), AV_CODEC_ID_HEVC = MKBETAG('H','2','6','5'), #define AV_CODEC_ID_H265 AV_CODEC_ID_HEVC /* various PCM "codecs" */ AV_CODEC_ID_FIRST_AUDIO = 0x10000, ///< A dummy id pointing at the start of audio codecs AV_CODEC_ID_PCM_S16LE = 0x10000, AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_U16LE, AV_CODEC_ID_PCM_U16BE, AV_CODEC_ID_PCM_S8, AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_MULAW, AV_CODEC_ID_PCM_ALAW, AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE, AV_CODEC_ID_PCM_U32LE, AV_CODEC_ID_PCM_U32BE, AV_CODEC_ID_PCM_S24LE, AV_CODEC_ID_PCM_S24BE, AV_CODEC_ID_PCM_U24LE, AV_CODEC_ID_PCM_U24BE, AV_CODEC_ID_PCM_S24DAUD, AV_CODEC_ID_PCM_ZORK, AV_CODEC_ID_PCM_S16LE_PLANAR, AV_CODEC_ID_PCM_DVD, AV_CODEC_ID_PCM_F32BE, AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F64BE, AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_BLURAY, AV_CODEC_ID_PCM_LXF, AV_CODEC_ID_S302M, AV_CODEC_ID_PCM_S8_PLANAR, AV_CODEC_ID_PCM_S24LE_PLANAR_DEPRECATED, AV_CODEC_ID_PCM_S32LE_PLANAR_DEPRECATED, AV_CODEC_ID_PCM_S24LE_PLANAR = MKBETAG(24,'P','S','P'), AV_CODEC_ID_PCM_S32LE_PLANAR = MKBETAG(32,'P','S','P'), AV_CODEC_ID_PCM_S16BE_PLANAR = MKBETAG('P','S','P',16), /* various ADPCM codecs */ AV_CODEC_ID_ADPCM_IMA_QT = 0x11000, AV_CODEC_ID_ADPCM_IMA_WAV, AV_CODEC_ID_ADPCM_IMA_DK3, AV_CODEC_ID_ADPCM_IMA_DK4, AV_CODEC_ID_ADPCM_IMA_WS, AV_CODEC_ID_ADPCM_IMA_SMJPEG, AV_CODEC_ID_ADPCM_MS, AV_CODEC_ID_ADPCM_4XM, AV_CODEC_ID_ADPCM_XA, AV_CODEC_ID_ADPCM_ADX, AV_CODEC_ID_ADPCM_EA, AV_CODEC_ID_ADPCM_G726, AV_CODEC_ID_ADPCM_CT, AV_CODEC_ID_ADPCM_SWF, AV_CODEC_ID_ADPCM_YAMAHA, AV_CODEC_ID_ADPCM_SBPRO_4, AV_CODEC_ID_ADPCM_SBPRO_3, AV_CODEC_ID_ADPCM_SBPRO_2, AV_CODEC_ID_ADPCM_THP, AV_CODEC_ID_ADPCM_IMA_AMV, AV_CODEC_ID_ADPCM_EA_R1, AV_CODEC_ID_ADPCM_EA_R3, AV_CODEC_ID_ADPCM_EA_R2, AV_CODEC_ID_ADPCM_IMA_EA_SEAD, AV_CODEC_ID_ADPCM_IMA_EA_EACS, AV_CODEC_ID_ADPCM_EA_XAS, AV_CODEC_ID_ADPCM_EA_MAXIS_XA, AV_CODEC_ID_ADPCM_IMA_ISS, AV_CODEC_ID_ADPCM_G722, AV_CODEC_ID_ADPCM_IMA_APC, AV_CODEC_ID_VIMA = MKBETAG('V','I','M','A'), AV_CODEC_ID_ADPCM_AFC = MKBETAG('A','F','C',' '), AV_CODEC_ID_ADPCM_IMA_OKI = MKBETAG('O','K','I',' '), AV_CODEC_ID_ADPCM_DTK = MKBETAG('D','T','K',' '), AV_CODEC_ID_ADPCM_IMA_RAD = MKBETAG('R','A','D',' '), AV_CODEC_ID_ADPCM_G726LE = MKBETAG('6','2','7','G'), /* AMR */ AV_CODEC_ID_AMR_NB = 0x12000, AV_CODEC_ID_AMR_WB, /* RealAudio codecs*/ AV_CODEC_ID_RA_144 = 0x13000, AV_CODEC_ID_RA_288, /* various DPCM codecs */ AV_CODEC_ID_ROQ_DPCM = 0x14000, AV_CODEC_ID_INTERPLAY_DPCM, AV_CODEC_ID_XAN_DPCM, AV_CODEC_ID_SOL_DPCM, /* audio codecs */ AV_CODEC_ID_MP2 = 0x15000, AV_CODEC_ID_MP3, ///< preferred ID for decoding MPEG audio layer 1, 2 or 3 AV_CODEC_ID_AAC, AV_CODEC_ID_AC3, AV_CODEC_ID_DTS, AV_CODEC_ID_VORBIS, AV_CODEC_ID_DVAUDIO, AV_CODEC_ID_WMAV1, AV_CODEC_ID_WMAV2, AV_CODEC_ID_MACE3, AV_CODEC_ID_MACE6, AV_CODEC_ID_VMDAUDIO, AV_CODEC_ID_FLAC, AV_CODEC_ID_MP3ADU, AV_CODEC_ID_MP3ON4, AV_CODEC_ID_SHORTEN, AV_CODEC_ID_ALAC, AV_CODEC_ID_WESTWOOD_SND1, AV_CODEC_ID_GSM, ///< as in Berlin toast format AV_CODEC_ID_QDM2, AV_CODEC_ID_COOK, AV_CODEC_ID_TRUESPEECH, AV_CODEC_ID_TTA, AV_CODEC_ID_SMACKAUDIO, AV_CODEC_ID_QCELP, AV_CODEC_ID_WAVPACK, AV_CODEC_ID_DSICINAUDIO, AV_CODEC_ID_IMC, AV_CODEC_ID_MUSEPACK7, AV_CODEC_ID_MLP, AV_CODEC_ID_GSM_MS, /* as found in WAV */ AV_CODEC_ID_ATRAC3, #if FF_API_VOXWARE AV_CODEC_ID_VOXWARE, #endif AV_CODEC_ID_APE, AV_CODEC_ID_NELLYMOSER, AV_CODEC_ID_MUSEPACK8, AV_CODEC_ID_SPEEX, AV_CODEC_ID_WMAVOICE, AV_CODEC_ID_WMAPRO, AV_CODEC_ID_WMALOSSLESS, AV_CODEC_ID_ATRAC3P, AV_CODEC_ID_EAC3, AV_CODEC_ID_SIPR, AV_CODEC_ID_MP1, AV_CODEC_ID_TWINVQ, AV_CODEC_ID_TRUEHD, AV_CODEC_ID_MP4ALS, AV_CODEC_ID_ATRAC1, AV_CODEC_ID_BINKAUDIO_RDFT, AV_CODEC_ID_BINKAUDIO_DCT, AV_CODEC_ID_AAC_LATM, AV_CODEC_ID_QDMC, AV_CODEC_ID_CELT, AV_CODEC_ID_G723_1, AV_CODEC_ID_G729, AV_CODEC_ID_8SVX_EXP, AV_CODEC_ID_8SVX_FIB, AV_CODEC_ID_BMV_AUDIO, AV_CODEC_ID_RALF, AV_CODEC_ID_IAC, AV_CODEC_ID_ILBC, AV_CODEC_ID_OPUS_DEPRECATED, AV_CODEC_ID_COMFORT_NOISE, AV_CODEC_ID_TAK_DEPRECATED, AV_CODEC_ID_METASOUND, AV_CODEC_ID_FFWAVESYNTH = MKBETAG('F','F','W','S'), AV_CODEC_ID_SONIC = MKBETAG('S','O','N','C'), AV_CODEC_ID_SONIC_LS = MKBETAG('S','O','N','L'), AV_CODEC_ID_PAF_AUDIO = MKBETAG('P','A','F','A'), AV_CODEC_ID_OPUS = MKBETAG('O','P','U','S'), AV_CODEC_ID_TAK = MKBETAG('t','B','a','K'), AV_CODEC_ID_EVRC = MKBETAG('s','e','v','c'), AV_CODEC_ID_SMV = MKBETAG('s','s','m','v'), /* subtitle codecs */ AV_CODEC_ID_FIRST_SUBTITLE = 0x17000, ///< A dummy ID pointing at the start of subtitle codecs. AV_CODEC_ID_DVD_SUBTITLE = 0x17000, AV_CODEC_ID_DVB_SUBTITLE, AV_CODEC_ID_TEXT, ///< raw UTF-8 text AV_CODEC_ID_XSUB, AV_CODEC_ID_SSA, AV_CODEC_ID_MOV_TEXT, AV_CODEC_ID_HDMV_PGS_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT, AV_CODEC_ID_SRT, AV_CODEC_ID_MICRODVD = MKBETAG('m','D','V','D'), AV_CODEC_ID_EIA_608 = MKBETAG('c','6','0','8'), AV_CODEC_ID_JACOSUB = MKBETAG('J','S','U','B'), AV_CODEC_ID_SAMI = MKBETAG('S','A','M','I'), AV_CODEC_ID_REALTEXT = MKBETAG('R','T','X','T'), AV_CODEC_ID_SUBVIEWER1 = MKBETAG('S','b','V','1'), AV_CODEC_ID_SUBVIEWER = MKBETAG('S','u','b','V'), AV_CODEC_ID_SUBRIP = MKBETAG('S','R','i','p'), AV_CODEC_ID_WEBVTT = MKBETAG('W','V','T','T'), AV_CODEC_ID_MPL2 = MKBETAG('M','P','L','2'), AV_CODEC_ID_VPLAYER = MKBETAG('V','P','l','r'), AV_CODEC_ID_PJS = MKBETAG('P','h','J','S'), AV_CODEC_ID_ASS = MKBETAG('A','S','S',' '), ///< ASS as defined in Matroska /* other specific kind of codecs (generally used for attachments) */ AV_CODEC_ID_FIRST_UNKNOWN = 0x18000, ///< A dummy ID pointing at the start of various fake codecs. AV_CODEC_ID_TTF = 0x18000, AV_CODEC_ID_BINTEXT = MKBETAG('B','T','X','T'), AV_CODEC_ID_XBIN = MKBETAG('X','B','I','N'), AV_CODEC_ID_IDF = MKBETAG( 0 ,'I','D','F'), AV_CODEC_ID_OTF = MKBETAG( 0 ,'O','T','F'), AV_CODEC_ID_SMPTE_KLV = MKBETAG('K','L','V','A'), AV_CODEC_ID_DVD_NAV = MKBETAG('D','N','A','V'), AV_CODEC_ID_TIMED_ID3 = MKBETAG('T','I','D','3'), AV_CODEC_ID_PROBE = 0x19000, ///< codec_id is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it AV_CODEC_ID_MPEG2TS = 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS * stream (only used by libavformat) */ AV_CODEC_ID_MPEG4SYSTEMS = 0x20001, /**< _FAKE_ codec to indicate a MPEG-4 Systems * stream (only used by libavformat) */ AV_CODEC_ID_FFMETADATA = 0x21000, ///< Dummy codec for streams containing only metadata information. #if FF_API_CODEC_ID #include "old_codec_ids.h" #endif }; /** * This struct describes the properties of a single codec described by an * AVCodecID. * @see avcodec_get_descriptor() */ typedef struct AVCodecDescriptor { enum AVCodecID id; enum AVMediaType type; /** * Name of the codec described by this descriptor. It is non-empty and * unique for each codec descriptor. It should contain alphanumeric * characters and '_' only. */ const char *name; /** * A more descriptive name for this codec. May be NULL. */ const char *long_name; /** * Codec properties, a combination of AV_CODEC_PROP_* flags. */ int props; } AVCodecDescriptor; /** * Codec uses only intra compression. * Video codecs only. */ #define AV_CODEC_PROP_INTRA_ONLY (1 << 0) /** * Codec supports lossy compression. Audio and video codecs only. * @note a codec may support both lossy and lossless * compression modes */ #define AV_CODEC_PROP_LOSSY (1 << 1) /** * Codec supports lossless compression. Audio and video codecs only. */ #define AV_CODEC_PROP_LOSSLESS (1 << 2) /** * Subtitle codec is bitmap based * Decoded AVSubtitle data can be read from the AVSubtitleRect->pict field. */ #define AV_CODEC_PROP_BITMAP_SUB (1 << 16) /** * Subtitle codec is text based. * Decoded AVSubtitle data can be read from the AVSubtitleRect->ass field. */ #define AV_CODEC_PROP_TEXT_SUB (1 << 17) /** * @ingroup lavc_decoding * Required number of additionally allocated bytes at the end of the input bitstream for decoding. * This is mainly needed because some optimized bitstream readers read * 32 or 64 bit at once and could read over the end.
* Note: If the first 23 bits of the additional bytes are not 0, then damaged * MPEG bitstreams could cause overread and segfault. */ #define FF_INPUT_BUFFER_PADDING_SIZE 16 /** * @ingroup lavc_encoding * minimum encoding buffer size * Used to avoid some checks during header writing. */ #define FF_MIN_BUFFER_SIZE 16384 /** * @ingroup lavc_encoding * motion estimation type. */ enum Motion_Est_ID { ME_ZERO = 1, ///< no search, that is use 0,0 vector whenever one is needed ME_FULL, ME_LOG, ME_PHODS, ME_EPZS, ///< enhanced predictive zonal search ME_X1, ///< reserved for experiments ME_HEX, ///< hexagon based search ME_UMH, ///< uneven multi-hexagon search ME_TESA, ///< transformed exhaustive search algorithm ME_ITER=50, ///< iterative search }; /** * @ingroup lavc_decoding */ enum AVDiscard{ /* We leave some space between them for extensions (drop some * keyframes for intra-only or drop just some bidir frames). */ AVDISCARD_NONE =-16, ///< discard nothing AVDISCARD_DEFAULT = 0, ///< discard useless packets like 0 size packets in avi AVDISCARD_NONREF = 8, ///< discard all non reference AVDISCARD_BIDIR = 16, ///< discard all bidirectional frames AVDISCARD_NONKEY = 32, ///< discard all frames except keyframes AVDISCARD_ALL = 48, ///< discard all }; enum AVColorPrimaries{ AVCOL_PRI_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B AVCOL_PRI_UNSPECIFIED = 2, AVCOL_PRI_BT470M = 4, AVCOL_PRI_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM AVCOL_PRI_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC AVCOL_PRI_SMPTE240M = 7, ///< functionally identical to above AVCOL_PRI_FILM = 8, AVCOL_PRI_BT2020 = 9, ///< ITU-R BT2020 AVCOL_PRI_NB , ///< Not part of ABI }; enum AVColorTransferCharacteristic{ AVCOL_TRC_BT709 = 1, ///< also ITU-R BT1361 AVCOL_TRC_UNSPECIFIED = 2, AVCOL_TRC_GAMMA22 = 4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM AVCOL_TRC_GAMMA28 = 5, ///< also ITU-R BT470BG AVCOL_TRC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 or 625 / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC AVCOL_TRC_SMPTE240M = 7, AVCOL_TRC_LINEAR = 8, ///< "Linear transfer characteristics" AVCOL_TRC_LOG = 9, ///< "Logarithmic transfer characteristic (100:1 range)" AVCOL_TRC_LOG_SQRT = 10, ///< "Logarithmic transfer characteristic (100 * Sqrt( 10 ) : 1 range)" AVCOL_TRC_IEC61966_2_4 = 11, ///< IEC 61966-2-4 AVCOL_TRC_BT1361_ECG = 12, ///< ITU-R BT1361 Extended Colour Gamut AVCOL_TRC_IEC61966_2_1 = 13, ///< IEC 61966-2-1 (sRGB or sYCC) AVCOL_TRC_BT2020_10 = 14, ///< ITU-R BT2020 for 10 bit system AVCOL_TRC_BT2020_12 = 15, ///< ITU-R BT2020 for 12 bit system AVCOL_TRC_NB , ///< Not part of ABI }; /** * X X 3 4 X X are luma samples, * 1 2 1-6 are possible chroma positions * X X 5 6 X 0 is undefined/unknown position */ enum AVChromaLocation{ AVCHROMA_LOC_UNSPECIFIED = 0, AVCHROMA_LOC_LEFT = 1, ///< mpeg2/4, h264 default AVCHROMA_LOC_CENTER = 2, ///< mpeg1, jpeg, h263 AVCHROMA_LOC_TOPLEFT = 3, ///< DV AVCHROMA_LOC_TOP = 4, AVCHROMA_LOC_BOTTOMLEFT = 5, AVCHROMA_LOC_BOTTOM = 6, AVCHROMA_LOC_NB , ///< Not part of ABI }; enum AVAudioServiceType { AV_AUDIO_SERVICE_TYPE_MAIN = 0, AV_AUDIO_SERVICE_TYPE_EFFECTS = 1, AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED = 2, AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED = 3, AV_AUDIO_SERVICE_TYPE_DIALOGUE = 4, AV_AUDIO_SERVICE_TYPE_COMMENTARY = 5, AV_AUDIO_SERVICE_TYPE_EMERGENCY = 6, AV_AUDIO_SERVICE_TYPE_VOICE_OVER = 7, AV_AUDIO_SERVICE_TYPE_KARAOKE = 8, AV_AUDIO_SERVICE_TYPE_NB , ///< Not part of ABI }; /** * @ingroup lavc_encoding */ typedef struct RcOverride{ int start_frame; int end_frame; int qscale; // If this is 0 then quality_factor will be used instead. float quality_factor; } RcOverride; #if FF_API_MAX_BFRAMES /** * @deprecated there is no libavcodec-wide limit on the number of B-frames */ #define FF_MAX_B_FRAMES 16 #endif /* encoding support These flags can be passed in AVCodecContext.flags before initialization. Note: Not everything is supported yet. */ /** * Allow decoders to produce frames with data planes that are not aligned * to CPU requirements (e.g. due to cropping). */ #define CODEC_FLAG_UNALIGNED 0x0001 #define CODEC_FLAG_QSCALE 0x0002 ///< Use fixed qscale. #define CODEC_FLAG_4MV 0x0004 ///< 4 MV per MB allowed / advanced prediction for H.263. #define CODEC_FLAG_OUTPUT_CORRUPT 0x0008 ///< Output even those frames that might be corrupted #define CODEC_FLAG_QPEL 0x0010 ///< Use qpel MC. #define CODEC_FLAG_GMC 0x0020 ///< Use GMC. #define CODEC_FLAG_MV0 0x0040 ///< Always try a MB with MV=<0,0>. /** * The parent program guarantees that the input for B-frames containing * streams is not written to for at least s->max_b_frames+1 frames, if * this is not set the input will be copied. */ #define CODEC_FLAG_INPUT_PRESERVED 0x0100 #define CODEC_FLAG_PASS1 0x0200 ///< Use internal 2pass ratecontrol in first pass mode. #define CODEC_FLAG_PASS2 0x0400 ///< Use internal 2pass ratecontrol in second pass mode. #define CODEC_FLAG_GRAY 0x2000 ///< Only decode/encode grayscale. #if FF_API_EMU_EDGE /** * @deprecated edges are not used/required anymore. I.e. this flag is now always * set. */ #define CODEC_FLAG_EMU_EDGE 0x4000 #endif #define CODEC_FLAG_PSNR 0x8000 ///< error[?] variables will be set during encoding. #define CODEC_FLAG_TRUNCATED 0x00010000 /** Input bitstream might be truncated at a random location instead of only at frame boundaries. */ #define CODEC_FLAG_NORMALIZE_AQP 0x00020000 ///< Normalize adaptive quantization. #define CODEC_FLAG_INTERLACED_DCT 0x00040000 ///< Use interlaced DCT. #define CODEC_FLAG_LOW_DELAY 0x00080000 ///< Force low delay. #define CODEC_FLAG_GLOBAL_HEADER 0x00400000 ///< Place global headers in extradata instead of every keyframe. #define CODEC_FLAG_BITEXACT 0x00800000 ///< Use only bitexact stuff (except (I)DCT). /* Fx : Flag for h263+ extra options */ #define CODEC_FLAG_AC_PRED 0x01000000 ///< H.263 advanced intra coding / MPEG-4 AC prediction #define CODEC_FLAG_LOOP_FILTER 0x00000800 ///< loop filter #define CODEC_FLAG_INTERLACED_ME 0x20000000 ///< interlaced motion estimation #define CODEC_FLAG_CLOSED_GOP 0x80000000 #define CODEC_FLAG2_FAST 0x00000001 ///< Allow non spec compliant speedup tricks. #define CODEC_FLAG2_NO_OUTPUT 0x00000004 ///< Skip bitstream encoding. #define CODEC_FLAG2_LOCAL_HEADER 0x00000008 ///< Place global headers at every keyframe instead of in extradata. #define CODEC_FLAG2_DROP_FRAME_TIMECODE 0x00002000 ///< timecode is in drop frame format. DEPRECATED!!!! #define CODEC_FLAG2_IGNORE_CROP 0x00010000 ///< Discard cropping information from SPS. #define CODEC_FLAG2_CHUNKS 0x00008000 ///< Input bitstream might be truncated at a packet boundaries instead of only at frame boundaries. #define CODEC_FLAG2_SHOW_ALL 0x00400000 ///< Show all frames before the first keyframe /* Unsupported options : * Syntax Arithmetic coding (SAC) * Reference Picture Selection * Independent Segment Decoding */ /* /Fx */ /* codec capabilities */ #define CODEC_CAP_DRAW_HORIZ_BAND 0x0001 ///< Decoder can use draw_horiz_band callback. /** * Codec uses get_buffer() for allocating buffers and supports custom allocators. * If not set, it might not use get_buffer() at all or use operations that * assume the buffer was allocated by avcodec_default_get_buffer. */ #define CODEC_CAP_DR1 0x0002 #define CODEC_CAP_TRUNCATED 0x0008 #if FF_API_XVMC /* Codec can export data for HW decoding. This flag indicates that * the codec would call get_format() with list that might contain HW accelerated * pixel formats (XvMC, VDPAU, VAAPI, etc). The application can pick any of them * including raw image format. * The application can use the passed context to determine bitstream version, * chroma format, resolution etc. */ #define CODEC_CAP_HWACCEL 0x0010 #endif /* FF_API_XVMC */ /** * Encoder or decoder requires flushing with NULL input at the end in order to * give the complete and correct output. * * NOTE: If this flag is not set, the codec is guaranteed to never be fed with * with NULL data. The user can still send NULL data to the public encode * or decode function, but libavcodec will not pass it along to the codec * unless this flag is set. * * Decoders: * The decoder has a non-zero delay and needs to be fed with avpkt->data=NULL, * avpkt->size=0 at the end to get the delayed data until the decoder no longer * returns frames. * * Encoders: * The encoder needs to be fed with NULL data at the end of encoding until the * encoder no longer returns data. * * NOTE: For encoders implementing the AVCodec.encode2() function, setting this * flag also means that the encoder must set the pts and duration for * each output packet. If this flag is not set, the pts and duration will * be determined by libavcodec from the input frame. */ #define CODEC_CAP_DELAY 0x0020 /** * Codec can be fed a final frame with a smaller size. * This can be used to prevent truncation of the last audio samples. */ #define CODEC_CAP_SMALL_LAST_FRAME 0x0040 #if FF_API_CAP_VDPAU /** * Codec can export data for HW decoding (VDPAU). */ #define CODEC_CAP_HWACCEL_VDPAU 0x0080 #endif /** * Codec can output multiple frames per AVPacket * Normally demuxers return one frame at a time, demuxers which do not do * are connected to a parser to split what they return into proper frames. * This flag is reserved to the very rare category of codecs which have a * bitstream that cannot be split into frames without timeconsuming * operations like full decoding. Demuxers carring such bitstreams thus * may return multiple frames in a packet. This has many disadvantages like * prohibiting stream copy in many cases thus it should only be considered * as a last resort. */ #define CODEC_CAP_SUBFRAMES 0x0100 /** * Codec is experimental and is thus avoided in favor of non experimental * encoders */ #define CODEC_CAP_EXPERIMENTAL 0x0200 /** * Codec should fill in channel configuration and samplerate instead of container */ #define CODEC_CAP_CHANNEL_CONF 0x0400 #if FF_API_NEG_LINESIZES /** * @deprecated no codecs use this capability */ #define CODEC_CAP_NEG_LINESIZES 0x0800 #endif /** * Codec supports frame-level multithreading. */ #define CODEC_CAP_FRAME_THREADS 0x1000 /** * Codec supports slice-based (or partition-based) multithreading. */ #define CODEC_CAP_SLICE_THREADS 0x2000 /** * Codec supports changed parameters at any point. */ #define CODEC_CAP_PARAM_CHANGE 0x4000 /** * Codec supports avctx->thread_count == 0 (auto). */ #define CODEC_CAP_AUTO_THREADS 0x8000 /** * Audio encoder supports receiving a different number of samples in each call. */ #define CODEC_CAP_VARIABLE_FRAME_SIZE 0x10000 /** * Codec is intra only. */ #define CODEC_CAP_INTRA_ONLY 0x40000000 /** * Codec is lossless. */ #define CODEC_CAP_LOSSLESS 0x80000000 #if FF_API_MB_TYPE //The following defines may change, don't expect compatibility if you use them. #define MB_TYPE_INTRA4x4 0x0001 #define MB_TYPE_INTRA16x16 0x0002 //FIXME H.264-specific #define MB_TYPE_INTRA_PCM 0x0004 //FIXME H.264-specific #define MB_TYPE_16x16 0x0008 #define MB_TYPE_16x8 0x0010 #define MB_TYPE_8x16 0x0020 #define MB_TYPE_8x8 0x0040 #define MB_TYPE_INTERLACED 0x0080 #define MB_TYPE_DIRECT2 0x0100 //FIXME #define MB_TYPE_ACPRED 0x0200 #define MB_TYPE_GMC 0x0400 #define MB_TYPE_SKIP 0x0800 #define MB_TYPE_P0L0 0x1000 #define MB_TYPE_P1L0 0x2000 #define MB_TYPE_P0L1 0x4000 #define MB_TYPE_P1L1 0x8000 #define MB_TYPE_L0 (MB_TYPE_P0L0 | MB_TYPE_P1L0) #define MB_TYPE_L1 (MB_TYPE_P0L1 | MB_TYPE_P1L1) #define MB_TYPE_L0L1 (MB_TYPE_L0 | MB_TYPE_L1) #define MB_TYPE_QUANT 0x00010000 #define MB_TYPE_CBP 0x00020000 //Note bits 24-31 are reserved for codec specific use (h264 ref0, mpeg1 0mv, ...) #endif /** * Pan Scan area. * This specifies the area which should be displayed. * Note there may be multiple such areas for one frame. */ typedef struct AVPanScan{ /** * id * - encoding: Set by user. * - decoding: Set by libavcodec. */ int id; /** * width and height in 1/16 pel * - encoding: Set by user. * - decoding: Set by libavcodec. */ int width; int height; /** * position of the top left corner in 1/16 pel for up to 3 fields/frames * - encoding: Set by user. * - decoding: Set by libavcodec. */ int16_t position[3][2]; }AVPanScan; #if FF_API_QSCALE_TYPE #define FF_QSCALE_TYPE_MPEG1 0 #define FF_QSCALE_TYPE_MPEG2 1 #define FF_QSCALE_TYPE_H264 2 #define FF_QSCALE_TYPE_VP56 3 #endif #if FF_API_GET_BUFFER #define FF_BUFFER_TYPE_INTERNAL 1 #define FF_BUFFER_TYPE_USER 2 ///< direct rendering buffers (image is (de)allocated by user) #define FF_BUFFER_TYPE_SHARED 4 ///< Buffer from somewhere else; don't deallocate image (data/base), all other tables are not shared. #define FF_BUFFER_TYPE_COPY 8 ///< Just a (modified) copy of some other buffer, don't deallocate anything. #define FF_BUFFER_HINTS_VALID 0x01 // Buffer hints value is meaningful (if 0 ignore). #define FF_BUFFER_HINTS_READABLE 0x02 // Codec will read from buffer. #define FF_BUFFER_HINTS_PRESERVE 0x04 // User must not alter buffer content. #define FF_BUFFER_HINTS_REUSABLE 0x08 // Codec will reuse the buffer (update). #endif /** * The decoder will keep a reference to the frame and may reuse it later. */ #define AV_GET_BUFFER_FLAG_REF (1 << 0) /** * @defgroup lavc_packet AVPacket * * Types and functions for working with AVPacket. * @{ */ enum AVPacketSideDataType { AV_PKT_DATA_PALETTE, AV_PKT_DATA_NEW_EXTRADATA, /** * An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows: * @code * u32le param_flags * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) * s32le channel_count * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) * u64le channel_layout * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) * s32le sample_rate * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) * s32le width * s32le height * @endcode */ AV_PKT_DATA_PARAM_CHANGE, /** * An AV_PKT_DATA_H263_MB_INFO side data packet contains a number of * structures with info about macroblocks relevant to splitting the * packet into smaller packets on macroblock edges (e.g. as for RFC 2190). * That is, it does not necessarily contain info about all macroblocks, * as long as the distance between macroblocks in the info is smaller * than the target payload size. * Each MB info structure is 12 bytes, and is laid out as follows: * @code * u32le bit offset from the start of the packet * u8 current quantizer at the start of the macroblock * u8 GOB number * u16le macroblock address within the GOB * u8 horizontal MV predictor * u8 vertical MV predictor * u8 horizontal MV predictor for block number 3 * u8 vertical MV predictor for block number 3 * @endcode */ AV_PKT_DATA_H263_MB_INFO, /** * Recommmends skipping the specified number of samples * @code * u32le number of samples to skip from start of this packet * u32le number of samples to skip from end of this packet * u8 reason for start skip * u8 reason for end skip (0=padding silence, 1=convergence) * @endcode */ AV_PKT_DATA_SKIP_SAMPLES=70, /** * An AV_PKT_DATA_JP_DUALMONO side data packet indicates that * the packet may contain "dual mono" audio specific to Japanese DTV * and if it is true, recommends only the selected channel to be used. * @code * u8 selected channels (0=mail/left, 1=sub/right, 2=both) * @endcode */ AV_PKT_DATA_JP_DUALMONO, /** * A list of zero terminated key/value strings. There is no end marker for * the list, so it is required to rely on the side data size to stop. */ AV_PKT_DATA_STRINGS_METADATA, /** * Subtitle event position * @code * u32le x1 * u32le y1 * u32le x2 * u32le y2 * @endcode */ AV_PKT_DATA_SUBTITLE_POSITION, /** * Data found in BlockAdditional element of matroska container. There is * no end marker for the data, so it is required to rely on the side data * size to recognize the end. 8 byte id (as found in BlockAddId) followed * by data. */ AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, /** * The optional first identifier line of a WebVTT cue. */ AV_PKT_DATA_WEBVTT_IDENTIFIER, /** * The optional settings (rendering instructions) that immediately * follow the timestamp specifier of a WebVTT cue. */ AV_PKT_DATA_WEBVTT_SETTINGS, /** * A list of zero terminated key/value strings. There is no end marker for * the list, so it is required to rely on the side data size to stop. This * side data includes updated metadata which appeared in the stream. */ AV_PKT_DATA_METADATA_UPDATE, }; /** * This structure stores compressed data. It is typically exported by demuxers * and then passed as input to decoders, or received as output from encoders and * then passed to muxers. * * For video, it should typically contain one compressed frame. For audio it may * contain several compressed frames. * * AVPacket is one of the few structs in FFmpeg, whose size is a part of public * ABI. Thus it may be allocated on stack and no new fields can be added to it * without libavcodec and libavformat major bump. * * The semantics of data ownership depends on the buf or destruct (deprecated) * fields. If either is set, the packet data is dynamically allocated and is * valid indefinitely until av_free_packet() is called (which in turn calls * av_buffer_unref()/the destruct callback to free the data). If neither is set, * the packet data is typically backed by some static buffer somewhere and is * only valid for a limited time (e.g. until the next read call when demuxing). * * The side data is always allocated with av_malloc() and is freed in * av_free_packet(). */ typedef struct AVPacket { /** * A reference to the reference-counted buffer where the packet data is * stored. * May be NULL, then the packet data is not reference-counted. */ AVBufferRef *buf; /** * Presentation timestamp in AVStream->time_base units; the time at which * the decompressed packet will be presented to the user. * Can be AV_NOPTS_VALUE if it is not stored in the file. * pts MUST be larger or equal to dts as presentation cannot happen before * decompression, unless one wants to view hex dumps. Some formats misuse * the terms dts and pts/cts to mean something different. Such timestamps * must be converted to true pts/dts before they are stored in AVPacket. */ int64_t pts; /** * Decompression timestamp in AVStream->time_base units; the time at which * the packet is decompressed. * Can be AV_NOPTS_VALUE if it is not stored in the file. */ int64_t dts; uint8_t *data; int size; int stream_index; /** * A combination of AV_PKT_FLAG values */ int flags; /** * Additional packet data that can be provided by the container. * Packet can contain several types of side information. */ struct { uint8_t *data; int size; enum AVPacketSideDataType type; } *side_data; int side_data_elems; /** * Duration of this packet in AVStream->time_base units, 0 if unknown. * Equals next_pts - this_pts in presentation order. */ int duration; #if FF_API_DESTRUCT_PACKET attribute_deprecated void (*destruct)(struct AVPacket *); attribute_deprecated void *priv; #endif int64_t pos; ///< byte position in stream, -1 if unknown /** * Time difference in AVStream->time_base units from the pts of this * packet to the point at which the output from the decoder has converged * independent from the availability of previous frames. That is, the * frames are virtually identical no matter if decoding started from * the very first frame or from this keyframe. * Is AV_NOPTS_VALUE if unknown. * This field is not the display duration of the current packet. * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY * set. * * The purpose of this field is to allow seeking in streams that have no * keyframes in the conventional sense. It corresponds to the * recovery point SEI in H.264 and match_time_delta in NUT. It is also * essential for some types of subtitle streams to ensure that all * subtitles are correctly displayed after seeking. */ int64_t convergence_duration; } AVPacket; #define AV_PKT_FLAG_KEY 0x0001 ///< The packet contains a keyframe #define AV_PKT_FLAG_CORRUPT 0x0002 ///< The packet content is corrupted enum AVSideDataParamChangeFlags { AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT = 0x0001, AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT = 0x0002, AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE = 0x0004, AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS = 0x0008, }; /** * @} */ struct AVCodecInternal; enum AVFieldOrder { AV_FIELD_UNKNOWN, AV_FIELD_PROGRESSIVE, AV_FIELD_TT, //< Top coded_first, top displayed first AV_FIELD_BB, //< Bottom coded first, bottom displayed first AV_FIELD_TB, //< Top coded first, bottom displayed first AV_FIELD_BT, //< Bottom coded first, top displayed first }; /** * main external API structure. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * Please use AVOptions (av_opt* / av_set/get*()) to access these fields from user * applications. * sizeof(AVCodecContext) must not be used outside libav*. */ typedef struct AVCodecContext { /** * information on struct for av_log * - set by avcodec_alloc_context3 */ const AVClass *av_class; int log_level_offset; enum AVMediaType codec_type; /* see AVMEDIA_TYPE_xxx */ const struct AVCodec *codec; char codec_name[32]; enum AVCodecID codec_id; /* see AV_CODEC_ID_xxx */ /** * fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A'). * This is used to work around some encoder bugs. * A demuxer should set this to what is stored in the field used to identify the codec. * If there are multiple such fields in a container then the demuxer should choose the one * which maximizes the information about the used codec. * If the codec tag field in a container is larger than 32 bits then the demuxer should * remap the longer ID to 32 bits with a table or other structure. Alternatively a new * extra_codec_tag + size could be added but for this a clear advantage must be demonstrated * first. * - encoding: Set by user, if not then the default based on codec_id will be used. * - decoding: Set by user, will be converted to uppercase by libavcodec during init. */ unsigned int codec_tag; /** * fourcc from the AVI stream header (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A'). * This is used to work around some encoder bugs. * - encoding: unused * - decoding: Set by user, will be converted to uppercase by libavcodec during init. */ unsigned int stream_codec_tag; void *priv_data; /** * Private context used for internal data. * * Unlike priv_data, this is not codec-specific. It is used in general * libavcodec functions. */ struct AVCodecInternal *internal; /** * Private data of the user, can be used to carry app specific stuff. * - encoding: Set by user. * - decoding: Set by user. */ void *opaque; /** * the average bitrate * - encoding: Set by user; unused for constant quantizer encoding. * - decoding: Set by libavcodec. 0 or some bitrate if this info is available in the stream. */ int bit_rate; /** * number of bits the bitstream is allowed to diverge from the reference. * the reference can be CBR (for CBR pass1) or VBR (for pass2) * - encoding: Set by user; unused for constant quantizer encoding. * - decoding: unused */ int bit_rate_tolerance; /** * Global quality for codecs which cannot change it per frame. * This should be proportional to MPEG-1/2/4 qscale. * - encoding: Set by user. * - decoding: unused */ int global_quality; /** * - encoding: Set by user. * - decoding: unused */ int compression_level; #define FF_COMPRESSION_DEFAULT -1 /** * CODEC_FLAG_*. * - encoding: Set by user. * - decoding: Set by user. */ int flags; /** * CODEC_FLAG2_* * - encoding: Set by user. * - decoding: Set by user. */ int flags2; /** * some codecs need / can use extradata like Huffman tables. * mjpeg: Huffman tables * rv10: additional flags * mpeg4: global headers (they can be in the bitstream or here) * The allocated memory should be FF_INPUT_BUFFER_PADDING_SIZE bytes larger * than extradata_size to avoid problems if it is read with the bitstream reader. * The bytewise contents of extradata must not depend on the architecture or CPU endianness. * - encoding: Set/allocated/freed by libavcodec. * - decoding: Set/allocated/freed by user. */ uint8_t *extradata; int extradata_size; /** * This is the fundamental unit of time (in seconds) in terms * of which frame timestamps are represented. For fixed-fps content, * timebase should be 1/framerate and timestamp increments should be * identically 1. * - encoding: MUST be set by user. * - decoding: Set by libavcodec. */ AVRational time_base; /** * For some codecs, the time base is closer to the field rate than the frame rate. * Most notably, H.264 and MPEG-2 specify time_base as half of frame duration * if no telecine is used ... * * Set to time_base ticks per frame. Default 1, e.g., H.264/MPEG-2 set it to 2. */ int ticks_per_frame; /** * Codec delay. * * Encoding: Number of frames delay there will be from the encoder input to * the decoder output. (we assume the decoder matches the spec) * Decoding: Number of frames delay in addition to what a standard decoder * as specified in the spec would produce. * * Video: * Number of frames the decoded output will be delayed relative to the * encoded input. * * Audio: * For encoding, this is the number of "priming" samples added to the * beginning of the stream. The decoded output will be delayed by this * many samples relative to the input to the encoder. Note that this * field is purely informational and does not directly affect the pts * output by the encoder, which should always be based on the actual * presentation time, including any delay. * For decoding, this is the number of samples the decoder needs to * output before the decoder's output is valid. When seeking, you should * start decoding this many samples prior to your desired seek point. * * - encoding: Set by libavcodec. * - decoding: Set by libavcodec. */ int delay; /* video only */ /** * picture width / height. * - encoding: MUST be set by user. * - decoding: May be set by the user before opening the decoder if known e.g. * from the container. Some decoders will require the dimensions * to be set by the caller. During decoding, the decoder may * overwrite those values as required. */ int width, height; /** * Bitstream width / height, may be different from width/height e.g. when * the decoded frame is cropped before being output or lowres is enabled. * - encoding: unused * - decoding: May be set by the user before opening the decoder if known * e.g. from the container. During decoding, the decoder may * overwrite those values as required. */ int coded_width, coded_height; #if FF_API_ASPECT_EXTENDED #define FF_ASPECT_EXTENDED 15 #endif /** * the number of pictures in a group of pictures, or 0 for intra_only * - encoding: Set by user. * - decoding: unused */ int gop_size; /** * Pixel format, see AV_PIX_FMT_xxx. * May be set by the demuxer if known from headers. * May be overridden by the decoder if it knows better. * - encoding: Set by user. * - decoding: Set by user if known, overridden by libavcodec if known */ enum AVPixelFormat pix_fmt; /** * Motion estimation algorithm used for video coding. * 1 (zero), 2 (full), 3 (log), 4 (phods), 5 (epzs), 6 (x1), 7 (hex), * 8 (umh), 9 (iter), 10 (tesa) [7, 8, 10 are x264 specific, 9 is snow specific] * - encoding: MUST be set by user. * - decoding: unused */ int me_method; /** * If non NULL, 'draw_horiz_band' is called by the libavcodec * decoder to draw a horizontal band. It improves cache usage. Not * all codecs can do that. You must check the codec capabilities * beforehand. * When multithreading is used, it may be called from multiple threads * at the same time; threads might draw different parts of the same AVFrame, * or multiple AVFrames, and there is no guarantee that slices will be drawn * in order. * The function is also used by hardware acceleration APIs. * It is called at least once during frame decoding to pass * the data needed for hardware render. * In that mode instead of pixel data, AVFrame points to * a structure specific to the acceleration API. The application * reads the structure and can change some fields to indicate progress * or mark state. * - encoding: unused * - decoding: Set by user. * @param height the height of the slice * @param y the y position of the slice * @param type 1->top field, 2->bottom field, 3->frame * @param offset offset into the AVFrame.data from which the slice should be read */ void (*draw_horiz_band)(struct AVCodecContext *s, const AVFrame *src, int offset[AV_NUM_DATA_POINTERS], int y, int type, int height); /** * callback to negotiate the pixelFormat * @param fmt is the list of formats which are supported by the codec, * it is terminated by -1 as 0 is a valid format, the formats are ordered by quality. * The first is always the native one. * @return the chosen format * - encoding: unused * - decoding: Set by user, if not set the native format will be chosen. */ enum AVPixelFormat (*get_format)(struct AVCodecContext *s, const enum AVPixelFormat * fmt); /** * maximum number of B-frames between non-B-frames * Note: The output will be delayed by max_b_frames+1 relative to the input. * - encoding: Set by user. * - decoding: unused */ int max_b_frames; /** * qscale factor between IP and B-frames * If > 0 then the last P-frame quantizer will be used (q= lastp_q*factor+offset). * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset). * - encoding: Set by user. * - decoding: unused */ float b_quant_factor; /** obsolete FIXME remove */ int rc_strategy; #define FF_RC_STRATEGY_XVID 1 int b_frame_strategy; /** * qscale offset between IP and B-frames * - encoding: Set by user. * - decoding: unused */ float b_quant_offset; /** * Size of the frame reordering buffer in the decoder. * For MPEG-2 it is 1 IPB or 0 low delay IP. * - encoding: Set by libavcodec. * - decoding: Set by libavcodec. */ int has_b_frames; /** * 0-> h263 quant 1-> mpeg quant * - encoding: Set by user. * - decoding: unused */ int mpeg_quant; /** * qscale factor between P and I-frames * If > 0 then the last p frame quantizer will be used (q= lastp_q*factor+offset). * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset). * - encoding: Set by user. * - decoding: unused */ float i_quant_factor; /** * qscale offset between P and I-frames * - encoding: Set by user. * - decoding: unused */ float i_quant_offset; /** * luminance masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float lumi_masking; /** * temporary complexity masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float temporal_cplx_masking; /** * spatial complexity masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float spatial_cplx_masking; /** * p block masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float p_masking; /** * darkness masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float dark_masking; /** * slice count * - encoding: Set by libavcodec. * - decoding: Set by user (or 0). */ int slice_count; /** * prediction method (needed for huffyuv) * - encoding: Set by user. * - decoding: unused */ int prediction_method; #define FF_PRED_LEFT 0 #define FF_PRED_PLANE 1 #define FF_PRED_MEDIAN 2 /** * slice offsets in the frame in bytes * - encoding: Set/allocated by libavcodec. * - decoding: Set/allocated by user (or NULL). */ int *slice_offset; /** * sample aspect ratio (0 if unknown) * That is the width of a pixel divided by the height of the pixel. * Numerator and denominator must be relatively prime and smaller than 256 for some video standards. * - encoding: Set by user. * - decoding: Set by libavcodec. */ AVRational sample_aspect_ratio; /** * motion estimation comparison function * - encoding: Set by user. * - decoding: unused */ int me_cmp; /** * subpixel motion estimation comparison function * - encoding: Set by user. * - decoding: unused */ int me_sub_cmp; /** * macroblock comparison function (not supported yet) * - encoding: Set by user. * - decoding: unused */ int mb_cmp; /** * interlaced DCT comparison function * - encoding: Set by user. * - decoding: unused */ int ildct_cmp; #define FF_CMP_SAD 0 #define FF_CMP_SSE 1 #define FF_CMP_SATD 2 #define FF_CMP_DCT 3 #define FF_CMP_PSNR 4 #define FF_CMP_BIT 5 #define FF_CMP_RD 6 #define FF_CMP_ZERO 7 #define FF_CMP_VSAD 8 #define FF_CMP_VSSE 9 #define FF_CMP_NSSE 10 #define FF_CMP_W53 11 #define FF_CMP_W97 12 #define FF_CMP_DCTMAX 13 #define FF_CMP_DCT264 14 #define FF_CMP_CHROMA 256 /** * ME diamond size & shape * - encoding: Set by user. * - decoding: unused */ int dia_size; /** * amount of previous MV predictors (2a+1 x 2a+1 square) * - encoding: Set by user. * - decoding: unused */ int last_predictor_count; /** * prepass for motion estimation * - encoding: Set by user. * - decoding: unused */ int pre_me; /** * motion estimation prepass comparison function * - encoding: Set by user. * - decoding: unused */ int me_pre_cmp; /** * ME prepass diamond size & shape * - encoding: Set by user. * - decoding: unused */ int pre_dia_size; /** * subpel ME quality * - encoding: Set by user. * - decoding: unused */ int me_subpel_quality; /** * DTG active format information (additional aspect ratio * information only used in DVB MPEG-2 transport streams) * 0 if not set. * * - encoding: unused * - decoding: Set by decoder. */ int dtg_active_format; #define FF_DTG_AFD_SAME 8 #define FF_DTG_AFD_4_3 9 #define FF_DTG_AFD_16_9 10 #define FF_DTG_AFD_14_9 11 #define FF_DTG_AFD_4_3_SP_14_9 13 #define FF_DTG_AFD_16_9_SP_14_9 14 #define FF_DTG_AFD_SP_4_3 15 /** * maximum motion estimation search range in subpel units * If 0 then no limit. * * - encoding: Set by user. * - decoding: unused */ int me_range; /** * intra quantizer bias * - encoding: Set by user. * - decoding: unused */ int intra_quant_bias; #define FF_DEFAULT_QUANT_BIAS 999999 /** * inter quantizer bias * - encoding: Set by user. * - decoding: unused */ int inter_quant_bias; /** * slice flags * - encoding: unused * - decoding: Set by user. */ int slice_flags; #define SLICE_FLAG_CODED_ORDER 0x0001 ///< draw_horiz_band() is called in coded order instead of display #define SLICE_FLAG_ALLOW_FIELD 0x0002 ///< allow draw_horiz_band() with field slices (MPEG2 field pics) #define SLICE_FLAG_ALLOW_PLANE 0x0004 ///< allow draw_horiz_band() with 1 component at a time (SVQ1) #if FF_API_XVMC /** * XVideo Motion Acceleration * - encoding: forbidden * - decoding: set by decoder * @deprecated XvMC doesn't need it anymore. */ attribute_deprecated int xvmc_acceleration; #endif /* FF_API_XVMC */ /** * macroblock decision mode * - encoding: Set by user. * - decoding: unused */ int mb_decision; #define FF_MB_DECISION_SIMPLE 0 ///< uses mb_cmp #define FF_MB_DECISION_BITS 1 ///< chooses the one which needs the fewest bits #define FF_MB_DECISION_RD 2 ///< rate distortion /** * custom intra quantization matrix * - encoding: Set by user, can be NULL. * - decoding: Set by libavcodec. */ uint16_t *intra_matrix; /** * custom inter quantization matrix * - encoding: Set by user, can be NULL. * - decoding: Set by libavcodec. */ uint16_t *inter_matrix; /** * scene change detection threshold * 0 is default, larger means fewer detected scene changes. * - encoding: Set by user. * - decoding: unused */ int scenechange_threshold; /** * noise reduction strength * - encoding: Set by user. * - decoding: unused */ int noise_reduction; /** * Motion estimation threshold below which no motion estimation is * performed, but instead the user specified motion vectors are used. * * - encoding: Set by user. * - decoding: unused */ int me_threshold; /** * Macroblock threshold below which the user specified macroblock types will be used. * - encoding: Set by user. * - decoding: unused */ int mb_threshold; /** * precision of the intra DC coefficient - 8 * - encoding: Set by user. * - decoding: unused */ int intra_dc_precision; /** * Number of macroblock rows at the top which are skipped. * - encoding: unused * - decoding: Set by user. */ int skip_top; /** * Number of macroblock rows at the bottom which are skipped. * - encoding: unused * - decoding: Set by user. */ int skip_bottom; /** * Border processing masking, raises the quantizer for mbs on the borders * of the picture. * - encoding: Set by user. * - decoding: unused */ float border_masking; /** * minimum MB lagrange multipler * - encoding: Set by user. * - decoding: unused */ int mb_lmin; /** * maximum MB lagrange multipler * - encoding: Set by user. * - decoding: unused */ int mb_lmax; /** * * - encoding: Set by user. * - decoding: unused */ int me_penalty_compensation; /** * * - encoding: Set by user. * - decoding: unused */ int bidir_refine; /** * * - encoding: Set by user. * - decoding: unused */ int brd_scale; /** * minimum GOP size * - encoding: Set by user. * - decoding: unused */ int keyint_min; /** * number of reference frames * - encoding: Set by user. * - decoding: Set by lavc. */ int refs; /** * chroma qp offset from luma * - encoding: Set by user. * - decoding: unused */ int chromaoffset; /** * Multiplied by qscale for each frame and added to scene_change_score. * - encoding: Set by user. * - decoding: unused */ int scenechange_factor; /** * * Note: Value depends upon the compare function used for fullpel ME. * - encoding: Set by user. * - decoding: unused */ int mv0_threshold; /** * Adjust sensitivity of b_frame_strategy 1. * - encoding: Set by user. * - decoding: unused */ int b_sensitivity; /** * Chromaticity coordinates of the source primaries. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorPrimaries color_primaries; /** * Color Transfer Characteristic. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorTransferCharacteristic color_trc; /** * YUV colorspace type. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorSpace colorspace; /** * MPEG vs JPEG YUV range. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorRange color_range; /** * This defines the location of chroma samples. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVChromaLocation chroma_sample_location; /** * Number of slices. * Indicates number of picture subdivisions. Used for parallelized * decoding. * - encoding: Set by user * - decoding: unused */ int slices; /** Field order * - encoding: set by libavcodec * - decoding: Set by user. */ enum AVFieldOrder field_order; /* audio only */ int sample_rate; ///< samples per second int channels; ///< number of audio channels /** * audio sample format * - encoding: Set by user. * - decoding: Set by libavcodec. */ enum AVSampleFormat sample_fmt; ///< sample format /* The following data should not be initialized. */ /** * Number of samples per channel in an audio frame. * * - encoding: set by libavcodec in avcodec_open2(). Each submitted frame * except the last must contain exactly frame_size samples per channel. * May be 0 when the codec has CODEC_CAP_VARIABLE_FRAME_SIZE set, then the * frame size is not restricted. * - decoding: may be set by some decoders to indicate constant frame size */ int frame_size; /** * Frame counter, set by libavcodec. * * - decoding: total number of frames returned from the decoder so far. * - encoding: total number of frames passed to the encoder so far. * * @note the counter is not incremented if encoding/decoding resulted in * an error. */ int frame_number; /** * number of bytes per packet if constant and known or 0 * Used by some WAV based audio codecs. */ int block_align; /** * Audio cutoff bandwidth (0 means "automatic") * - encoding: Set by user. * - decoding: unused */ int cutoff; #if FF_API_REQUEST_CHANNELS /** * Decoder should decode to this many channels if it can (0 for default) * - encoding: unused * - decoding: Set by user. * @deprecated Deprecated in favor of request_channel_layout. */ attribute_deprecated int request_channels; #endif /** * Audio channel layout. * - encoding: set by user. * - decoding: set by user, may be overwritten by libavcodec. */ uint64_t channel_layout; /** * Request decoder to use this channel layout if it can (0 for default) * - encoding: unused * - decoding: Set by user. */ uint64_t request_channel_layout; /** * Type of service that the audio stream conveys. * - encoding: Set by user. * - decoding: Set by libavcodec. */ enum AVAudioServiceType audio_service_type; /** * desired sample format * - encoding: Not used. * - decoding: Set by user. * Decoder will decode to this format if it can. */ enum AVSampleFormat request_sample_fmt; #if FF_API_GET_BUFFER /** * Called at the beginning of each frame to get a buffer for it. * * The function will set AVFrame.data[], AVFrame.linesize[]. * AVFrame.extended_data[] must also be set, but it should be the same as * AVFrame.data[] except for planar audio with more channels than can fit * in AVFrame.data[]. In that case, AVFrame.data[] shall still contain as * many data pointers as it can hold. * * if CODEC_CAP_DR1 is not set then get_buffer() must call * avcodec_default_get_buffer() instead of providing buffers allocated by * some other means. * * AVFrame.data[] should be 32- or 16-byte-aligned unless the CPU doesn't * need it. avcodec_default_get_buffer() aligns the output buffer properly, * but if get_buffer() is overridden then alignment considerations should * be taken into account. * * @see avcodec_default_get_buffer() * * Video: * * If pic.reference is set then the frame will be read later by libavcodec. * avcodec_align_dimensions2() should be used to find the required width and * height, as they normally need to be rounded up to the next multiple of 16. * * If frame multithreading is used and thread_safe_callbacks is set, * it may be called from a different thread, but not from more than one at * once. Does not need to be reentrant. * * @see release_buffer(), reget_buffer() * @see avcodec_align_dimensions2() * * Audio: * * Decoders request a buffer of a particular size by setting * AVFrame.nb_samples prior to calling get_buffer(). The decoder may, * however, utilize only part of the buffer by setting AVFrame.nb_samples * to a smaller value in the output frame. * * Decoders cannot use the buffer after returning from * avcodec_decode_audio4(), so they will not call release_buffer(), as it * is assumed to be released immediately upon return. In some rare cases, * a decoder may need to call get_buffer() more than once in a single * call to avcodec_decode_audio4(). In that case, when get_buffer() is * called again after it has already been called once, the previously * acquired buffer is assumed to be released at that time and may not be * reused by the decoder. * * As a convenience, av_samples_get_buffer_size() and * av_samples_fill_arrays() in libavutil may be used by custom get_buffer() * functions to find the required data size and to fill data pointers and * linesize. In AVFrame.linesize, only linesize[0] may be set for audio * since all planes must be the same size. * * @see av_samples_get_buffer_size(), av_samples_fill_arrays() * * - encoding: unused * - decoding: Set by libavcodec, user can override. * * @deprecated use get_buffer2() */ attribute_deprecated int (*get_buffer)(struct AVCodecContext *c, AVFrame *pic); /** * Called to release buffers which were allocated with get_buffer. * A released buffer can be reused in get_buffer(). * pic.data[*] must be set to NULL. * May be called from a different thread if frame multithreading is used, * but not by more than one thread at once, so does not need to be reentrant. * - encoding: unused * - decoding: Set by libavcodec, user can override. * * @deprecated custom freeing callbacks should be set from get_buffer2() */ attribute_deprecated void (*release_buffer)(struct AVCodecContext *c, AVFrame *pic); /** * Called at the beginning of a frame to get cr buffer for it. * Buffer type (size, hints) must be the same. libavcodec won't check it. * libavcodec will pass previous buffer in pic, function should return * same buffer or new buffer with old frame "painted" into it. * If pic.data[0] == NULL must behave like get_buffer(). * if CODEC_CAP_DR1 is not set then reget_buffer() must call * avcodec_default_reget_buffer() instead of providing buffers allocated by * some other means. * - encoding: unused * - decoding: Set by libavcodec, user can override. */ attribute_deprecated int (*reget_buffer)(struct AVCodecContext *c, AVFrame *pic); #endif /** * This callback is called at the beginning of each frame to get data * buffer(s) for it. There may be one contiguous buffer for all the data or * there may be a buffer per each data plane or anything in between. What * this means is, you may set however many entries in buf[] you feel necessary. * Each buffer must be reference-counted using the AVBuffer API (see description * of buf[] below). * * The following fields will be set in the frame before this callback is * called: * - format * - width, height (video only) * - sample_rate, channel_layout, nb_samples (audio only) * Their values may differ from the corresponding values in * AVCodecContext. This callback must use the frame values, not the codec * context values, to calculate the required buffer size. * * This callback must fill the following fields in the frame: * - data[] * - linesize[] * - extended_data: * * if the data is planar audio with more than 8 channels, then this * callback must allocate and fill extended_data to contain all pointers * to all data planes. data[] must hold as many pointers as it can. * extended_data must be allocated with av_malloc() and will be freed in * av_frame_unref(). * * otherwise exended_data must point to data * - buf[] must contain one or more pointers to AVBufferRef structures. Each of * the frame's data and extended_data pointers must be contained in these. That * is, one AVBufferRef for each allocated chunk of memory, not necessarily one * AVBufferRef per data[] entry. See: av_buffer_create(), av_buffer_alloc(), * and av_buffer_ref(). * - extended_buf and nb_extended_buf must be allocated with av_malloc() by * this callback and filled with the extra buffers if there are more * buffers than buf[] can hold. extended_buf will be freed in * av_frame_unref(). * * If CODEC_CAP_DR1 is not set then get_buffer2() must call * avcodec_default_get_buffer2() instead of providing buffers allocated by * some other means. * * Each data plane must be aligned to the maximum required by the target * CPU. * * @see avcodec_default_get_buffer2() * * Video: * * If AV_GET_BUFFER_FLAG_REF is set in flags then the frame may be reused * (read and/or written to if it is writable) later by libavcodec. * * avcodec_align_dimensions2() should be used to find the required width and * height, as they normally need to be rounded up to the next multiple of 16. * * Some decoders do not support linesizes changing between frames. * * If frame multithreading is used and thread_safe_callbacks is set, * this callback may be called from a different thread, but not from more * than one at once. Does not need to be reentrant. * * @see avcodec_align_dimensions2() * * Audio: * * Decoders request a buffer of a particular size by setting * AVFrame.nb_samples prior to calling get_buffer2(). The decoder may, * however, utilize only part of the buffer by setting AVFrame.nb_samples * to a smaller value in the output frame. * * As a convenience, av_samples_get_buffer_size() and * av_samples_fill_arrays() in libavutil may be used by custom get_buffer2() * functions to find the required data size and to fill data pointers and * linesize. In AVFrame.linesize, only linesize[0] may be set for audio * since all planes must be the same size. * * @see av_samples_get_buffer_size(), av_samples_fill_arrays() * * - encoding: unused * - decoding: Set by libavcodec, user can override. */ int (*get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags); /** * If non-zero, the decoded audio and video frames returned from * avcodec_decode_video2() and avcodec_decode_audio4() are reference-counted * and are valid indefinitely. The caller must free them with * av_frame_unref() when they are not needed anymore. * Otherwise, the decoded frames must not be freed by the caller and are * only valid until the next decode call. * * - encoding: unused * - decoding: set by the caller before avcodec_open2(). */ int refcounted_frames; /* - encoding parameters */ float qcompress; ///< amount of qscale change between easy & hard scenes (0.0-1.0) float qblur; ///< amount of qscale smoothing over time (0.0-1.0) /** * minimum quantizer * - encoding: Set by user. * - decoding: unused */ int qmin; /** * maximum quantizer * - encoding: Set by user. * - decoding: unused */ int qmax; /** * maximum quantizer difference between frames * - encoding: Set by user. * - decoding: unused */ int max_qdiff; /** * ratecontrol qmin qmax limiting method * 0-> clipping, 1-> use a nice continuous function to limit qscale wthin qmin/qmax. * - encoding: Set by user. * - decoding: unused */ float rc_qsquish; float rc_qmod_amp; int rc_qmod_freq; /** * decoder bitstream buffer size * - encoding: Set by user. * - decoding: unused */ int rc_buffer_size; /** * ratecontrol override, see RcOverride * - encoding: Allocated/set/freed by user. * - decoding: unused */ int rc_override_count; RcOverride *rc_override; /** * rate control equation * - encoding: Set by user * - decoding: unused */ const char *rc_eq; /** * maximum bitrate * - encoding: Set by user. * - decoding: unused */ int rc_max_rate; /** * minimum bitrate * - encoding: Set by user. * - decoding: unused */ int rc_min_rate; float rc_buffer_aggressivity; /** * initial complexity for pass1 ratecontrol * - encoding: Set by user. * - decoding: unused */ float rc_initial_cplx; /** * Ratecontrol attempt to use, at maximum, of what can be used without an underflow. * - encoding: Set by user. * - decoding: unused. */ float rc_max_available_vbv_use; /** * Ratecontrol attempt to use, at least, times the amount needed to prevent a vbv overflow. * - encoding: Set by user. * - decoding: unused. */ float rc_min_vbv_overflow_use; /** * Number of bits which should be loaded into the rc buffer before decoding starts. * - encoding: Set by user. * - decoding: unused */ int rc_initial_buffer_occupancy; #define FF_CODER_TYPE_VLC 0 #define FF_CODER_TYPE_AC 1 #define FF_CODER_TYPE_RAW 2 #define FF_CODER_TYPE_RLE 3 #define FF_CODER_TYPE_DEFLATE 4 /** * coder type * - encoding: Set by user. * - decoding: unused */ int coder_type; /** * context model * - encoding: Set by user. * - decoding: unused */ int context_model; /** * minimum Lagrange multipler * - encoding: Set by user. * - decoding: unused */ int lmin; /** * maximum Lagrange multipler * - encoding: Set by user. * - decoding: unused */ int lmax; /** * frame skip threshold * - encoding: Set by user. * - decoding: unused */ int frame_skip_threshold; /** * frame skip factor * - encoding: Set by user. * - decoding: unused */ int frame_skip_factor; /** * frame skip exponent * - encoding: Set by user. * - decoding: unused */ int frame_skip_exp; /** * frame skip comparison function * - encoding: Set by user. * - decoding: unused */ int frame_skip_cmp; /** * trellis RD quantization * - encoding: Set by user. * - decoding: unused */ int trellis; /** * - encoding: Set by user. * - decoding: unused */ int min_prediction_order; /** * - encoding: Set by user. * - decoding: unused */ int max_prediction_order; /** * GOP timecode frame start number * - encoding: Set by user, in non drop frame format * - decoding: Set by libavcodec (timecode in the 25 bits format, -1 if unset) */ int64_t timecode_frame_start; /* The RTP callback: This function is called */ /* every time the encoder has a packet to send. */ /* It depends on the encoder if the data starts */ /* with a Start Code (it should). H.263 does. */ /* mb_nb contains the number of macroblocks */ /* encoded in the RTP payload. */ void (*rtp_callback)(struct AVCodecContext *avctx, void *data, int size, int mb_nb); int rtp_payload_size; /* The size of the RTP payload: the coder will */ /* do its best to deliver a chunk with size */ /* below rtp_payload_size, the chunk will start */ /* with a start code on some codecs like H.263. */ /* This doesn't take account of any particular */ /* headers inside the transmitted RTP payload. */ /* statistics, used for 2-pass encoding */ int mv_bits; int header_bits; int i_tex_bits; int p_tex_bits; int i_count; int p_count; int skip_count; int misc_bits; /** * number of bits used for the previously encoded frame * - encoding: Set by libavcodec. * - decoding: unused */ int frame_bits; /** * pass1 encoding statistics output buffer * - encoding: Set by libavcodec. * - decoding: unused */ char *stats_out; /** * pass2 encoding statistics input buffer * Concatenated stuff from stats_out of pass1 should be placed here. * - encoding: Allocated/set/freed by user. * - decoding: unused */ char *stats_in; /** * Work around bugs in encoders which sometimes cannot be detected automatically. * - encoding: Set by user * - decoding: Set by user */ int workaround_bugs; #define FF_BUG_AUTODETECT 1 ///< autodetection #if FF_API_OLD_MSMPEG4 #define FF_BUG_OLD_MSMPEG4 2 #endif #define FF_BUG_XVID_ILACE 4 #define FF_BUG_UMP4 8 #define FF_BUG_NO_PADDING 16 #define FF_BUG_AMV 32 #if FF_API_AC_VLC #define FF_BUG_AC_VLC 0 ///< Will be removed, libavcodec can now handle these non-compliant files by default. #endif #define FF_BUG_QPEL_CHROMA 64 #define FF_BUG_STD_QPEL 128 #define FF_BUG_QPEL_CHROMA2 256 #define FF_BUG_DIRECT_BLOCKSIZE 512 #define FF_BUG_EDGE 1024 #define FF_BUG_HPEL_CHROMA 2048 #define FF_BUG_DC_CLIP 4096 #define FF_BUG_MS 8192 ///< Work around various bugs in Microsoft's broken decoders. #define FF_BUG_TRUNCATED 16384 /** * strictly follow the standard (MPEG4, ...). * - encoding: Set by user. * - decoding: Set by user. * Setting this to STRICT or higher means the encoder and decoder will * generally do stupid things, whereas setting it to unofficial or lower * will mean the encoder might produce output that is not supported by all * spec-compliant decoders. Decoders don't differentiate between normal, * unofficial and experimental (that is, they always try to decode things * when they can) unless they are explicitly asked to behave stupidly * (=strictly conform to the specs) */ int strict_std_compliance; #define FF_COMPLIANCE_VERY_STRICT 2 ///< Strictly conform to an older more strict version of the spec or reference software. #define FF_COMPLIANCE_STRICT 1 ///< Strictly conform to all the things in the spec no matter what consequences. #define FF_COMPLIANCE_NORMAL 0 #define FF_COMPLIANCE_UNOFFICIAL -1 ///< Allow unofficial extensions #define FF_COMPLIANCE_EXPERIMENTAL -2 ///< Allow nonstandardized experimental things. /** * error concealment flags * - encoding: unused * - decoding: Set by user. */ int error_concealment; #define FF_EC_GUESS_MVS 1 #define FF_EC_DEBLOCK 2 /** * debug * - encoding: Set by user. * - decoding: Set by user. */ int debug; #define FF_DEBUG_PICT_INFO 1 #define FF_DEBUG_RC 2 #define FF_DEBUG_BITSTREAM 4 #define FF_DEBUG_MB_TYPE 8 #define FF_DEBUG_QP 16 #if FF_API_DEBUG_MV /** * @deprecated this option does nothing */ #define FF_DEBUG_MV 32 #endif #define FF_DEBUG_DCT_COEFF 0x00000040 #define FF_DEBUG_SKIP 0x00000080 #define FF_DEBUG_STARTCODE 0x00000100 #define FF_DEBUG_PTS 0x00000200 #define FF_DEBUG_ER 0x00000400 #define FF_DEBUG_MMCO 0x00000800 #define FF_DEBUG_BUGS 0x00001000 #if FF_API_DEBUG_MV #define FF_DEBUG_VIS_QP 0x00002000 ///< only access through AVOptions from outside libavcodec #define FF_DEBUG_VIS_MB_TYPE 0x00004000 ///< only access through AVOptions from outside libavcodec #endif #define FF_DEBUG_BUFFERS 0x00008000 #define FF_DEBUG_THREADS 0x00010000 #if FF_API_DEBUG_MV /** * debug * Code outside libavcodec should access this field using AVOptions * - encoding: Set by user. * - decoding: Set by user. */ int debug_mv; #define FF_DEBUG_VIS_MV_P_FOR 0x00000001 //visualize forward predicted MVs of P frames #define FF_DEBUG_VIS_MV_B_FOR 0x00000002 //visualize forward predicted MVs of B frames #define FF_DEBUG_VIS_MV_B_BACK 0x00000004 //visualize backward predicted MVs of B frames #endif /** * Error recognition; may misdetect some more or less valid parts as errors. * - encoding: unused * - decoding: Set by user. */ int err_recognition; /** * Verify checksums embedded in the bitstream (could be of either encoded or * decoded data, depending on the codec) and print an error message on mismatch. * If AV_EF_EXPLODE is also set, a mismatching checksum will result in the * decoder returning an error. */ #define AV_EF_CRCCHECK (1<<0) #define AV_EF_BITSTREAM (1<<1) ///< detect bitstream specification deviations #define AV_EF_BUFFER (1<<2) ///< detect improper bitstream length #define AV_EF_EXPLODE (1<<3) ///< abort decoding on minor error detection #define AV_EF_CAREFUL (1<<16) ///< consider things that violate the spec, are fast to calculate and have not been seen in the wild as errors #define AV_EF_COMPLIANT (1<<17) ///< consider all spec non compliancies as errors #define AV_EF_AGGRESSIVE (1<<18) ///< consider things that a sane encoder should not do as an error /** * opaque 64bit number (generally a PTS) that will be reordered and * output in AVFrame.reordered_opaque * @deprecated in favor of pkt_pts * - encoding: unused * - decoding: Set by user. */ int64_t reordered_opaque; /** * Hardware accelerator in use * - encoding: unused. * - decoding: Set by libavcodec */ struct AVHWAccel *hwaccel; /** * Hardware accelerator context. * For some hardware accelerators, a global context needs to be * provided by the user. In that case, this holds display-dependent * data FFmpeg cannot instantiate itself. Please refer to the * FFmpeg HW accelerator documentation to know how to fill this * is. e.g. for VA API, this is a struct vaapi_context. * - encoding: unused * - decoding: Set by user */ void *hwaccel_context; /** * error * - encoding: Set by libavcodec if flags&CODEC_FLAG_PSNR. * - decoding: unused */ uint64_t error[AV_NUM_DATA_POINTERS]; /** * DCT algorithm, see FF_DCT_* below * - encoding: Set by user. * - decoding: unused */ int dct_algo; #define FF_DCT_AUTO 0 #define FF_DCT_FASTINT 1 #define FF_DCT_INT 2 #define FF_DCT_MMX 3 #define FF_DCT_ALTIVEC 5 #define FF_DCT_FAAN 6 /** * IDCT algorithm, see FF_IDCT_* below. * - encoding: Set by user. * - decoding: Set by user. */ int idct_algo; #define FF_IDCT_AUTO 0 #define FF_IDCT_INT 1 #define FF_IDCT_SIMPLE 2 #define FF_IDCT_SIMPLEMMX 3 #define FF_IDCT_ARM 7 #define FF_IDCT_ALTIVEC 8 #define FF_IDCT_SH4 9 #define FF_IDCT_SIMPLEARM 10 #define FF_IDCT_IPP 13 #define FF_IDCT_XVIDMMX 14 #define FF_IDCT_SIMPLEARMV5TE 16 #define FF_IDCT_SIMPLEARMV6 17 #define FF_IDCT_SIMPLEVIS 18 #define FF_IDCT_FAAN 20 #define FF_IDCT_SIMPLENEON 22 #if FF_API_ARCH_ALPHA #define FF_IDCT_SIMPLEALPHA 23 #endif /** * bits per sample/pixel from the demuxer (needed for huffyuv). * - encoding: Set by libavcodec. * - decoding: Set by user. */ int bits_per_coded_sample; /** * Bits per sample/pixel of internal libavcodec pixel/sample format. * - encoding: set by user. * - decoding: set by libavcodec. */ int bits_per_raw_sample; #if FF_API_LOWRES /** * low resolution decoding, 1-> 1/2 size, 2->1/4 size * - encoding: unused * - decoding: Set by user. * Code outside libavcodec should access this field using: * av_codec_{get,set}_lowres(avctx) */ int lowres; #endif /** * the picture in the bitstream * - encoding: Set by libavcodec. * - decoding: unused */ AVFrame *coded_frame; /** * thread count * is used to decide how many independent tasks should be passed to execute() * - encoding: Set by user. * - decoding: Set by user. */ int thread_count; /** * Which multithreading methods to use. * Use of FF_THREAD_FRAME will increase decoding delay by one frame per thread, * so clients which cannot provide future frames should not use it. * * - encoding: Set by user, otherwise the default is used. * - decoding: Set by user, otherwise the default is used. */ int thread_type; #define FF_THREAD_FRAME 1 ///< Decode more than one frame at once #define FF_THREAD_SLICE 2 ///< Decode more than one part of a single frame at once /** * Which multithreading methods are in use by the codec. * - encoding: Set by libavcodec. * - decoding: Set by libavcodec. */ int active_thread_type; /** * Set by the client if its custom get_buffer() callback can be called * synchronously from another thread, which allows faster multithreaded decoding. * draw_horiz_band() will be called from other threads regardless of this setting. * Ignored if the default get_buffer() is used. * - encoding: Set by user. * - decoding: Set by user. */ int thread_safe_callbacks; /** * The codec may call this to execute several independent things. * It will return only after finishing all tasks. * The user may replace this with some multithreaded implementation, * the default implementation will execute the parts serially. * @param count the number of things to execute * - encoding: Set by libavcodec, user can override. * - decoding: Set by libavcodec, user can override. */ int (*execute)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg), void *arg2, int *ret, int count, int size); /** * The codec may call this to execute several independent things. * It will return only after finishing all tasks. * The user may replace this with some multithreaded implementation, * the default implementation will execute the parts serially. * Also see avcodec_thread_init and e.g. the --enable-pthread configure option. * @param c context passed also to func * @param count the number of things to execute * @param arg2 argument passed unchanged to func * @param ret return values of executed functions, must have space for "count" values. May be NULL. * @param func function that will be called count times, with jobnr from 0 to count-1. * threadnr will be in the range 0 to c->thread_count-1 < MAX_THREADS and so that no * two instances of func executing at the same time will have the same threadnr. * @return always 0 currently, but code should handle a future improvement where when any call to func * returns < 0 no further calls to func may be done and < 0 is returned. * - encoding: Set by libavcodec, user can override. * - decoding: Set by libavcodec, user can override. */ int (*execute2)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg, int jobnr, int threadnr), void *arg2, int *ret, int count); #if FF_API_THREAD_OPAQUE /** * @deprecated this field should not be used from outside of lavc */ attribute_deprecated void *thread_opaque; #endif /** * noise vs. sse weight for the nsse comparsion function * - encoding: Set by user. * - decoding: unused */ int nsse_weight; /** * profile * - encoding: Set by user. * - decoding: Set by libavcodec. */ int profile; #define FF_PROFILE_UNKNOWN -99 #define FF_PROFILE_RESERVED -100 #define FF_PROFILE_AAC_MAIN 0 #define FF_PROFILE_AAC_LOW 1 #define FF_PROFILE_AAC_SSR 2 #define FF_PROFILE_AAC_LTP 3 #define FF_PROFILE_AAC_HE 4 #define FF_PROFILE_AAC_HE_V2 28 #define FF_PROFILE_AAC_LD 22 #define FF_PROFILE_AAC_ELD 38 #define FF_PROFILE_MPEG2_AAC_LOW 128 #define FF_PROFILE_MPEG2_AAC_HE 131 #define FF_PROFILE_DTS 20 #define FF_PROFILE_DTS_ES 30 #define FF_PROFILE_DTS_96_24 40 #define FF_PROFILE_DTS_HD_HRA 50 #define FF_PROFILE_DTS_HD_MA 60 #define FF_PROFILE_MPEG2_422 0 #define FF_PROFILE_MPEG2_HIGH 1 #define FF_PROFILE_MPEG2_SS 2 #define FF_PROFILE_MPEG2_SNR_SCALABLE 3 #define FF_PROFILE_MPEG2_MAIN 4 #define FF_PROFILE_MPEG2_SIMPLE 5 #define FF_PROFILE_H264_CONSTRAINED (1<<9) // 8+1; constraint_set1_flag #define FF_PROFILE_H264_INTRA (1<<11) // 8+3; constraint_set3_flag #define FF_PROFILE_H264_BASELINE 66 #define FF_PROFILE_H264_CONSTRAINED_BASELINE (66|FF_PROFILE_H264_CONSTRAINED) #define FF_PROFILE_H264_MAIN 77 #define FF_PROFILE_H264_EXTENDED 88 #define FF_PROFILE_H264_HIGH 100 #define FF_PROFILE_H264_HIGH_10 110 #define FF_PROFILE_H264_HIGH_10_INTRA (110|FF_PROFILE_H264_INTRA) #define FF_PROFILE_H264_HIGH_422 122 #define FF_PROFILE_H264_HIGH_422_INTRA (122|FF_PROFILE_H264_INTRA) #define FF_PROFILE_H264_HIGH_444 144 #define FF_PROFILE_H264_HIGH_444_PREDICTIVE 244 #define FF_PROFILE_H264_HIGH_444_INTRA (244|FF_PROFILE_H264_INTRA) #define FF_PROFILE_H264_CAVLC_444 44 #define FF_PROFILE_VC1_SIMPLE 0 #define FF_PROFILE_VC1_MAIN 1 #define FF_PROFILE_VC1_COMPLEX 2 #define FF_PROFILE_VC1_ADVANCED 3 #define FF_PROFILE_MPEG4_SIMPLE 0 #define FF_PROFILE_MPEG4_SIMPLE_SCALABLE 1 #define FF_PROFILE_MPEG4_CORE 2 #define FF_PROFILE_MPEG4_MAIN 3 #define FF_PROFILE_MPEG4_N_BIT 4 #define FF_PROFILE_MPEG4_SCALABLE_TEXTURE 5 #define FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION 6 #define FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE 7 #define FF_PROFILE_MPEG4_HYBRID 8 #define FF_PROFILE_MPEG4_ADVANCED_REAL_TIME 9 #define FF_PROFILE_MPEG4_CORE_SCALABLE 10 #define FF_PROFILE_MPEG4_ADVANCED_CODING 11 #define FF_PROFILE_MPEG4_ADVANCED_CORE 12 #define FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE 13 #define FF_PROFILE_MPEG4_SIMPLE_STUDIO 14 #define FF_PROFILE_MPEG4_ADVANCED_SIMPLE 15 #define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0 0 #define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1 1 #define FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION 2 #define FF_PROFILE_JPEG2000_DCINEMA_2K 3 #define FF_PROFILE_JPEG2000_DCINEMA_4K 4 #define FF_PROFILE_HEVC_MAIN 1 #define FF_PROFILE_HEVC_MAIN_10 2 #define FF_PROFILE_HEVC_MAIN_STILL_PICTURE 3 /** * level * - encoding: Set by user. * - decoding: Set by libavcodec. */ int level; #define FF_LEVEL_UNKNOWN -99 /** * Skip loop filtering for selected frames. * - encoding: unused * - decoding: Set by user. */ enum AVDiscard skip_loop_filter; /** * Skip IDCT/dequantization for selected frames. * - encoding: unused * - decoding: Set by user. */ enum AVDiscard skip_idct; /** * Skip decoding for selected frames. * - encoding: unused * - decoding: Set by user. */ enum AVDiscard skip_frame; /** * Header containing style information for text subtitles. * For SUBTITLE_ASS subtitle type, it should contain the whole ASS * [Script Info] and [V4+ Styles] section, plus the [Events] line and * the Format line following. It shouldn't include any Dialogue line. * - encoding: Set/allocated/freed by user (before avcodec_open2()) * - decoding: Set/allocated/freed by libavcodec (by avcodec_open2()) */ uint8_t *subtitle_header; int subtitle_header_size; #if FF_API_ERROR_RATE /** * @deprecated use the 'error_rate' private AVOption of the mpegvideo * encoders */ attribute_deprecated int error_rate; #endif #if FF_API_CODEC_PKT /** * @deprecated this field is not supposed to be accessed from outside lavc */ attribute_deprecated AVPacket *pkt; #endif /** * VBV delay coded in the last frame (in periods of a 27 MHz clock). * Used for compliant TS muxing. * - encoding: Set by libavcodec. * - decoding: unused. */ uint64_t vbv_delay; /** * Timebase in which pkt_dts/pts and AVPacket.dts/pts are. * Code outside libavcodec should access this field using: * av_codec_{get,set}_pkt_timebase(avctx) * - encoding unused. * - decoding set by user. */ AVRational pkt_timebase; /** * AVCodecDescriptor * Code outside libavcodec should access this field using: * av_codec_{get,set}_codec_descriptor(avctx) * - encoding: unused. * - decoding: set by libavcodec. */ const AVCodecDescriptor *codec_descriptor; #if !FF_API_LOWRES /** * low resolution decoding, 1-> 1/2 size, 2->1/4 size * - encoding: unused * - decoding: Set by user. * Code outside libavcodec should access this field using: * av_codec_{get,set}_lowres(avctx) */ int lowres; #endif /** * Current statistics for PTS correction. * - decoding: maintained and used by libavcodec, not intended to be used by user apps * - encoding: unused */ int64_t pts_correction_num_faulty_pts; /// Number of incorrect PTS values so far int64_t pts_correction_num_faulty_dts; /// Number of incorrect DTS values so far int64_t pts_correction_last_pts; /// PTS of the last frame int64_t pts_correction_last_dts; /// DTS of the last frame /** * Character encoding of the input subtitles file. * - decoding: set by user * - encoding: unused */ char *sub_charenc; /** * Subtitles character encoding mode. Formats or codecs might be adjusting * this setting (if they are doing the conversion themselves for instance). * - decoding: set by libavcodec * - encoding: unused */ int sub_charenc_mode; #define FF_SUB_CHARENC_MODE_DO_NOTHING -1 ///< do nothing (demuxer outputs a stream supposed to be already in UTF-8, or the codec is bitmap for instance) #define FF_SUB_CHARENC_MODE_AUTOMATIC 0 ///< libavcodec will select the mode itself #define FF_SUB_CHARENC_MODE_PRE_DECODER 1 ///< the AVPacket data needs to be recoded to UTF-8 before being fed to the decoder, requires iconv /** * Skip processing alpha if supported by codec. * Note that if the format uses pre-multiplied alpha (common with VP6, * and recommended due to better video quality/compression) * the image will look as if alpha-blended onto a black background. * However for formats that do not use pre-multiplied alpha * there might be serious artefacts (though e.g. libswscale currently * assumes pre-multiplied alpha anyway). * Code outside libavcodec should access this field using AVOptions * * - decoding: set by user * - encoding: unused */ int skip_alpha; /** * Number of samples to skip after a discontinuity * - decoding: unused * - encoding: set by libavcodec */ int seek_preroll; #if !FF_API_DEBUG_MV /** * debug motion vectors * Code outside libavcodec should access this field using AVOptions * - encoding: Set by user. * - decoding: Set by user. */ int debug_mv; #define FF_DEBUG_VIS_MV_P_FOR 0x00000001 //visualize forward predicted MVs of P frames #define FF_DEBUG_VIS_MV_B_FOR 0x00000002 //visualize forward predicted MVs of B frames #define FF_DEBUG_VIS_MV_B_BACK 0x00000004 //visualize backward predicted MVs of B frames #endif /** * custom intra quantization matrix * Code outside libavcodec should access this field using av_codec_g/set_chroma_intra_matrix() * - encoding: Set by user, can be NULL. * - decoding: unused. */ uint16_t *chroma_intra_matrix; } AVCodecContext; AVRational av_codec_get_pkt_timebase (const AVCodecContext *avctx); void av_codec_set_pkt_timebase (AVCodecContext *avctx, AVRational val); const AVCodecDescriptor *av_codec_get_codec_descriptor(const AVCodecContext *avctx); void av_codec_set_codec_descriptor(AVCodecContext *avctx, const AVCodecDescriptor *desc); int av_codec_get_lowres(const AVCodecContext *avctx); void av_codec_set_lowres(AVCodecContext *avctx, int val); int av_codec_get_seek_preroll(const AVCodecContext *avctx); void av_codec_set_seek_preroll(AVCodecContext *avctx, int val); uint16_t *av_codec_get_chroma_intra_matrix(const AVCodecContext *avctx); void av_codec_set_chroma_intra_matrix(AVCodecContext *avctx, uint16_t *val); /** * AVProfile. */ typedef struct AVProfile { int profile; const char *name; ///< short name for the profile } AVProfile; typedef struct AVCodecDefault AVCodecDefault; struct AVSubtitle; /** * AVCodec. */ typedef struct AVCodec { /** * Name of the codec implementation. * The name is globally unique among encoders and among decoders (but an * encoder and a decoder can share the same name). * This is the primary way to find a codec from the user perspective. */ const char *name; /** * Descriptive name for the codec, meant to be more human readable than name. * You should use the NULL_IF_CONFIG_SMALL() macro to define it. */ const char *long_name; enum AVMediaType type; enum AVCodecID id; /** * Codec capabilities. * see CODEC_CAP_* */ int capabilities; const AVRational *supported_framerates; ///< array of supported framerates, or NULL if any, array is terminated by {0,0} const enum AVPixelFormat *pix_fmts; ///< array of supported pixel formats, or NULL if unknown, array is terminated by -1 const int *supported_samplerates; ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0 const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1 const uint64_t *channel_layouts; ///< array of support channel layouts, or NULL if unknown. array is terminated by 0 #if FF_API_LOWRES uint8_t max_lowres; ///< maximum value for lowres supported by the decoder, no direct access, use av_codec_get_max_lowres() #endif const AVClass *priv_class; ///< AVClass for the private context const AVProfile *profiles; ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN} /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavcodec and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ int priv_data_size; struct AVCodec *next; /** * @name Frame-level threading support functions * @{ */ /** * If defined, called on thread contexts when they are created. * If the codec allocates writable tables in init(), re-allocate them here. * priv_data will be set to a copy of the original. */ int (*init_thread_copy)(AVCodecContext *); /** * Copy necessary context variables from a previous thread context to the current one. * If not defined, the next thread will start automatically; otherwise, the codec * must call ff_thread_finish_setup(). * * dst and src will (rarely) point to the same context, in which case memcpy should be skipped. */ int (*update_thread_context)(AVCodecContext *dst, const AVCodecContext *src); /** @} */ /** * Private codec-specific defaults. */ const AVCodecDefault *defaults; /** * Initialize codec static data, called from avcodec_register(). */ void (*init_static_data)(struct AVCodec *codec); int (*init)(AVCodecContext *); int (*encode_sub)(AVCodecContext *, uint8_t *buf, int buf_size, const struct AVSubtitle *sub); /** * Encode data to an AVPacket. * * @param avctx codec context * @param avpkt output AVPacket (may contain a user-provided buffer) * @param[in] frame AVFrame containing the raw data to be encoded * @param[out] got_packet_ptr encoder sets to 0 or 1 to indicate that a * non-empty packet was returned in avpkt. * @return 0 on success, negative error code on failure */ int (*encode2)(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr); int (*decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt); int (*close)(AVCodecContext *); /** * Flush buffers. * Will be called when seeking */ void (*flush)(AVCodecContext *); } AVCodec; int av_codec_get_max_lowres(const AVCodec *codec); struct MpegEncContext; /** * AVHWAccel. */ typedef struct AVHWAccel { /** * Name of the hardware accelerated codec. * The name is globally unique among encoders and among decoders (but an * encoder and a decoder can share the same name). */ const char *name; /** * Type of codec implemented by the hardware accelerator. * * See AVMEDIA_TYPE_xxx */ enum AVMediaType type; /** * Codec implemented by the hardware accelerator. * * See AV_CODEC_ID_xxx */ enum AVCodecID id; /** * Supported pixel format. * * Only hardware accelerated formats are supported here. */ enum AVPixelFormat pix_fmt; /** * Hardware accelerated codec capabilities. * see FF_HWACCEL_CODEC_CAP_* */ int capabilities; struct AVHWAccel *next; /** * Called at the beginning of each frame or field picture. * * Meaningful frame information (codec specific) is guaranteed to * be parsed at this point. This function is mandatory. * * Note that buf can be NULL along with buf_size set to 0. * Otherwise, this means the whole frame is available at this point. * * @param avctx the codec context * @param buf the frame data buffer base * @param buf_size the size of the frame in bytes * @return zero if successful, a negative value otherwise */ int (*start_frame)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size); /** * Callback for each slice. * * Meaningful slice information (codec specific) is guaranteed to * be parsed at this point. This function is mandatory. * The only exception is XvMC, that works on MB level. * * @param avctx the codec context * @param buf the slice data buffer base * @param buf_size the size of the slice in bytes * @return zero if successful, a negative value otherwise */ int (*decode_slice)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size); /** * Called at the end of each frame or field picture. * * The whole picture is parsed at this point and can now be sent * to the hardware accelerator. This function is mandatory. * * @param avctx the codec context * @return zero if successful, a negative value otherwise */ int (*end_frame)(AVCodecContext *avctx); /** * Size of HW accelerator private data. * * Private data is allocated with av_mallocz() before * AVCodecContext.get_buffer() and deallocated after * AVCodecContext.release_buffer(). */ int priv_data_size; /** * Called for every Macroblock in a slice. * * XvMC uses it to replace the ff_MPV_decode_mb(). * Instead of decoding to raw picture, MB parameters are * stored in an array provided by the video driver. * * @param s the mpeg context */ void (*decode_mb)(struct MpegEncContext *s); } AVHWAccel; /** * @defgroup lavc_picture AVPicture * * Functions for working with AVPicture * @{ */ /** * Picture data structure. * * Up to four components can be stored into it, the last component is * alpha. */ typedef struct AVPicture { uint8_t *data[AV_NUM_DATA_POINTERS]; ///< pointers to the image data planes int linesize[AV_NUM_DATA_POINTERS]; ///< number of bytes per line } AVPicture; /** * @} */ enum AVSubtitleType { SUBTITLE_NONE, SUBTITLE_BITMAP, ///< A bitmap, pict will be set /** * Plain text, the text field must be set by the decoder and is * authoritative. ass and pict fields may contain approximations. */ SUBTITLE_TEXT, /** * Formatted text, the ass field must be set by the decoder and is * authoritative. pict and text fields may contain approximations. */ SUBTITLE_ASS, }; #define AV_SUBTITLE_FLAG_FORCED 0x00000001 typedef struct AVSubtitleRect { int x; ///< top left corner of pict, undefined when pict is not set int y; ///< top left corner of pict, undefined when pict is not set int w; ///< width of pict, undefined when pict is not set int h; ///< height of pict, undefined when pict is not set int nb_colors; ///< number of colors in pict, undefined when pict is not set /** * data+linesize for the bitmap of this subtitle. * can be set for text/ass as well once they where rendered */ AVPicture pict; enum AVSubtitleType type; char *text; ///< 0 terminated plain UTF-8 text /** * 0 terminated ASS/SSA compatible event line. * The presentation of this is unaffected by the other values in this * struct. */ char *ass; int flags; } AVSubtitleRect; typedef struct AVSubtitle { uint16_t format; /* 0 = graphics */ uint32_t start_display_time; /* relative to packet pts, in ms */ uint32_t end_display_time; /* relative to packet pts, in ms */ unsigned num_rects; AVSubtitleRect **rects; int64_t pts; ///< Same as packet pts, in AV_TIME_BASE } AVSubtitle; /** * If c is NULL, returns the first registered codec, * if c is non-NULL, returns the next registered codec after c, * or NULL if c is the last one. */ AVCodec *av_codec_next(const AVCodec *c); /** * Return the LIBAVCODEC_VERSION_INT constant. */ unsigned avcodec_version(void); /** * Return the libavcodec build-time configuration. */ const char *avcodec_configuration(void); /** * Return the libavcodec license. */ const char *avcodec_license(void); /** * Register the codec codec and initialize libavcodec. * * @warning either this function or avcodec_register_all() must be called * before any other libavcodec functions. * * @see avcodec_register_all() */ void avcodec_register(AVCodec *codec); /** * Register all the codecs, parsers and bitstream filters which were enabled at * configuration time. If you do not call this function you can select exactly * which formats you want to support, by using the individual registration * functions. * * @see avcodec_register * @see av_register_codec_parser * @see av_register_bitstream_filter */ void avcodec_register_all(void); /** * Allocate an AVCodecContext and set its fields to default values. The * resulting struct can be deallocated by calling avcodec_close() on it followed * by av_free(). * * @param codec if non-NULL, allocate private data and initialize defaults * for the given codec. It is illegal to then call avcodec_open2() * with a different codec. * If NULL, then the codec-specific defaults won't be initialized, * which may result in suboptimal default settings (this is * important mainly for encoders, e.g. libx264). * * @return An AVCodecContext filled with default values or NULL on failure. * @see avcodec_get_context_defaults */ AVCodecContext *avcodec_alloc_context3(const AVCodec *codec); /** * Set the fields of the given AVCodecContext to default values corresponding * to the given codec (defaults may be codec-dependent). * * Do not call this function if a non-NULL codec has been passed * to avcodec_alloc_context3() that allocated this AVCodecContext. * If codec is non-NULL, it is illegal to call avcodec_open2() with a * different codec on this AVCodecContext. */ int avcodec_get_context_defaults3(AVCodecContext *s, const AVCodec *codec); /** * Get the AVClass for AVCodecContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avcodec_get_class(void); /** * Get the AVClass for AVFrame. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avcodec_get_frame_class(void); /** * Get the AVClass for AVSubtitleRect. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avcodec_get_subtitle_rect_class(void); /** * Copy the settings of the source AVCodecContext into the destination * AVCodecContext. The resulting destination codec context will be * unopened, i.e. you are required to call avcodec_open2() before you * can use this AVCodecContext to decode/encode video/audio data. * * @param dest target codec context, should be initialized with * avcodec_alloc_context3(NULL), but otherwise uninitialized * @param src source codec context * @return AVERROR() on error (e.g. memory allocation error), 0 on success */ int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src); #if FF_API_AVFRAME_LAVC /** * @deprecated use av_frame_alloc() */ attribute_deprecated AVFrame *avcodec_alloc_frame(void); /** * Set the fields of the given AVFrame to default values. * * @param frame The AVFrame of which the fields should be set to default values. * * @deprecated use av_frame_unref() */ attribute_deprecated void avcodec_get_frame_defaults(AVFrame *frame); /** * Free the frame and any dynamically allocated objects in it, * e.g. extended_data. * * @param frame frame to be freed. The pointer will be set to NULL. * * @warning this function does NOT free the data buffers themselves * (it does not know how, since they might have been allocated with * a custom get_buffer()). * * @deprecated use av_frame_free() */ attribute_deprecated void avcodec_free_frame(AVFrame **frame); #endif /** * Initialize the AVCodecContext to use the given AVCodec. Prior to using this * function the context has to be allocated with avcodec_alloc_context3(). * * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(), * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for * retrieving a codec. * * @warning This function is not thread safe! * * @code * avcodec_register_all(); * av_dict_set(&opts, "b", "2.5M", 0); * codec = avcodec_find_decoder(AV_CODEC_ID_H264); * if (!codec) * exit(1); * * context = avcodec_alloc_context3(codec); * * if (avcodec_open2(context, codec, opts) < 0) * exit(1); * @endcode * * @param avctx The context to initialize. * @param codec The codec to open this context for. If a non-NULL codec has been * previously passed to avcodec_alloc_context3() or * avcodec_get_context_defaults3() for this context, then this * parameter MUST be either NULL or equal to the previously passed * codec. * @param options A dictionary filled with AVCodecContext and codec-private options. * On return this object will be filled with options that were not found. * * @return zero on success, a negative value on error * @see avcodec_alloc_context3(), avcodec_find_decoder(), avcodec_find_encoder(), * av_dict_set(), av_opt_find(). */ int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options); /** * Close a given AVCodecContext and free all the data associated with it * (but not the AVCodecContext itself). * * Calling this function on an AVCodecContext that hasn't been opened will free * the codec-specific data allocated in avcodec_alloc_context3() / * avcodec_get_context_defaults3() with a non-NULL codec. Subsequent calls will * do nothing. */ int avcodec_close(AVCodecContext *avctx); /** * Free all allocated data in the given subtitle struct. * * @param sub AVSubtitle to free. */ void avsubtitle_free(AVSubtitle *sub); /** * @} */ /** * @addtogroup lavc_packet * @{ */ #if FF_API_DESTRUCT_PACKET /** * Default packet destructor. * @deprecated use the AVBuffer API instead */ attribute_deprecated void av_destruct_packet(AVPacket *pkt); #endif /** * Initialize optional fields of a packet with default values. * * Note, this does not touch the data and size members, which have to be * initialized separately. * * @param pkt packet */ void av_init_packet(AVPacket *pkt); /** * Allocate the payload of a packet and initialize its fields with * default values. * * @param pkt packet * @param size wanted payload size * @return 0 if OK, AVERROR_xxx otherwise */ int av_new_packet(AVPacket *pkt, int size); /** * Reduce packet size, correctly zeroing padding * * @param pkt packet * @param size new size */ void av_shrink_packet(AVPacket *pkt, int size); /** * Increase packet size, correctly zeroing padding * * @param pkt packet * @param grow_by number of bytes by which to increase the size of the packet */ int av_grow_packet(AVPacket *pkt, int grow_by); /** * Initialize a reference-counted packet from av_malloc()ed data. * * @param pkt packet to be initialized. This function will set the data, size, * buf and destruct fields, all others are left untouched. * @param data Data allocated by av_malloc() to be used as packet data. If this * function returns successfully, the data is owned by the underlying AVBuffer. * The caller may not access the data through other means. * @param size size of data in bytes, without the padding. I.e. the full buffer * size is assumed to be size + FF_INPUT_BUFFER_PADDING_SIZE. * * @return 0 on success, a negative AVERROR on error */ int av_packet_from_data(AVPacket *pkt, uint8_t *data, int size); /** * @warning This is a hack - the packet memory allocation stuff is broken. The * packet is allocated if it was not really allocated. */ int av_dup_packet(AVPacket *pkt); /** * Copy packet, including contents * * @return 0 on success, negative AVERROR on fail */ int av_copy_packet(AVPacket *dst, AVPacket *src); /** * Copy packet side data * * @return 0 on success, negative AVERROR on fail */ int av_copy_packet_side_data(AVPacket *dst, AVPacket *src); /** * Free a packet. * * @param pkt packet to free */ void av_free_packet(AVPacket *pkt); /** * Allocate new information of a packet. * * @param pkt packet * @param type side information type * @param size side information size * @return pointer to fresh allocated data or NULL otherwise */ uint8_t* av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size); /** * Shrink the already allocated side data buffer * * @param pkt packet * @param type side information type * @param size new side information size * @return 0 on success, < 0 on failure */ int av_packet_shrink_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size); /** * Get side information from packet. * * @param pkt packet * @param type desired side information type * @param size pointer for side information size to store (optional) * @return pointer to data if present or NULL otherwise */ uint8_t* av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int *size); int av_packet_merge_side_data(AVPacket *pkt); int av_packet_split_side_data(AVPacket *pkt); /** * Pack a dictionary for use in side_data. * * @param dict The dictionary to pack. * @param size pointer to store the size of the returned data * @return pointer to data if successful, NULL otherwise */ uint8_t *av_packet_pack_dictionary(AVDictionary *dict, int *size); /** * Unpack a dictionary from side_data. * * @param data data from side_data * @param size size of the data * @param dict the metadata storage dictionary * @return 0 on success, < 0 on failure */ int av_packet_unpack_dictionary(const uint8_t *data, int size, AVDictionary **dict); /** * Convenience function to free all the side data stored. * All the other fields stay untouched. * * @param pkt packet */ void av_packet_free_side_data(AVPacket *pkt); /** * Setup a new reference to the data described by a given packet * * If src is reference-counted, setup dst as a new reference to the * buffer in src. Otherwise allocate a new buffer in dst and copy the * data from src into it. * * All the other fields are copied from src. * * @see av_packet_unref * * @param dst Destination packet * @param src Source packet * * @return 0 on success, a negative AVERROR on error. */ int av_packet_ref(AVPacket *dst, AVPacket *src); /** * Wipe the packet. * * Unreference the buffer referenced by the packet and reset the * remaining packet fields to their default values. * * @param pkt The packet to be unreferenced. */ void av_packet_unref(AVPacket *pkt); /** * Move every field in src to dst and reset src. * * @see av_packet_unref * * @param src Source packet, will be reset * @param dst Destination packet */ void av_packet_move_ref(AVPacket *dst, AVPacket *src); /** * Copy only "properties" fields from src to dst. * * Properties for the purpose of this function are all the fields * beside those related to the packet data (buf, data, size) * * @param dst Destination packet * @param src Source packet * * @return 0 on success AVERROR on failure. * */ int av_packet_copy_props(AVPacket *dst, const AVPacket *src); /** * @} */ /** * @addtogroup lavc_decoding * @{ */ /** * Find a registered decoder with a matching codec ID. * * @param id AVCodecID of the requested decoder * @return A decoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_decoder(enum AVCodecID id); /** * Find a registered decoder with the specified name. * * @param name name of the requested decoder * @return A decoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_decoder_by_name(const char *name); #if FF_API_GET_BUFFER attribute_deprecated int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic); attribute_deprecated void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic); attribute_deprecated int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic); #endif /** * The default callback for AVCodecContext.get_buffer2(). It is made public so * it can be called by custom get_buffer2() implementations for decoders without * CODEC_CAP_DR1 set. */ int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags); #if FF_API_EMU_EDGE /** * Return the amount of padding in pixels which the get_buffer callback must * provide around the edge of the image for codecs which do not have the * CODEC_FLAG_EMU_EDGE flag. * * @return Required padding in pixels. * * @deprecated CODEC_FLAG_EMU_EDGE is deprecated, so this function is no longer * needed */ attribute_deprecated unsigned avcodec_get_edge_width(void); #endif /** * Modify width and height values so that they will result in a memory * buffer that is acceptable for the codec if you do not use any horizontal * padding. * * May only be used if a codec with CODEC_CAP_DR1 has been opened. */ void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height); /** * Modify width and height values so that they will result in a memory * buffer that is acceptable for the codec if you also ensure that all * line sizes are a multiple of the respective linesize_align[i]. * * May only be used if a codec with CODEC_CAP_DR1 has been opened. */ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]); /** * Converts AVChromaLocation to swscale x/y chroma position. * * The positions represent the chroma (0,0) position in a coordinates system * with luma (0,0) representing the origin and luma(1,1) representing 256,256 * * @param xpos horizontal chroma sample position * @param ypos vertical chroma sample position */ int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos); /** * Converts swscale x/y chroma position to AVChromaLocation. * * The positions represent the chroma (0,0) position in a coordinates system * with luma (0,0) representing the origin and luma(1,1) representing 256,256 * * @param xpos horizontal chroma sample position * @param ypos vertical chroma sample position */ enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos); #if FF_API_OLD_DECODE_AUDIO /** * Wrapper function which calls avcodec_decode_audio4. * * @deprecated Use avcodec_decode_audio4 instead. * * Decode the audio frame of size avpkt->size from avpkt->data into samples. * Some decoders may support multiple frames in a single AVPacket, such * decoders would then just decode the first frame. In this case, * avcodec_decode_audio3 has to be called again with an AVPacket that contains * the remaining data in order to decode the second frame etc. * If no frame * could be outputted, frame_size_ptr is zero. Otherwise, it is the * decompressed frame size in bytes. * * @warning You must set frame_size_ptr to the allocated size of the * output buffer before calling avcodec_decode_audio3(). * * @warning The input buffer must be FF_INPUT_BUFFER_PADDING_SIZE larger than * the actual read bytes because some optimized bitstream readers read 32 or 64 * bits at once and could read over the end. * * @warning The end of the input buffer avpkt->data should be set to 0 to ensure that * no overreading happens for damaged MPEG streams. * * @warning You must not provide a custom get_buffer() when using * avcodec_decode_audio3(). Doing so will override it with * avcodec_default_get_buffer. Use avcodec_decode_audio4() instead, * which does allow the application to provide a custom get_buffer(). * * @note You might have to align the input buffer avpkt->data and output buffer * samples. The alignment requirements depend on the CPU: On some CPUs it isn't * necessary at all, on others it won't work at all if not aligned and on others * it will work but it will have an impact on performance. * * In practice, avpkt->data should have 4 byte alignment at minimum and * samples should be 16 byte aligned unless the CPU doesn't need it * (AltiVec and SSE do). * * @note Codecs which have the CODEC_CAP_DELAY capability set have a delay * between input and output, these need to be fed with avpkt->data=NULL, * avpkt->size=0 at the end to return the remaining frames. * * @param avctx the codec context * @param[out] samples the output buffer, sample type in avctx->sample_fmt * If the sample format is planar, each channel plane will * be the same size, with no padding between channels. * @param[in,out] frame_size_ptr the output buffer size in bytes * @param[in] avpkt The input AVPacket containing the input buffer. * You can create such packet with av_init_packet() and by then setting * data and size, some decoders might in addition need other fields. * All decoders are designed to use the least fields possible though. * @return On error a negative value is returned, otherwise the number of bytes * used or zero if no frame data was decompressed (used) from the input AVPacket. */ attribute_deprecated int avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples, int *frame_size_ptr, AVPacket *avpkt); #endif /** * Decode the audio frame of size avpkt->size from avpkt->data into frame. * * Some decoders may support multiple frames in a single AVPacket. Such * decoders would then just decode the first frame and the return value would be * less than the packet size. In this case, avcodec_decode_audio4 has to be * called again with an AVPacket containing the remaining data in order to * decode the second frame, etc... Even if no frames are returned, the packet * needs to be fed to the decoder with remaining data until it is completely * consumed or an error occurs. * * Some decoders (those marked with CODEC_CAP_DELAY) have a delay between input * and output. This means that for some packets they will not immediately * produce decoded output and need to be flushed at the end of decoding to get * all the decoded data. Flushing is done by calling this function with packets * with avpkt->data set to NULL and avpkt->size set to 0 until it stops * returning samples. It is safe to flush even those decoders that are not * marked with CODEC_CAP_DELAY, then no samples will be returned. * * @warning The input buffer, avpkt->data must be FF_INPUT_BUFFER_PADDING_SIZE * larger than the actual read bytes because some optimized bitstream * readers read 32 or 64 bits at once and could read over the end. * * @param avctx the codec context * @param[out] frame The AVFrame in which to store decoded audio samples. * The decoder will allocate a buffer for the decoded frame by * calling the AVCodecContext.get_buffer2() callback. * When AVCodecContext.refcounted_frames is set to 1, the frame is * reference counted and the returned reference belongs to the * caller. The caller must release the frame using av_frame_unref() * when the frame is no longer needed. The caller may safely write * to the frame if av_frame_is_writable() returns 1. * When AVCodecContext.refcounted_frames is set to 0, the returned * reference belongs to the decoder and is valid only until the * next call to this function or until closing or flushing the * decoder. The caller may not write to it. * @param[out] got_frame_ptr Zero if no frame could be decoded, otherwise it is * non-zero. Note that this field being set to zero * does not mean that an error has occurred. For * decoders with CODEC_CAP_DELAY set, no given decode * call is guaranteed to produce a frame. * @param[in] avpkt The input AVPacket containing the input buffer. * At least avpkt->data and avpkt->size should be set. Some * decoders might also require additional fields to be set. * @return A negative error code is returned if an error occurred during * decoding, otherwise the number of bytes consumed from the input * AVPacket is returned. */ int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt); /** * Decode the video frame of size avpkt->size from avpkt->data into picture. * Some decoders may support multiple frames in a single AVPacket, such * decoders would then just decode the first frame. * * @warning The input buffer must be FF_INPUT_BUFFER_PADDING_SIZE larger than * the actual read bytes because some optimized bitstream readers read 32 or 64 * bits at once and could read over the end. * * @warning The end of the input buffer buf should be set to 0 to ensure that * no overreading happens for damaged MPEG streams. * * @note Codecs which have the CODEC_CAP_DELAY capability set have a delay * between input and output, these need to be fed with avpkt->data=NULL, * avpkt->size=0 at the end to return the remaining frames. * * @param avctx the codec context * @param[out] picture The AVFrame in which the decoded video frame will be stored. * Use av_frame_alloc() to get an AVFrame. The codec will * allocate memory for the actual bitmap by calling the * AVCodecContext.get_buffer2() callback. * When AVCodecContext.refcounted_frames is set to 1, the frame is * reference counted and the returned reference belongs to the * caller. The caller must release the frame using av_frame_unref() * when the frame is no longer needed. The caller may safely write * to the frame if av_frame_is_writable() returns 1. * When AVCodecContext.refcounted_frames is set to 0, the returned * reference belongs to the decoder and is valid only until the * next call to this function or until closing or flushing the * decoder. The caller may not write to it. * * @param[in] avpkt The input AVPacket containing the input buffer. * You can create such packet with av_init_packet() and by then setting * data and size, some decoders might in addition need other fields like * flags&AV_PKT_FLAG_KEY. All decoders are designed to use the least * fields possible. * @param[in,out] got_picture_ptr Zero if no frame could be decompressed, otherwise, it is nonzero. * @return On error a negative value is returned, otherwise the number of bytes * used or zero if no frame could be decompressed. */ int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, const AVPacket *avpkt); /** * Decode a subtitle message. * Return a negative value on error, otherwise return the number of bytes used. * If no subtitle could be decompressed, got_sub_ptr is zero. * Otherwise, the subtitle is stored in *sub. * Note that CODEC_CAP_DR1 is not available for subtitle codecs. This is for * simplicity, because the performance difference is expect to be negligible * and reusing a get_buffer written for video codecs would probably perform badly * due to a potentially very different allocation pattern. * * Some decoders (those marked with CODEC_CAP_DELAY) have a delay between input * and output. This means that for some packets they will not immediately * produce decoded output and need to be flushed at the end of decoding to get * all the decoded data. Flushing is done by calling this function with packets * with avpkt->data set to NULL and avpkt->size set to 0 until it stops * returning subtitles. It is safe to flush even those decoders that are not * marked with CODEC_CAP_DELAY, then no subtitles will be returned. * * @param avctx the codec context * @param[out] sub The AVSubtitle in which the decoded subtitle will be stored, must be freed with avsubtitle_free if *got_sub_ptr is set. * @param[in,out] got_sub_ptr Zero if no subtitle could be decompressed, otherwise, it is nonzero. * @param[in] avpkt The input AVPacket containing the input buffer. */ int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt); /** * @defgroup lavc_parsing Frame parsing * @{ */ enum AVPictureStructure { AV_PICTURE_STRUCTURE_UNKNOWN, //< unknown AV_PICTURE_STRUCTURE_TOP_FIELD, //< coded as top field AV_PICTURE_STRUCTURE_BOTTOM_FIELD, //< coded as bottom field AV_PICTURE_STRUCTURE_FRAME, //< coded as frame }; typedef struct AVCodecParserContext { void *priv_data; struct AVCodecParser *parser; int64_t frame_offset; /* offset of the current frame */ int64_t cur_offset; /* current offset (incremented by each av_parser_parse()) */ int64_t next_frame_offset; /* offset of the next frame */ /* video info */ int pict_type; /* XXX: Put it back in AVCodecContext. */ /** * This field is used for proper frame duration computation in lavf. * It signals, how much longer the frame duration of the current frame * is compared to normal frame duration. * * frame_duration = (1 + repeat_pict) * time_base * * It is used by codecs like H.264 to display telecined material. */ int repeat_pict; /* XXX: Put it back in AVCodecContext. */ int64_t pts; /* pts of the current frame */ int64_t dts; /* dts of the current frame */ /* private data */ int64_t last_pts; int64_t last_dts; int fetch_timestamp; #define AV_PARSER_PTS_NB 4 int cur_frame_start_index; int64_t cur_frame_offset[AV_PARSER_PTS_NB]; int64_t cur_frame_pts[AV_PARSER_PTS_NB]; int64_t cur_frame_dts[AV_PARSER_PTS_NB]; int flags; #define PARSER_FLAG_COMPLETE_FRAMES 0x0001 #define PARSER_FLAG_ONCE 0x0002 /// Set if the parser has a valid file offset #define PARSER_FLAG_FETCHED_OFFSET 0x0004 #define PARSER_FLAG_USE_CODEC_TS 0x1000 int64_t offset; ///< byte offset from starting packet start int64_t cur_frame_end[AV_PARSER_PTS_NB]; /** * Set by parser to 1 for key frames and 0 for non-key frames. * It is initialized to -1, so if the parser doesn't set this flag, * old-style fallback using AV_PICTURE_TYPE_I picture type as key frames * will be used. */ int key_frame; /** * Time difference in stream time base units from the pts of this * packet to the point at which the output from the decoder has converged * independent from the availability of previous frames. That is, the * frames are virtually identical no matter if decoding started from * the very first frame or from this keyframe. * Is AV_NOPTS_VALUE if unknown. * This field is not the display duration of the current frame. * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY * set. * * The purpose of this field is to allow seeking in streams that have no * keyframes in the conventional sense. It corresponds to the * recovery point SEI in H.264 and match_time_delta in NUT. It is also * essential for some types of subtitle streams to ensure that all * subtitles are correctly displayed after seeking. */ int64_t convergence_duration; // Timestamp generation support: /** * Synchronization point for start of timestamp generation. * * Set to >0 for sync point, 0 for no sync point and <0 for undefined * (default). * * For example, this corresponds to presence of H.264 buffering period * SEI message. */ int dts_sync_point; /** * Offset of the current timestamp against last timestamp sync point in * units of AVCodecContext.time_base. * * Set to INT_MIN when dts_sync_point unused. Otherwise, it must * contain a valid timestamp offset. * * Note that the timestamp of sync point has usually a nonzero * dts_ref_dts_delta, which refers to the previous sync point. Offset of * the next frame after timestamp sync point will be usually 1. * * For example, this corresponds to H.264 cpb_removal_delay. */ int dts_ref_dts_delta; /** * Presentation delay of current frame in units of AVCodecContext.time_base. * * Set to INT_MIN when dts_sync_point unused. Otherwise, it must * contain valid non-negative timestamp delta (presentation time of a frame * must not lie in the past). * * This delay represents the difference between decoding and presentation * time of the frame. * * For example, this corresponds to H.264 dpb_output_delay. */ int pts_dts_delta; /** * Position of the packet in file. * * Analogous to cur_frame_pts/dts */ int64_t cur_frame_pos[AV_PARSER_PTS_NB]; /** * Byte position of currently parsed frame in stream. */ int64_t pos; /** * Previous frame byte position. */ int64_t last_pos; /** * Duration of the current frame. * For audio, this is in units of 1 / AVCodecContext.sample_rate. * For all other types, this is in units of AVCodecContext.time_base. */ int duration; enum AVFieldOrder field_order; /** * Indicate whether a picture is coded as a frame, top field or bottom field. * * For example, H.264 field_pic_flag equal to 0 corresponds to * AV_PICTURE_STRUCTURE_FRAME. An H.264 picture with field_pic_flag * equal to 1 and bottom_field_flag equal to 0 corresponds to * AV_PICTURE_STRUCTURE_TOP_FIELD. */ enum AVPictureStructure picture_structure; /** * Picture number incremented in presentation or output order. * This field may be reinitialized at the first picture of a new sequence. * * For example, this corresponds to H.264 PicOrderCnt. */ int output_picture_number; } AVCodecParserContext; typedef struct AVCodecParser { int codec_ids[5]; /* several codec IDs are permitted */ int priv_data_size; int (*parser_init)(AVCodecParserContext *s); int (*parser_parse)(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size); void (*parser_close)(AVCodecParserContext *s); int (*split)(AVCodecContext *avctx, const uint8_t *buf, int buf_size); struct AVCodecParser *next; } AVCodecParser; AVCodecParser *av_parser_next(AVCodecParser *c); void av_register_codec_parser(AVCodecParser *parser); AVCodecParserContext *av_parser_init(int codec_id); /** * Parse a packet. * * @param s parser context. * @param avctx codec context. * @param poutbuf set to pointer to parsed buffer or NULL if not yet finished. * @param poutbuf_size set to size of parsed buffer or zero if not yet finished. * @param buf input buffer. * @param buf_size input length, to signal EOF, this should be 0 (so that the last frame can be output). * @param pts input presentation timestamp. * @param dts input decoding timestamp. * @param pos input byte position in stream. * @return the number of bytes of the input bitstream used. * * Example: * @code * while(in_len){ * len = av_parser_parse2(myparser, AVCodecContext, &data, &size, * in_data, in_len, * pts, dts, pos); * in_data += len; * in_len -= len; * * if(size) * decode_frame(data, size); * } * @endcode */ int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int64_t pts, int64_t dts, int64_t pos); /** * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed * @deprecated use AVBitStreamFilter */ int av_parser_change(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe); void av_parser_close(AVCodecParserContext *s); /** * @} * @} */ /** * @addtogroup lavc_encoding * @{ */ /** * Find a registered encoder with a matching codec ID. * * @param id AVCodecID of the requested encoder * @return An encoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_encoder(enum AVCodecID id); /** * Find a registered encoder with the specified name. * * @param name name of the requested encoder * @return An encoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_encoder_by_name(const char *name); #if FF_API_OLD_ENCODE_AUDIO /** * Encode an audio frame from samples into buf. * * @deprecated Use avcodec_encode_audio2 instead. * * @note The output buffer should be at least FF_MIN_BUFFER_SIZE bytes large. * However, for codecs with avctx->frame_size equal to 0 (e.g. PCM) the user * will know how much space is needed because it depends on the value passed * in buf_size as described below. In that case a lower value can be used. * * @param avctx the codec context * @param[out] buf the output buffer * @param[in] buf_size the output buffer size * @param[in] samples the input buffer containing the samples * The number of samples read from this buffer is frame_size*channels, * both of which are defined in avctx. * For codecs which have avctx->frame_size equal to 0 (e.g. PCM) the number of * samples read from samples is equal to: * buf_size * 8 / (avctx->channels * av_get_bits_per_sample(avctx->codec_id)) * This also implies that av_get_bits_per_sample() must not return 0 for these * codecs. * @return On error a negative value is returned, on success zero or the number * of bytes used to encode the data read from the input buffer. */ int attribute_deprecated avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size, const short *samples); #endif /** * Encode a frame of audio. * * Takes input samples from frame and writes the next output packet, if * available, to avpkt. The output packet does not necessarily contain data for * the most recent frame, as encoders can delay, split, and combine input frames * internally as needed. * * @param avctx codec context * @param avpkt output AVPacket. * The user can supply an output buffer by setting * avpkt->data and avpkt->size prior to calling the * function, but if the size of the user-provided data is not * large enough, encoding will fail. If avpkt->data and * avpkt->size are set, avpkt->destruct must also be set. All * other AVPacket fields will be reset by the encoder using * av_init_packet(). If avpkt->data is NULL, the encoder will * allocate it. The encoder will set avpkt->size to the size * of the output packet. * * If this function fails or produces no output, avpkt will be * freed using av_free_packet() (i.e. avpkt->destruct will be * called to free the user supplied buffer). * @param[in] frame AVFrame containing the raw audio data to be encoded. * May be NULL when flushing an encoder that has the * CODEC_CAP_DELAY capability set. * If CODEC_CAP_VARIABLE_FRAME_SIZE is set, then each frame * can have any number of samples. * If it is not set, frame->nb_samples must be equal to * avctx->frame_size for all frames except the last. * The final frame may be smaller than avctx->frame_size. * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the * output packet is non-empty, and to 0 if it is * empty. If the function returns an error, the * packet can be assumed to be invalid, and the * value of got_packet_ptr is undefined and should * not be used. * @return 0 on success, negative error code on failure */ int avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr); #if FF_API_OLD_ENCODE_VIDEO /** * @deprecated use avcodec_encode_video2() instead. * * Encode a video frame from pict into buf. * The input picture should be * stored using a specific format, namely avctx.pix_fmt. * * @param avctx the codec context * @param[out] buf the output buffer for the bitstream of encoded frame * @param[in] buf_size the size of the output buffer in bytes * @param[in] pict the input picture to encode * @return On error a negative value is returned, on success zero or the number * of bytes used from the output buffer. */ attribute_deprecated int avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVFrame *pict); #endif /** * Encode a frame of video. * * Takes input raw video data from frame and writes the next output packet, if * available, to avpkt. The output packet does not necessarily contain data for * the most recent frame, as encoders can delay and reorder input frames * internally as needed. * * @param avctx codec context * @param avpkt output AVPacket. * The user can supply an output buffer by setting * avpkt->data and avpkt->size prior to calling the * function, but if the size of the user-provided data is not * large enough, encoding will fail. All other AVPacket fields * will be reset by the encoder using av_init_packet(). If * avpkt->data is NULL, the encoder will allocate it. * The encoder will set avpkt->size to the size of the * output packet. The returned data (if any) belongs to the * caller, he is responsible for freeing it. * * If this function fails or produces no output, avpkt will be * freed using av_free_packet() (i.e. avpkt->destruct will be * called to free the user supplied buffer). * @param[in] frame AVFrame containing the raw video data to be encoded. * May be NULL when flushing an encoder that has the * CODEC_CAP_DELAY capability set. * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the * output packet is non-empty, and to 0 if it is * empty. If the function returns an error, the * packet can be assumed to be invalid, and the * value of got_packet_ptr is undefined and should * not be used. * @return 0 on success, negative error code on failure */ int avcodec_encode_video2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr); int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVSubtitle *sub); /** * @} */ #if FF_API_AVCODEC_RESAMPLE /** * @defgroup lavc_resample Audio resampling * @ingroup libavc * @deprecated use libswresample instead * * @{ */ struct ReSampleContext; struct AVResampleContext; typedef struct ReSampleContext ReSampleContext; /** * Initialize audio resampling context. * * @param output_channels number of output channels * @param input_channels number of input channels * @param output_rate output sample rate * @param input_rate input sample rate * @param sample_fmt_out requested output sample format * @param sample_fmt_in input sample format * @param filter_length length of each FIR filter in the filterbank relative to the cutoff frequency * @param log2_phase_count log2 of the number of entries in the polyphase filterbank * @param linear if 1 then the used FIR filter will be linearly interpolated between the 2 closest, if 0 the closest will be used * @param cutoff cutoff frequency, 1.0 corresponds to half the output sampling rate * @return allocated ReSampleContext, NULL if error occurred */ attribute_deprecated ReSampleContext *av_audio_resample_init(int output_channels, int input_channels, int output_rate, int input_rate, enum AVSampleFormat sample_fmt_out, enum AVSampleFormat sample_fmt_in, int filter_length, int log2_phase_count, int linear, double cutoff); attribute_deprecated int audio_resample(ReSampleContext *s, short *output, short *input, int nb_samples); /** * Free resample context. * * @param s a non-NULL pointer to a resample context previously * created with av_audio_resample_init() */ attribute_deprecated void audio_resample_close(ReSampleContext *s); /** * Initialize an audio resampler. * Note, if either rate is not an integer then simply scale both rates up so they are. * @param filter_length length of each FIR filter in the filterbank relative to the cutoff freq * @param log2_phase_count log2 of the number of entries in the polyphase filterbank * @param linear If 1 then the used FIR filter will be linearly interpolated between the 2 closest, if 0 the closest will be used * @param cutoff cutoff frequency, 1.0 corresponds to half the output sampling rate */ attribute_deprecated struct AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_length, int log2_phase_count, int linear, double cutoff); /** * Resample an array of samples using a previously configured context. * @param src an array of unconsumed samples * @param consumed the number of samples of src which have been consumed are returned here * @param src_size the number of unconsumed samples available * @param dst_size the amount of space in samples available in dst * @param update_ctx If this is 0 then the context will not be modified, that way several channels can be resampled with the same context. * @return the number of samples written in dst or -1 if an error occurred */ attribute_deprecated int av_resample(struct AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx); /** * Compensate samplerate/timestamp drift. The compensation is done by changing * the resampler parameters, so no audible clicks or similar distortions occur * @param compensation_distance distance in output samples over which the compensation should be performed * @param sample_delta number of output samples which should be output less * * example: av_resample_compensate(c, 10, 500) * here instead of 510 samples only 500 samples would be output * * note, due to rounding the actual compensation might be slightly different, * especially if the compensation_distance is large and the in_rate used during init is small */ attribute_deprecated void av_resample_compensate(struct AVResampleContext *c, int sample_delta, int compensation_distance); attribute_deprecated void av_resample_close(struct AVResampleContext *c); /** * @} */ #endif /** * @addtogroup lavc_picture * @{ */ /** * Allocate memory for the pixels of a picture and setup the AVPicture * fields for it. * * Call avpicture_free() to free it. * * @param picture the picture structure to be filled in * @param pix_fmt the pixel format of the picture * @param width the width of the picture * @param height the height of the picture * @return zero if successful, a negative error code otherwise * * @see av_image_alloc(), avpicture_fill() */ int avpicture_alloc(AVPicture *picture, enum AVPixelFormat pix_fmt, int width, int height); /** * Free a picture previously allocated by avpicture_alloc(). * The data buffer used by the AVPicture is freed, but the AVPicture structure * itself is not. * * @param picture the AVPicture to be freed */ void avpicture_free(AVPicture *picture); /** * Setup the picture fields based on the specified image parameters * and the provided image data buffer. * * The picture fields are filled in by using the image data buffer * pointed to by ptr. * * If ptr is NULL, the function will fill only the picture linesize * array and return the required size for the image buffer. * * To allocate an image buffer and fill the picture data in one call, * use avpicture_alloc(). * * @param picture the picture to be filled in * @param ptr buffer where the image data is stored, or NULL * @param pix_fmt the pixel format of the image * @param width the width of the image in pixels * @param height the height of the image in pixels * @return the size in bytes required for src, a negative error code * in case of failure * * @see av_image_fill_arrays() */ int avpicture_fill(AVPicture *picture, const uint8_t *ptr, enum AVPixelFormat pix_fmt, int width, int height); /** * Copy pixel data from an AVPicture into a buffer. * * avpicture_get_size() can be used to compute the required size for * the buffer to fill. * * @param src source picture with filled data * @param pix_fmt picture pixel format * @param width picture width * @param height picture height * @param dest destination buffer * @param dest_size destination buffer size in bytes * @return the number of bytes written to dest, or a negative value * (error code) on error, for example if the destination buffer is not * big enough * * @see av_image_copy_to_buffer() */ int avpicture_layout(const AVPicture *src, enum AVPixelFormat pix_fmt, int width, int height, unsigned char *dest, int dest_size); /** * Calculate the size in bytes that a picture of the given width and height * would occupy if stored in the given picture format. * * @param pix_fmt picture pixel format * @param width picture width * @param height picture height * @return the computed picture buffer size or a negative error code * in case of error * * @see av_image_get_buffer_size(). */ int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height); #if FF_API_DEINTERLACE /** * deinterlace - if not supported return -1 * * @deprecated - use yadif (in libavfilter) instead */ attribute_deprecated int avpicture_deinterlace(AVPicture *dst, const AVPicture *src, enum AVPixelFormat pix_fmt, int width, int height); #endif /** * Copy image src to dst. Wraps av_image_copy(). */ void av_picture_copy(AVPicture *dst, const AVPicture *src, enum AVPixelFormat pix_fmt, int width, int height); /** * Crop image top and left side. */ int av_picture_crop(AVPicture *dst, const AVPicture *src, enum AVPixelFormat pix_fmt, int top_band, int left_band); /** * Pad image. */ int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width, enum AVPixelFormat pix_fmt, int padtop, int padbottom, int padleft, int padright, int *color); /** * @} */ /** * @defgroup lavc_misc Utility functions * @ingroup libavc * * Miscellaneous utility functions related to both encoding and decoding * (or neither). * @{ */ /** * @defgroup lavc_misc_pixfmt Pixel formats * * Functions for working with pixel formats. * @{ */ /** * Utility function to access log2_chroma_w log2_chroma_h from * the pixel format AVPixFmtDescriptor. * * This function asserts that pix_fmt is valid. See av_pix_fmt_get_chroma_sub_sample * for one that returns a failure code and continues in case of invalid * pix_fmts. * * @param[in] pix_fmt the pixel format * @param[out] h_shift store log2_chroma_w * @param[out] v_shift store log2_chroma_h * * @see av_pix_fmt_get_chroma_sub_sample */ void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift); /** * Return a value representing the fourCC code associated to the * pixel format pix_fmt, or 0 if no associated fourCC code can be * found. */ unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat pix_fmt); #define FF_LOSS_RESOLUTION 0x0001 /**< loss due to resolution change */ #define FF_LOSS_DEPTH 0x0002 /**< loss due to color depth change */ #define FF_LOSS_COLORSPACE 0x0004 /**< loss due to color space conversion */ #define FF_LOSS_ALPHA 0x0008 /**< loss of alpha bits */ #define FF_LOSS_COLORQUANT 0x0010 /**< loss due to color quantization */ #define FF_LOSS_CHROMA 0x0020 /**< loss of chroma (e.g. RGB to gray conversion) */ /** * Compute what kind of losses will occur when converting from one specific * pixel format to another. * When converting from one pixel format to another, information loss may occur. * For example, when converting from RGB24 to GRAY, the color information will * be lost. Similarly, other losses occur when converting from some formats to * other formats. These losses can involve loss of chroma, but also loss of * resolution, loss of color depth, loss due to the color space conversion, loss * of the alpha bits or loss due to color quantization. * avcodec_get_fix_fmt_loss() informs you about the various types of losses * which will occur when converting from one pixel format to another. * * @param[in] dst_pix_fmt destination pixel format * @param[in] src_pix_fmt source pixel format * @param[in] has_alpha Whether the source pixel format alpha channel is used. * @return Combination of flags informing you what kind of losses will occur * (maximum loss for an invalid dst_pix_fmt). */ int avcodec_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt, enum AVPixelFormat src_pix_fmt, int has_alpha); /** * Find the best pixel format to convert to given a certain source pixel * format. When converting from one pixel format to another, information loss * may occur. For example, when converting from RGB24 to GRAY, the color * information will be lost. Similarly, other losses occur when converting from * some formats to other formats. avcodec_find_best_pix_fmt_of_2() searches which of * the given pixel formats should be used to suffer the least amount of loss. * The pixel formats from which it chooses one, are determined by the * pix_fmt_list parameter. * * * @param[in] pix_fmt_list AV_PIX_FMT_NONE terminated array of pixel formats to choose from * @param[in] src_pix_fmt source pixel format * @param[in] has_alpha Whether the source pixel format alpha channel is used. * @param[out] loss_ptr Combination of flags informing you what kind of losses will occur. * @return The best pixel format to convert to or -1 if none was found. */ enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(const enum AVPixelFormat *pix_fmt_list, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); /** * Find the best pixel format to convert to given a certain source pixel * format and a selection of two destination pixel formats. When converting from * one pixel format to another, information loss may occur. For example, when converting * from RGB24 to GRAY, the color information will be lost. Similarly, other losses occur when * converting from some formats to other formats. avcodec_find_best_pix_fmt_of_2() selects which of * the given pixel formats should be used to suffer the least amount of loss. * * If one of the destination formats is AV_PIX_FMT_NONE the other pixel format (if valid) will be * returned. * * @code * src_pix_fmt = AV_PIX_FMT_YUV420P; * dst_pix_fmt1= AV_PIX_FMT_RGB24; * dst_pix_fmt2= AV_PIX_FMT_GRAY8; * dst_pix_fmt3= AV_PIX_FMT_RGB8; * loss= FF_LOSS_CHROMA; // don't care about chroma loss, so chroma loss will be ignored. * dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt1, dst_pix_fmt2, src_pix_fmt, alpha, &loss); * dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt, dst_pix_fmt3, src_pix_fmt, alpha, &loss); * @endcode * * @param[in] dst_pix_fmt1 One of the two destination pixel formats to choose from * @param[in] dst_pix_fmt2 The other of the two destination pixel formats to choose from * @param[in] src_pix_fmt Source pixel format * @param[in] has_alpha Whether the source pixel format alpha channel is used. * @param[in, out] loss_ptr Combination of loss flags. In: selects which of the losses to ignore, i.e. * NULL or value of zero means we care about all losses. Out: the loss * that occurs when converting from src to selected dst pixel format. * @return The best pixel format to convert to or -1 if none was found. */ enum AVPixelFormat avcodec_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); attribute_deprecated #if AV_HAVE_INCOMPATIBLE_LIBAV_ABI enum AVPixelFormat avcodec_find_best_pix_fmt2(const enum AVPixelFormat *pix_fmt_list, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); #else enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); #endif enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat * fmt); /** * @} */ #if FF_API_SET_DIMENSIONS /** * @deprecated this function is not supposed to be used from outside of lavc */ attribute_deprecated void avcodec_set_dimensions(AVCodecContext *s, int width, int height); #endif /** * Put a string representing the codec tag codec_tag in buf. * * @param buf buffer to place codec tag in * @param buf_size size in bytes of buf * @param codec_tag codec tag to assign * @return the length of the string that would have been generated if * enough space had been available, excluding the trailing null */ size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag); void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode); /** * Return a name for the specified profile, if available. * * @param codec the codec that is searched for the given profile * @param profile the profile value for which a name is requested * @return A name for the profile if found, NULL otherwise. */ const char *av_get_profile_name(const AVCodec *codec, int profile); int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size); int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int, int),void *arg, int *ret, int count); //FIXME func typedef /** * Fill AVFrame audio data and linesize pointers. * * The buffer buf must be a preallocated buffer with a size big enough * to contain the specified samples amount. The filled AVFrame data * pointers will point to this buffer. * * AVFrame extended_data channel pointers are allocated if necessary for * planar audio. * * @param frame the AVFrame * frame->nb_samples must be set prior to calling the * function. This function fills in frame->data, * frame->extended_data, frame->linesize[0]. * @param nb_channels channel count * @param sample_fmt sample format * @param buf buffer to use for frame data * @param buf_size size of buffer * @param align plane size sample alignment (0 = default) * @return >=0 on success, negative error code on failure * @todo return the size in bytes required to store the samples in * case of success, at the next libavutil bump */ int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels, enum AVSampleFormat sample_fmt, const uint8_t *buf, int buf_size, int align); /** * Reset the internal decoder state / flush internal buffers. Should be called * e.g. when seeking or when switching to a different stream. * * @note when refcounted frames are not used (i.e. avctx->refcounted_frames is 0), * this invalidates the frames previously returned from the decoder. When * refcounted frames are used, the decoder just releases any references it might * keep internally, but the caller's reference remains valid. */ void avcodec_flush_buffers(AVCodecContext *avctx); /** * Return codec bits per sample. * * @param[in] codec_id the codec * @return Number of bits per sample or zero if unknown for the given codec. */ int av_get_bits_per_sample(enum AVCodecID codec_id); /** * Return the PCM codec associated with a sample format. * @param be endianness, 0 for little, 1 for big, * -1 (or anything else) for native * @return AV_CODEC_ID_PCM_* or AV_CODEC_ID_NONE */ enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be); /** * Return codec bits per sample. * Only return non-zero if the bits per sample is exactly correct, not an * approximation. * * @param[in] codec_id the codec * @return Number of bits per sample or zero if unknown for the given codec. */ int av_get_exact_bits_per_sample(enum AVCodecID codec_id); /** * Return audio frame duration. * * @param avctx codec context * @param frame_bytes size of the frame, or 0 if unknown * @return frame duration, in samples, if known. 0 if not able to * determine. */ int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes); typedef struct AVBitStreamFilterContext { void *priv_data; struct AVBitStreamFilter *filter; AVCodecParserContext *parser; struct AVBitStreamFilterContext *next; } AVBitStreamFilterContext; typedef struct AVBitStreamFilter { const char *name; int priv_data_size; int (*filter)(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe); void (*close)(AVBitStreamFilterContext *bsfc); struct AVBitStreamFilter *next; } AVBitStreamFilter; /** * Register a bitstream filter. * * The filter will be accessible to the application code through * av_bitstream_filter_next() or can be directly initialized with * av_bitstream_filter_init(). * * @see avcodec_register_all() */ void av_register_bitstream_filter(AVBitStreamFilter *bsf); /** * Create and initialize a bitstream filter context given a bitstream * filter name. * * The returned context must be freed with av_bitstream_filter_close(). * * @param name the name of the bitstream filter * @return a bitstream filter context if a matching filter was found * and successfully initialized, NULL otherwise */ AVBitStreamFilterContext *av_bitstream_filter_init(const char *name); /** * Filter bitstream. * * This function filters the buffer buf with size buf_size, and places the * filtered buffer in the buffer pointed to by poutbuf. * * The output buffer must be freed by the caller. * * @param bsfc bitstream filter context created by av_bitstream_filter_init() * @param avctx AVCodecContext accessed by the filter, may be NULL. * If specified, this must point to the encoder context of the * output stream the packet is sent to. * @param args arguments which specify the filter configuration, may be NULL * @param poutbuf pointer which is updated to point to the filtered buffer * @param poutbuf_size pointer which is updated to the filtered buffer size in bytes * @param buf buffer containing the data to filter * @param buf_size size in bytes of buf * @param keyframe set to non-zero if the buffer to filter corresponds to a key-frame packet data * @return >= 0 in case of success, or a negative error code in case of failure * * If the return value is positive, an output buffer is allocated and * is availble in *poutbuf, and is distinct from the input buffer. * * If the return value is 0, the output buffer is not allocated and * should be considered identical to the input buffer, or in case * *poutbuf was set it points to the input buffer (not necessarily to * its starting address). */ int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe); /** * Release bitstream filter context. * * @param bsf the bitstream filter context created with * av_bitstream_filter_init(), can be NULL */ void av_bitstream_filter_close(AVBitStreamFilterContext *bsf); /** * If f is NULL, return the first registered bitstream filter, * if f is non-NULL, return the next registered bitstream filter * after f, or NULL if f is the last one. * * This function can be used to iterate over all registered bitstream * filters. */ AVBitStreamFilter *av_bitstream_filter_next(AVBitStreamFilter *f); /* memory */ /** * Same behaviour av_fast_malloc but the buffer has additional * FF_INPUT_BUFFER_PADDING_SIZE at the end which will always be 0. * * In addition the whole buffer will initially and after resizes * be 0-initialized so that no uninitialized data will ever appear. */ void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size); /** * Same behaviour av_fast_padded_malloc except that buffer will always * be 0-initialized after call. */ void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size); /** * Encode extradata length to a buffer. Used by xiph codecs. * * @param s buffer to write to; must be at least (v/255+1) bytes long * @param v size of extradata in bytes * @return number of bytes written to the buffer. */ unsigned int av_xiphlacing(unsigned char *s, unsigned int v); #if FF_API_MISSING_SAMPLE /** * Log a generic warning message about a missing feature. This function is * intended to be used internally by FFmpeg (libavcodec, libavformat, etc.) * only, and would normally not be used by applications. * @param[in] avc a pointer to an arbitrary struct of which the first field is * a pointer to an AVClass struct * @param[in] feature string containing the name of the missing feature * @param[in] want_sample indicates if samples are wanted which exhibit this feature. * If want_sample is non-zero, additional verbage will be added to the log * message which tells the user how to report samples to the development * mailing list. * @deprecated Use avpriv_report_missing_feature() instead. */ attribute_deprecated void av_log_missing_feature(void *avc, const char *feature, int want_sample); /** * Log a generic warning message asking for a sample. This function is * intended to be used internally by FFmpeg (libavcodec, libavformat, etc.) * only, and would normally not be used by applications. * @param[in] avc a pointer to an arbitrary struct of which the first field is * a pointer to an AVClass struct * @param[in] msg string containing an optional message, or NULL if no message * @deprecated Use avpriv_request_sample() instead. */ attribute_deprecated void av_log_ask_for_sample(void *avc, const char *msg, ...) av_printf_format(2, 3); #endif /* FF_API_MISSING_SAMPLE */ /** * Register the hardware accelerator hwaccel. */ void av_register_hwaccel(AVHWAccel *hwaccel); /** * If hwaccel is NULL, returns the first registered hardware accelerator, * if hwaccel is non-NULL, returns the next registered hardware accelerator * after hwaccel, or NULL if hwaccel is the last one. */ AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel); /** * Lock operation used by lockmgr */ enum AVLockOp { AV_LOCK_CREATE, ///< Create a mutex AV_LOCK_OBTAIN, ///< Lock the mutex AV_LOCK_RELEASE, ///< Unlock the mutex AV_LOCK_DESTROY, ///< Free mutex resources }; /** * Register a user provided lock manager supporting the operations * specified by AVLockOp. mutex points to a (void *) where the * lockmgr should store/get a pointer to a user allocated mutex. It's * NULL upon AV_LOCK_CREATE and != NULL for all other ops. * * @param cb User defined callback. Note: FFmpeg may invoke calls to this * callback during the call to av_lockmgr_register(). * Thus, the application must be prepared to handle that. * If cb is set to NULL the lockmgr will be unregistered. * Also note that during unregistration the previously registered * lockmgr callback may also be invoked. */ int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op)); /** * Get the type of the given codec. */ enum AVMediaType avcodec_get_type(enum AVCodecID codec_id); /** * Get the name of a codec. * @return a static string identifying the codec; never NULL */ const char *avcodec_get_name(enum AVCodecID id); /** * @return a positive value if s is open (i.e. avcodec_open2() was called on it * with no corresponding avcodec_close()), 0 otherwise. */ int avcodec_is_open(AVCodecContext *s); /** * @return a non-zero number if codec is an encoder, zero otherwise */ int av_codec_is_encoder(const AVCodec *codec); /** * @return a non-zero number if codec is a decoder, zero otherwise */ int av_codec_is_decoder(const AVCodec *codec); /** * @return descriptor for given codec ID or NULL if no descriptor exists. */ const AVCodecDescriptor *avcodec_descriptor_get(enum AVCodecID id); /** * Iterate over all codec descriptors known to libavcodec. * * @param prev previous descriptor. NULL to get the first descriptor. * * @return next descriptor or NULL after the last descriptor */ const AVCodecDescriptor *avcodec_descriptor_next(const AVCodecDescriptor *prev); /** * @return codec descriptor with the given name or NULL if no such descriptor * exists. */ const AVCodecDescriptor *avcodec_descriptor_get_by_name(const char *name); /** * @} */ #endif /* AVCODEC_AVCODEC_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/avfft.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_AVFFT_H #define AVCODEC_AVFFT_H /** * @file * @ingroup lavc_fft * FFT functions */ /** * @defgroup lavc_fft FFT functions * @ingroup lavc_misc * * @{ */ typedef float FFTSample; typedef struct FFTComplex { FFTSample re, im; } FFTComplex; typedef struct FFTContext FFTContext; /** * Set up a complex FFT. * @param nbits log2 of the length of the input array * @param inverse if 0 perform the forward transform, if 1 perform the inverse */ FFTContext *av_fft_init(int nbits, int inverse); /** * Do the permutation needed BEFORE calling ff_fft_calc(). */ void av_fft_permute(FFTContext *s, FFTComplex *z); /** * Do a complex FFT with the parameters defined in av_fft_init(). The * input data must be permuted before. No 1.0/sqrt(n) normalization is done. */ void av_fft_calc(FFTContext *s, FFTComplex *z); void av_fft_end(FFTContext *s); FFTContext *av_mdct_init(int nbits, int inverse, double scale); void av_imdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input); void av_imdct_half(FFTContext *s, FFTSample *output, const FFTSample *input); void av_mdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input); void av_mdct_end(FFTContext *s); /* Real Discrete Fourier Transform */ enum RDFTransformType { DFT_R2C, IDFT_C2R, IDFT_R2C, DFT_C2R, }; typedef struct RDFTContext RDFTContext; /** * Set up a real FFT. * @param nbits log2 of the length of the input array * @param trans the type of transform */ RDFTContext *av_rdft_init(int nbits, enum RDFTransformType trans); void av_rdft_calc(RDFTContext *s, FFTSample *data); void av_rdft_end(RDFTContext *s); /* Discrete Cosine Transform */ typedef struct DCTContext DCTContext; enum DCTTransformType { DCT_II = 0, DCT_III, DCT_I, DST_I, }; /** * Set up DCT. * * @param nbits size of the input array: * (1 << nbits) for DCT-II, DCT-III and DST-I * (1 << nbits) + 1 for DCT-I * @param type the type of transform * * @note the first element of the input of DST-I is ignored */ DCTContext *av_dct_init(int nbits, enum DCTTransformType type); void av_dct_calc(DCTContext *s, FFTSample *data); void av_dct_end (DCTContext *s); /** * @} */ #endif /* AVCODEC_AVFFT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/dxva2.h ================================================ /* * DXVA2 HW acceleration * * copyright (c) 2009 Laurent Aimar * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_DXVA_H #define AVCODEC_DXVA_H /** * @file * @ingroup lavc_codec_hwaccel_dxva2 * Public libavcodec DXVA2 header. */ #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600 #undef _WIN32_WINNT #endif #if !defined(_WIN32_WINNT) #define _WIN32_WINNT 0x0600 #endif #include #include #include /** * @defgroup lavc_codec_hwaccel_dxva2 DXVA2 * @ingroup lavc_codec_hwaccel * * @{ */ #define FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG 1 ///< Work around for DXVA2 and old UVD/UVD+ ATI video cards /** * This structure is used to provides the necessary configurations and data * to the DXVA2 FFmpeg HWAccel implementation. * * The application must make it available as AVCodecContext.hwaccel_context. */ struct dxva_context { /** * DXVA2 decoder object */ IDirectXVideoDecoder *decoder; /** * DXVA2 configuration used to create the decoder */ const DXVA2_ConfigPictureDecode *cfg; /** * The number of surface in the surface array */ unsigned surface_count; /** * The array of Direct3D surfaces used to create the decoder */ LPDIRECT3DSURFACE9 *surface; /** * A bit field configuring the workarounds needed for using the decoder */ uint64_t workaround; /** * Private to the FFmpeg AVHWAccel implementation */ unsigned report_id; }; /** * @} */ #endif /* AVCODEC_DXVA_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/old_codec_ids.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_OLD_CODEC_IDS_H #define AVCODEC_OLD_CODEC_IDS_H #include "libavutil/common.h" /* * This header exists to prevent new codec IDs from being accidentally added to * the deprecated list. * Do not include it directly. It will be removed on next major bump * * Do not add new items to this list. Use the AVCodecID enum instead. */ CODEC_ID_NONE = AV_CODEC_ID_NONE, /* video codecs */ CODEC_ID_MPEG1VIDEO, CODEC_ID_MPEG2VIDEO, ///< preferred ID for MPEG-1/2 video decoding #if FF_API_XVMC CODEC_ID_MPEG2VIDEO_XVMC, #endif CODEC_ID_H261, CODEC_ID_H263, CODEC_ID_RV10, CODEC_ID_RV20, CODEC_ID_MJPEG, CODEC_ID_MJPEGB, CODEC_ID_LJPEG, CODEC_ID_SP5X, CODEC_ID_JPEGLS, CODEC_ID_MPEG4, CODEC_ID_RAWVIDEO, CODEC_ID_MSMPEG4V1, CODEC_ID_MSMPEG4V2, CODEC_ID_MSMPEG4V3, CODEC_ID_WMV1, CODEC_ID_WMV2, CODEC_ID_H263P, CODEC_ID_H263I, CODEC_ID_FLV1, CODEC_ID_SVQ1, CODEC_ID_SVQ3, CODEC_ID_DVVIDEO, CODEC_ID_HUFFYUV, CODEC_ID_CYUV, CODEC_ID_H264, CODEC_ID_INDEO3, CODEC_ID_VP3, CODEC_ID_THEORA, CODEC_ID_ASV1, CODEC_ID_ASV2, CODEC_ID_FFV1, CODEC_ID_4XM, CODEC_ID_VCR1, CODEC_ID_CLJR, CODEC_ID_MDEC, CODEC_ID_ROQ, CODEC_ID_INTERPLAY_VIDEO, CODEC_ID_XAN_WC3, CODEC_ID_XAN_WC4, CODEC_ID_RPZA, CODEC_ID_CINEPAK, CODEC_ID_WS_VQA, CODEC_ID_MSRLE, CODEC_ID_MSVIDEO1, CODEC_ID_IDCIN, CODEC_ID_8BPS, CODEC_ID_SMC, CODEC_ID_FLIC, CODEC_ID_TRUEMOTION1, CODEC_ID_VMDVIDEO, CODEC_ID_MSZH, CODEC_ID_ZLIB, CODEC_ID_QTRLE, CODEC_ID_TSCC, CODEC_ID_ULTI, CODEC_ID_QDRAW, CODEC_ID_VIXL, CODEC_ID_QPEG, CODEC_ID_PNG, CODEC_ID_PPM, CODEC_ID_PBM, CODEC_ID_PGM, CODEC_ID_PGMYUV, CODEC_ID_PAM, CODEC_ID_FFVHUFF, CODEC_ID_RV30, CODEC_ID_RV40, CODEC_ID_VC1, CODEC_ID_WMV3, CODEC_ID_LOCO, CODEC_ID_WNV1, CODEC_ID_AASC, CODEC_ID_INDEO2, CODEC_ID_FRAPS, CODEC_ID_TRUEMOTION2, CODEC_ID_BMP, CODEC_ID_CSCD, CODEC_ID_MMVIDEO, CODEC_ID_ZMBV, CODEC_ID_AVS, CODEC_ID_SMACKVIDEO, CODEC_ID_NUV, CODEC_ID_KMVC, CODEC_ID_FLASHSV, CODEC_ID_CAVS, CODEC_ID_JPEG2000, CODEC_ID_VMNC, CODEC_ID_VP5, CODEC_ID_VP6, CODEC_ID_VP6F, CODEC_ID_TARGA, CODEC_ID_DSICINVIDEO, CODEC_ID_TIERTEXSEQVIDEO, CODEC_ID_TIFF, CODEC_ID_GIF, CODEC_ID_DXA, CODEC_ID_DNXHD, CODEC_ID_THP, CODEC_ID_SGI, CODEC_ID_C93, CODEC_ID_BETHSOFTVID, CODEC_ID_PTX, CODEC_ID_TXD, CODEC_ID_VP6A, CODEC_ID_AMV, CODEC_ID_VB, CODEC_ID_PCX, CODEC_ID_SUNRAST, CODEC_ID_INDEO4, CODEC_ID_INDEO5, CODEC_ID_MIMIC, CODEC_ID_RL2, CODEC_ID_ESCAPE124, CODEC_ID_DIRAC, CODEC_ID_BFI, CODEC_ID_CMV, CODEC_ID_MOTIONPIXELS, CODEC_ID_TGV, CODEC_ID_TGQ, CODEC_ID_TQI, CODEC_ID_AURA, CODEC_ID_AURA2, CODEC_ID_V210X, CODEC_ID_TMV, CODEC_ID_V210, CODEC_ID_DPX, CODEC_ID_MAD, CODEC_ID_FRWU, CODEC_ID_FLASHSV2, CODEC_ID_CDGRAPHICS, CODEC_ID_R210, CODEC_ID_ANM, CODEC_ID_BINKVIDEO, CODEC_ID_IFF_ILBM, CODEC_ID_IFF_BYTERUN1, CODEC_ID_KGV1, CODEC_ID_YOP, CODEC_ID_VP8, CODEC_ID_PICTOR, CODEC_ID_ANSI, CODEC_ID_A64_MULTI, CODEC_ID_A64_MULTI5, CODEC_ID_R10K, CODEC_ID_MXPEG, CODEC_ID_LAGARITH, CODEC_ID_PRORES, CODEC_ID_JV, CODEC_ID_DFA, CODEC_ID_WMV3IMAGE, CODEC_ID_VC1IMAGE, CODEC_ID_UTVIDEO, CODEC_ID_BMV_VIDEO, CODEC_ID_VBLE, CODEC_ID_DXTORY, CODEC_ID_V410, CODEC_ID_XWD, CODEC_ID_CDXL, CODEC_ID_XBM, CODEC_ID_ZEROCODEC, CODEC_ID_MSS1, CODEC_ID_MSA1, CODEC_ID_TSCC2, CODEC_ID_MTS2, CODEC_ID_CLLC, CODEC_ID_Y41P = MKBETAG('Y','4','1','P'), CODEC_ID_ESCAPE130 = MKBETAG('E','1','3','0'), CODEC_ID_EXR = MKBETAG('0','E','X','R'), CODEC_ID_AVRP = MKBETAG('A','V','R','P'), CODEC_ID_G2M = MKBETAG( 0 ,'G','2','M'), CODEC_ID_AVUI = MKBETAG('A','V','U','I'), CODEC_ID_AYUV = MKBETAG('A','Y','U','V'), CODEC_ID_V308 = MKBETAG('V','3','0','8'), CODEC_ID_V408 = MKBETAG('V','4','0','8'), CODEC_ID_YUV4 = MKBETAG('Y','U','V','4'), CODEC_ID_SANM = MKBETAG('S','A','N','M'), CODEC_ID_PAF_VIDEO = MKBETAG('P','A','F','V'), CODEC_ID_SNOW = AV_CODEC_ID_SNOW, /* various PCM "codecs" */ CODEC_ID_FIRST_AUDIO = 0x10000, ///< A dummy id pointing at the start of audio codecs CODEC_ID_PCM_S16LE = 0x10000, CODEC_ID_PCM_S16BE, CODEC_ID_PCM_U16LE, CODEC_ID_PCM_U16BE, CODEC_ID_PCM_S8, CODEC_ID_PCM_U8, CODEC_ID_PCM_MULAW, CODEC_ID_PCM_ALAW, CODEC_ID_PCM_S32LE, CODEC_ID_PCM_S32BE, CODEC_ID_PCM_U32LE, CODEC_ID_PCM_U32BE, CODEC_ID_PCM_S24LE, CODEC_ID_PCM_S24BE, CODEC_ID_PCM_U24LE, CODEC_ID_PCM_U24BE, CODEC_ID_PCM_S24DAUD, CODEC_ID_PCM_ZORK, CODEC_ID_PCM_S16LE_PLANAR, CODEC_ID_PCM_DVD, CODEC_ID_PCM_F32BE, CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F64BE, CODEC_ID_PCM_F64LE, CODEC_ID_PCM_BLURAY, CODEC_ID_PCM_LXF, CODEC_ID_S302M, CODEC_ID_PCM_S8_PLANAR, /* various ADPCM codecs */ CODEC_ID_ADPCM_IMA_QT = 0x11000, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_IMA_DK3, CODEC_ID_ADPCM_IMA_DK4, CODEC_ID_ADPCM_IMA_WS, CODEC_ID_ADPCM_IMA_SMJPEG, CODEC_ID_ADPCM_MS, CODEC_ID_ADPCM_4XM, CODEC_ID_ADPCM_XA, CODEC_ID_ADPCM_ADX, CODEC_ID_ADPCM_EA, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_CT, CODEC_ID_ADPCM_SWF, CODEC_ID_ADPCM_YAMAHA, CODEC_ID_ADPCM_SBPRO_4, CODEC_ID_ADPCM_SBPRO_3, CODEC_ID_ADPCM_SBPRO_2, CODEC_ID_ADPCM_THP, CODEC_ID_ADPCM_IMA_AMV, CODEC_ID_ADPCM_EA_R1, CODEC_ID_ADPCM_EA_R3, CODEC_ID_ADPCM_EA_R2, CODEC_ID_ADPCM_IMA_EA_SEAD, CODEC_ID_ADPCM_IMA_EA_EACS, CODEC_ID_ADPCM_EA_XAS, CODEC_ID_ADPCM_EA_MAXIS_XA, CODEC_ID_ADPCM_IMA_ISS, CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_IMA_APC, CODEC_ID_VIMA = MKBETAG('V','I','M','A'), /* AMR */ CODEC_ID_AMR_NB = 0x12000, CODEC_ID_AMR_WB, /* RealAudio codecs*/ CODEC_ID_RA_144 = 0x13000, CODEC_ID_RA_288, /* various DPCM codecs */ CODEC_ID_ROQ_DPCM = 0x14000, CODEC_ID_INTERPLAY_DPCM, CODEC_ID_XAN_DPCM, CODEC_ID_SOL_DPCM, /* audio codecs */ CODEC_ID_MP2 = 0x15000, CODEC_ID_MP3, ///< preferred ID for decoding MPEG audio layer 1, 2 or 3 CODEC_ID_AAC, CODEC_ID_AC3, CODEC_ID_DTS, CODEC_ID_VORBIS, CODEC_ID_DVAUDIO, CODEC_ID_WMAV1, CODEC_ID_WMAV2, CODEC_ID_MACE3, CODEC_ID_MACE6, CODEC_ID_VMDAUDIO, CODEC_ID_FLAC, CODEC_ID_MP3ADU, CODEC_ID_MP3ON4, CODEC_ID_SHORTEN, CODEC_ID_ALAC, CODEC_ID_WESTWOOD_SND1, CODEC_ID_GSM, ///< as in Berlin toast format CODEC_ID_QDM2, CODEC_ID_COOK, CODEC_ID_TRUESPEECH, CODEC_ID_TTA, CODEC_ID_SMACKAUDIO, CODEC_ID_QCELP, CODEC_ID_WAVPACK, CODEC_ID_DSICINAUDIO, CODEC_ID_IMC, CODEC_ID_MUSEPACK7, CODEC_ID_MLP, CODEC_ID_GSM_MS, /* as found in WAV */ CODEC_ID_ATRAC3, CODEC_ID_VOXWARE, CODEC_ID_APE, CODEC_ID_NELLYMOSER, CODEC_ID_MUSEPACK8, CODEC_ID_SPEEX, CODEC_ID_WMAVOICE, CODEC_ID_WMAPRO, CODEC_ID_WMALOSSLESS, CODEC_ID_ATRAC3P, CODEC_ID_EAC3, CODEC_ID_SIPR, CODEC_ID_MP1, CODEC_ID_TWINVQ, CODEC_ID_TRUEHD, CODEC_ID_MP4ALS, CODEC_ID_ATRAC1, CODEC_ID_BINKAUDIO_RDFT, CODEC_ID_BINKAUDIO_DCT, CODEC_ID_AAC_LATM, CODEC_ID_QDMC, CODEC_ID_CELT, CODEC_ID_G723_1, CODEC_ID_G729, CODEC_ID_8SVX_EXP, CODEC_ID_8SVX_FIB, CODEC_ID_BMV_AUDIO, CODEC_ID_RALF, CODEC_ID_IAC, CODEC_ID_ILBC, CODEC_ID_FFWAVESYNTH = MKBETAG('F','F','W','S'), CODEC_ID_SONIC = MKBETAG('S','O','N','C'), CODEC_ID_SONIC_LS = MKBETAG('S','O','N','L'), CODEC_ID_PAF_AUDIO = MKBETAG('P','A','F','A'), CODEC_ID_OPUS = MKBETAG('O','P','U','S'), /* subtitle codecs */ CODEC_ID_FIRST_SUBTITLE = 0x17000, ///< A dummy ID pointing at the start of subtitle codecs. CODEC_ID_DVD_SUBTITLE = 0x17000, CODEC_ID_DVB_SUBTITLE, CODEC_ID_TEXT, ///< raw UTF-8 text CODEC_ID_XSUB, CODEC_ID_SSA, CODEC_ID_MOV_TEXT, CODEC_ID_HDMV_PGS_SUBTITLE, CODEC_ID_DVB_TELETEXT, CODEC_ID_SRT, CODEC_ID_MICRODVD = MKBETAG('m','D','V','D'), CODEC_ID_EIA_608 = MKBETAG('c','6','0','8'), CODEC_ID_JACOSUB = MKBETAG('J','S','U','B'), CODEC_ID_SAMI = MKBETAG('S','A','M','I'), CODEC_ID_REALTEXT = MKBETAG('R','T','X','T'), CODEC_ID_SUBVIEWER = MKBETAG('S','u','b','V'), /* other specific kind of codecs (generally used for attachments) */ CODEC_ID_FIRST_UNKNOWN = 0x18000, ///< A dummy ID pointing at the start of various fake codecs. CODEC_ID_TTF = 0x18000, CODEC_ID_BINTEXT = MKBETAG('B','T','X','T'), CODEC_ID_XBIN = MKBETAG('X','B','I','N'), CODEC_ID_IDF = MKBETAG( 0 ,'I','D','F'), CODEC_ID_OTF = MKBETAG( 0 ,'O','T','F'), CODEC_ID_PROBE = 0x19000, ///< codec_id is not known (like CODEC_ID_NONE) but lavf should attempt to identify it CODEC_ID_MPEG2TS = 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS * stream (only used by libavformat) */ CODEC_ID_MPEG4SYSTEMS = 0x20001, /**< _FAKE_ codec to indicate a MPEG-4 Systems * stream (only used by libavformat) */ CODEC_ID_FFMETADATA = 0x21000, ///< Dummy codec for streams containing only metadata information. #endif /* AVCODEC_OLD_CODEC_IDS_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/vaapi.h ================================================ /* * Video Acceleration API (shared data between FFmpeg and the video player) * HW decode acceleration for MPEG-2, MPEG-4, H.264 and VC-1 * * Copyright (C) 2008-2009 Splitted-Desktop Systems * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VAAPI_H #define AVCODEC_VAAPI_H /** * @file * @ingroup lavc_codec_hwaccel_vaapi * Public libavcodec VA API header. */ #include /** * @defgroup lavc_codec_hwaccel_vaapi VA API Decoding * @ingroup lavc_codec_hwaccel * @{ */ /** * This structure is used to share data between the FFmpeg library and * the client video application. * This shall be zero-allocated and available as * AVCodecContext.hwaccel_context. All user members can be set once * during initialization or through each AVCodecContext.get_buffer() * function call. In any case, they must be valid prior to calling * decoding functions. */ struct vaapi_context { /** * Window system dependent data * * - encoding: unused * - decoding: Set by user */ void *display; /** * Configuration ID * * - encoding: unused * - decoding: Set by user */ uint32_t config_id; /** * Context ID (video decode pipeline) * * - encoding: unused * - decoding: Set by user */ uint32_t context_id; /** * VAPictureParameterBuffer ID * * - encoding: unused * - decoding: Set by libavcodec */ uint32_t pic_param_buf_id; /** * VAIQMatrixBuffer ID * * - encoding: unused * - decoding: Set by libavcodec */ uint32_t iq_matrix_buf_id; /** * VABitPlaneBuffer ID (for VC-1 decoding) * * - encoding: unused * - decoding: Set by libavcodec */ uint32_t bitplane_buf_id; /** * Slice parameter/data buffer IDs * * - encoding: unused * - decoding: Set by libavcodec */ uint32_t *slice_buf_ids; /** * Number of effective slice buffer IDs to send to the HW * * - encoding: unused * - decoding: Set by libavcodec */ unsigned int n_slice_buf_ids; /** * Size of pre-allocated slice_buf_ids * * - encoding: unused * - decoding: Set by libavcodec */ unsigned int slice_buf_ids_alloc; /** * Pointer to VASliceParameterBuffers * * - encoding: unused * - decoding: Set by libavcodec */ void *slice_params; /** * Size of a VASliceParameterBuffer element * * - encoding: unused * - decoding: Set by libavcodec */ unsigned int slice_param_size; /** * Size of pre-allocated slice_params * * - encoding: unused * - decoding: Set by libavcodec */ unsigned int slice_params_alloc; /** * Number of slices currently filled in * * - encoding: unused * - decoding: Set by libavcodec */ unsigned int slice_count; /** * Pointer to slice data buffer base * - encoding: unused * - decoding: Set by libavcodec */ const uint8_t *slice_data; /** * Current size of slice data * * - encoding: unused * - decoding: Set by libavcodec */ uint32_t slice_data_size; }; /* @} */ #endif /* AVCODEC_VAAPI_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/vda.h ================================================ /* * VDA HW acceleration * * copyright (c) 2011 Sebastien Zwickert * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VDA_H #define AVCODEC_VDA_H /** * @file * @ingroup lavc_codec_hwaccel_vda * Public libavcodec VDA header. */ #include // emmintrin.h is unable to compile with -std=c99 -Werror=missing-prototypes // http://openradar.appspot.com/8026390 #undef __GNUC_STDC_INLINE__ #define Picture QuickdrawPicture #include #undef Picture #include "libavcodec/version.h" // extra flags not defined in VDADecoder.h enum { kVDADecodeInfo_Asynchronous = 1UL << 0, kVDADecodeInfo_FrameDropped = 1UL << 1 }; /** * @defgroup lavc_codec_hwaccel_vda VDA * @ingroup lavc_codec_hwaccel * * @{ */ /** * This structure is used to provide the necessary configurations and data * to the VDA FFmpeg HWAccel implementation. * * The application must make it available as AVCodecContext.hwaccel_context. */ struct vda_context { /** * VDA decoder object. * * - encoding: unused * - decoding: Set/Unset by libavcodec. */ VDADecoder decoder; /** * The Core Video pixel buffer that contains the current image data. * * encoding: unused * decoding: Set by libavcodec. Unset by user. */ CVPixelBufferRef cv_buffer; /** * Use the hardware decoder in synchronous mode. * * encoding: unused * decoding: Set by user. */ int use_sync_decoding; /** * The frame width. * * - encoding: unused * - decoding: Set/Unset by user. */ int width; /** * The frame height. * * - encoding: unused * - decoding: Set/Unset by user. */ int height; /** * The frame format. * * - encoding: unused * - decoding: Set/Unset by user. */ int format; /** * The pixel format for output image buffers. * * - encoding: unused * - decoding: Set/Unset by user. */ OSType cv_pix_fmt_type; /** * The current bitstream buffer. * * - encoding: unused * - decoding: Set/Unset by libavcodec. */ uint8_t *priv_bitstream; /** * The current size of the bitstream. * * - encoding: unused * - decoding: Set/Unset by libavcodec. */ int priv_bitstream_size; /** * The reference size used for fast reallocation. * * - encoding: unused * - decoding: Set/Unset by libavcodec. */ int priv_allocated_size; /** * Use av_buffer to manage buffer. * When the flag is set, the CVPixelBuffers returned by the decoder will * be released automatically, so you have to retain them if necessary. * Not setting this flag may cause memory leak. * * encoding: unused * decoding: Set by user. */ int use_ref_buffer; }; /** Create the video decoder. */ int ff_vda_create_decoder(struct vda_context *vda_ctx, uint8_t *extradata, int extradata_size); /** Destroy the video decoder. */ int ff_vda_destroy_decoder(struct vda_context *vda_ctx); /** * @} */ #endif /* AVCODEC_VDA_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/vdpau.h ================================================ /* * The Video Decode and Presentation API for UNIX (VDPAU) is used for * hardware-accelerated decoding of MPEG-1/2, H.264 and VC-1. * * Copyright (C) 2008 NVIDIA * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VDPAU_H #define AVCODEC_VDPAU_H /** * @file * @ingroup lavc_codec_hwaccel_vdpau * Public libavcodec VDPAU header. */ /** * @defgroup lavc_codec_hwaccel_vdpau VDPAU Decoder and Renderer * @ingroup lavc_codec_hwaccel * * VDPAU hardware acceleration has two modules * - VDPAU decoding * - VDPAU presentation * * The VDPAU decoding module parses all headers using FFmpeg * parsing mechanisms and uses VDPAU for the actual decoding. * * As per the current implementation, the actual decoding * and rendering (API calls) are done as part of the VDPAU * presentation (vo_vdpau.c) module. * * @{ */ #include #include #include "libavutil/avconfig.h" #include "libavutil/attributes.h" #include "avcodec.h" #include "version.h" #if FF_API_BUFS_VDPAU union AVVDPAUPictureInfo { VdpPictureInfoH264 h264; VdpPictureInfoMPEG1Or2 mpeg; VdpPictureInfoVC1 vc1; VdpPictureInfoMPEG4Part2 mpeg4; }; #endif struct AVCodecContext; struct AVFrame; typedef int (*AVVDPAU_Render2)(struct AVCodecContext *, struct AVFrame *, const VdpPictureInfo *, uint32_t, const VdpBitstreamBuffer *); /** * This structure is used to share data between the libavcodec library and * the client video application. * The user shall allocate the structure via the av_alloc_vdpau_hwaccel * function and make it available as * AVCodecContext.hwaccel_context. Members can be set by the user once * during initialization or through each AVCodecContext.get_buffer() * function call. In any case, they must be valid prior to calling * decoding functions. * * The size of this structure is not a part of the public ABI and must not * be used outside of libavcodec. Use av_vdpau_alloc_context() to allocate an * AVVDPAUContext. */ typedef struct AVVDPAUContext { /** * VDPAU decoder handle * * Set by user. */ VdpDecoder decoder; /** * VDPAU decoder render callback * * Set by the user. */ VdpDecoderRender *render; #if FF_API_BUFS_VDPAU /** * VDPAU picture information * * Set by libavcodec. */ attribute_deprecated union AVVDPAUPictureInfo info; /** * Allocated size of the bitstream_buffers table. * * Set by libavcodec. */ attribute_deprecated int bitstream_buffers_allocated; /** * Useful bitstream buffers in the bitstream buffers table. * * Set by libavcodec. */ attribute_deprecated int bitstream_buffers_used; /** * Table of bitstream buffers. * The user is responsible for freeing this buffer using av_freep(). * * Set by libavcodec. */ attribute_deprecated VdpBitstreamBuffer *bitstream_buffers; #endif AVVDPAU_Render2 render2; } AVVDPAUContext; /** * @brief allocation function for AVVDPAUContext * * Allows extending the struct without breaking API/ABI */ AVVDPAUContext *av_alloc_vdpaucontext(void); AVVDPAU_Render2 av_vdpau_hwaccel_get_render2(const AVVDPAUContext *); void av_vdpau_hwaccel_set_render2(AVVDPAUContext *, AVVDPAU_Render2); /** * Allocate an AVVDPAUContext. * * @return Newly-allocated AVVDPAUContext or NULL on failure. */ AVVDPAUContext *av_vdpau_alloc_context(void); /** * Get a decoder profile that should be used for initializing a VDPAU decoder. * Should be called from the AVCodecContext.get_format() callback. * * @param avctx the codec context being used for decoding the stream * @param profile a pointer into which the result will be written on success. * The contents of profile are undefined if this function returns * an error. * * @return 0 on success (non-negative), a negative AVERROR on failure. */ int av_vdpau_get_profile(AVCodecContext *avctx, VdpDecoderProfile *profile); #if FF_API_CAP_VDPAU /** @brief The videoSurface is used for rendering. */ #define FF_VDPAU_STATE_USED_FOR_RENDER 1 /** * @brief The videoSurface is needed for reference/prediction. * The codec manipulates this. */ #define FF_VDPAU_STATE_USED_FOR_REFERENCE 2 /** * @brief This structure is used as a callback between the FFmpeg * decoder (vd_) and presentation (vo_) module. * This is used for defining a video frame containing surface, * picture parameter, bitstream information etc which are passed * between the FFmpeg decoder and its clients. */ struct vdpau_render_state { VdpVideoSurface surface; ///< Used as rendered surface, never changed. int state; ///< Holds FF_VDPAU_STATE_* values. #if AV_HAVE_INCOMPATIBLE_LIBAV_ABI /** picture parameter information for all supported codecs */ union AVVDPAUPictureInfo info; #endif /** Describe size/location of the compressed video data. Set to 0 when freeing bitstream_buffers. */ int bitstream_buffers_allocated; int bitstream_buffers_used; /** The user is responsible for freeing this buffer using av_freep(). */ VdpBitstreamBuffer *bitstream_buffers; #if !AV_HAVE_INCOMPATIBLE_LIBAV_ABI /** picture parameter information for all supported codecs */ union AVVDPAUPictureInfo info; #endif }; #endif /* @}*/ #endif /* AVCODEC_VDPAU_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/version.h ================================================ /* * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VERSION_H #define AVCODEC_VERSION_H /** * @file * @ingroup libavc * Libavcodec version macros. */ #include "libavutil/version.h" #define LIBAVCODEC_VERSION_MAJOR 55 #define LIBAVCODEC_VERSION_MINOR 52 #define LIBAVCODEC_VERSION_MICRO 102 #define LIBAVCODEC_VERSION_INT AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \ LIBAVCODEC_VERSION_MINOR, \ LIBAVCODEC_VERSION_MICRO) #define LIBAVCODEC_VERSION AV_VERSION(LIBAVCODEC_VERSION_MAJOR, \ LIBAVCODEC_VERSION_MINOR, \ LIBAVCODEC_VERSION_MICRO) #define LIBAVCODEC_BUILD LIBAVCODEC_VERSION_INT #define LIBAVCODEC_IDENT "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #ifndef FF_API_REQUEST_CHANNELS #define FF_API_REQUEST_CHANNELS (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_OLD_DECODE_AUDIO #define FF_API_OLD_DECODE_AUDIO (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_OLD_ENCODE_AUDIO #define FF_API_OLD_ENCODE_AUDIO (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_OLD_ENCODE_VIDEO #define FF_API_OLD_ENCODE_VIDEO (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_CODEC_ID #define FF_API_CODEC_ID (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_AUDIO_CONVERT #define FF_API_AUDIO_CONVERT (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_AVCODEC_RESAMPLE #define FF_API_AVCODEC_RESAMPLE FF_API_AUDIO_CONVERT #endif #ifndef FF_API_DEINTERLACE #define FF_API_DEINTERLACE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_DESTRUCT_PACKET #define FF_API_DESTRUCT_PACKET (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_GET_BUFFER #define FF_API_GET_BUFFER (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_MISSING_SAMPLE #define FF_API_MISSING_SAMPLE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_LOWRES #define FF_API_LOWRES (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_CAP_VDPAU #define FF_API_CAP_VDPAU (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_BUFS_VDPAU #define FF_API_BUFS_VDPAU (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_VOXWARE #define FF_API_VOXWARE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_SET_DIMENSIONS #define FF_API_SET_DIMENSIONS (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_DEBUG_MV #define FF_API_DEBUG_MV (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_AC_VLC #define FF_API_AC_VLC (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_OLD_MSMPEG4 #define FF_API_OLD_MSMPEG4 (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_ASPECT_EXTENDED #define FF_API_ASPECT_EXTENDED (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_THREAD_OPAQUE #define FF_API_THREAD_OPAQUE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_CODEC_PKT #define FF_API_CODEC_PKT (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_ARCH_ALPHA #define FF_API_ARCH_ALPHA (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_XVMC #define FF_API_XVMC (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_ERROR_RATE #define FF_API_ERROR_RATE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_QSCALE_TYPE #define FF_API_QSCALE_TYPE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_MB_TYPE #define FF_API_MB_TYPE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_MAX_BFRAMES #define FF_API_MAX_BFRAMES (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_FAST_MALLOC #define FF_API_FAST_MALLOC (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_NEG_LINESIZES #define FF_API_NEG_LINESIZES (LIBAVCODEC_VERSION_MAJOR < 56) #endif #ifndef FF_API_EMU_EDGE #define FF_API_EMU_EDGE (LIBAVCODEC_VERSION_MAJOR < 56) #endif #endif /* AVCODEC_VERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavcodec/xvmc.h ================================================ /* * Copyright (C) 2003 Ivan Kalvachev * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_XVMC_H #define AVCODEC_XVMC_H /** * @file * @ingroup lavc_codec_hwaccel_xvmc * Public libavcodec XvMC header. */ #include #include "libavutil/attributes.h" #include "version.h" #include "avcodec.h" /** * @defgroup lavc_codec_hwaccel_xvmc XvMC * @ingroup lavc_codec_hwaccel * * @{ */ #define AV_XVMC_ID 0x1DC711C0 /**< special value to ensure that regular pixel routines haven't corrupted the struct the number is 1337 speak for the letters IDCT MCo (motion compensation) */ attribute_deprecated struct xvmc_pix_fmt { /** The field contains the special constant value AV_XVMC_ID. It is used as a test that the application correctly uses the API, and that there is no corruption caused by pixel routines. - application - set during initialization - libavcodec - unchanged */ int xvmc_id; /** Pointer to the block array allocated by XvMCCreateBlocks(). The array has to be freed by XvMCDestroyBlocks(). Each group of 64 values represents one data block of differential pixel information (in MoCo mode) or coefficients for IDCT. - application - set the pointer during initialization - libavcodec - fills coefficients/pixel data into the array */ short* data_blocks; /** Pointer to the macroblock description array allocated by XvMCCreateMacroBlocks() and freed by XvMCDestroyMacroBlocks(). - application - set the pointer during initialization - libavcodec - fills description data into the array */ XvMCMacroBlock* mv_blocks; /** Number of macroblock descriptions that can be stored in the mv_blocks array. - application - set during initialization - libavcodec - unchanged */ int allocated_mv_blocks; /** Number of blocks that can be stored at once in the data_blocks array. - application - set during initialization - libavcodec - unchanged */ int allocated_data_blocks; /** Indicate that the hardware would interpret data_blocks as IDCT coefficients and perform IDCT on them. - application - set during initialization - libavcodec - unchanged */ int idct; /** In MoCo mode it indicates that intra macroblocks are assumed to be in unsigned format; same as the XVMC_INTRA_UNSIGNED flag. - application - set during initialization - libavcodec - unchanged */ int unsigned_intra; /** Pointer to the surface allocated by XvMCCreateSurface(). It has to be freed by XvMCDestroySurface() on application exit. It identifies the frame and its state on the video hardware. - application - set during initialization - libavcodec - unchanged */ XvMCSurface* p_surface; /** Set by the decoder before calling ff_draw_horiz_band(), needed by the XvMCRenderSurface function. */ //@{ /** Pointer to the surface used as past reference - application - unchanged - libavcodec - set */ XvMCSurface* p_past_surface; /** Pointer to the surface used as future reference - application - unchanged - libavcodec - set */ XvMCSurface* p_future_surface; /** top/bottom field or frame - application - unchanged - libavcodec - set */ unsigned int picture_structure; /** XVMC_SECOND_FIELD - 1st or 2nd field in the sequence - application - unchanged - libavcodec - set */ unsigned int flags; //}@ /** Number of macroblock descriptions in the mv_blocks array that have already been passed to the hardware. - application - zeroes it on get_buffer(). A successful ff_draw_horiz_band() may increment it with filled_mb_block_num or zero both. - libavcodec - unchanged */ int start_mv_blocks_num; /** Number of new macroblock descriptions in the mv_blocks array (after start_mv_blocks_num) that are filled by libavcodec and have to be passed to the hardware. - application - zeroes it on get_buffer() or after successful ff_draw_horiz_band(). - libavcodec - increment with one of each stored MB */ int filled_mv_blocks_num; /** Number of the next free data block; one data block consists of 64 short values in the data_blocks array. All blocks before this one have already been claimed by placing their position into the corresponding block description structure field, that are part of the mv_blocks array. - application - zeroes it on get_buffer(). A successful ff_draw_horiz_band() may zero it together with start_mb_blocks_num. - libavcodec - each decoded macroblock increases it by the number of coded blocks it contains. */ int next_free_data_block_num; }; /** * @} */ #endif /* AVCODEC_XVMC_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavdevice/avdevice.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVDEVICE_AVDEVICE_H #define AVDEVICE_AVDEVICE_H #include "version.h" /** * @file * @ingroup lavd * Main libavdevice API header */ /** * @defgroup lavd Special devices muxing/demuxing library * @{ * Libavdevice is a complementary library to @ref libavf "libavformat". It * provides various "special" platform-specific muxers and demuxers, e.g. for * grabbing devices, audio capture and playback etc. As a consequence, the * (de)muxers in libavdevice are of the AVFMT_NOFILE type (they use their own * I/O functions). The filename passed to avformat_open_input() often does not * refer to an actually existing file, but has some special device-specific * meaning - e.g. for x11grab it is the display name. * * To use libavdevice, simply call avdevice_register_all() to register all * compiled muxers and demuxers. They all use standard libavformat API. * @} */ #include "libavformat/avformat.h" /** * Return the LIBAVDEVICE_VERSION_INT constant. */ unsigned avdevice_version(void); /** * Return the libavdevice build-time configuration. */ const char *avdevice_configuration(void); /** * Return the libavdevice license. */ const char *avdevice_license(void); /** * Initialize libavdevice and register all the input and output devices. * @warning This function is not thread safe. */ void avdevice_register_all(void); typedef struct AVDeviceRect { int x; /**< x coordinate of top left corner */ int y; /**< y coordinate of top left corner */ int width; /**< width */ int height; /**< height */ } AVDeviceRect; /** * Message types used by avdevice_app_to_dev_control_message(). */ enum AVAppToDevMessageType { /** * Dummy message. */ AV_APP_TO_DEV_NONE = MKBETAG('N','O','N','E'), /** * Window size change message. * * Message is sent to the device every time the application changes the size * of the window device renders to. * Message should also be sent right after window is created. * * data: AVDeviceRect: new window size. */ AV_APP_TO_DEV_WINDOW_SIZE = MKBETAG('G','E','O','M'), /** * Repaint request message. * * Message is sent to the device when window have to be rapainted. * * data: AVDeviceRect: area required to be repainted. * NULL: whole area is required to be repainted. */ AV_APP_TO_DEV_WINDOW_REPAINT = MKBETAG('R','E','P','A') }; /** * Message types used by avdevice_dev_to_app_control_message(). */ enum AVDevToAppMessageType { /** * Dummy message. */ AV_DEV_TO_APP_NONE = MKBETAG('N','O','N','E'), /** * Create window buffer message. * * Device requests to create a window buffer. Exact meaning is device- * and application-dependent. Message is sent before rendering first * frame and all one-shot initializations should be done here. * Application is allowed to ignore preferred window buffer size. * * @note: Application is obligated to inform about window buffer size * with AV_APP_TO_DEV_WINDOW_SIZE message. * * data: AVDeviceRect: preferred size of the window buffer. * NULL: no preferred size of the window buffer. */ AV_DEV_TO_APP_CREATE_WINDOW_BUFFER = MKBETAG('B','C','R','E'), /** * Prepare window buffer message. * * Device requests to prepare a window buffer for rendering. * Exact meaning is device- and application-dependent. * Message is sent before rendering of each frame. * * data: NULL. */ AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER = MKBETAG('B','P','R','E'), /** * Display window buffer message. * * Device requests to display a window buffer. * Message is sent when new frame is ready to be displyed. * Usually buffers need to be swapped in handler of this message. * * data: NULL. */ AV_DEV_TO_APP_DISPLAY_WINDOW_BUFFER = MKBETAG('B','D','I','S'), /** * Destroy window buffer message. * * Device requests to destroy a window buffer. * Message is sent when device is about to be destroyed and window * buffer is not required anymore. * * data: NULL. */ AV_DEV_TO_APP_DESTROY_WINDOW_BUFFER = MKBETAG('B','D','E','S') }; /** * Send control message from application to device. * * @param s device context. * @param type message type. * @param data message data. Exact type depends on message type. * @param data_size size of message data. * @return >= 0 on success, negative on error. * AVERROR(ENOSYS) when device doesn't implement handler of the message. */ int avdevice_app_to_dev_control_message(struct AVFormatContext *s, enum AVAppToDevMessageType type, void *data, size_t data_size); /** * Send control message from device to application. * * @param s device context. * @param type message type. * @param data message data. Can be NULL. * @param data_size size of message data. * @return >= 0 on success, negative on error. * AVERROR(ENOSYS) when application doesn't implement handler of the message. */ int avdevice_dev_to_app_control_message(struct AVFormatContext *s, enum AVDevToAppMessageType type, void *data, size_t data_size); /** * Structure describes basic parameters of the device. */ typedef struct AVDeviceInfo { char *device_name; /**< device name, format depends on device */ char *device_description; /**< human friendly name */ } AVDeviceInfo; /** * List of devices. */ typedef struct AVDeviceInfoList { AVDeviceInfo **devices; /**< list of autodetected devices */ int nb_devices; /**< number of autodetected devices */ int default_device; /**< index of default device or -1 if no default */ } AVDeviceInfoList; /** * List devices. * * Returns available device names and their parameters. * * @note: Some devices may accept system-dependent device names that cannot be * autodetected. The list returned by this function cannot be assumed to * be always completed. * * @param s device context. * @param[out] device_list list of autodetected devices. * @return count of autodetected devices, negative on error. */ int avdevice_list_devices(struct AVFormatContext *s, AVDeviceInfoList **device_list); /** * Convinient function to free result of avdevice_list_devices(). * * @param devices device list to be freed. */ void avdevice_free_list_devices(AVDeviceInfoList **device_list); #endif /* AVDEVICE_AVDEVICE_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavdevice/version.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVDEVICE_VERSION_H #define AVDEVICE_VERSION_H /** * @file * @ingroup lavd * Libavdevice version macros */ #include "libavutil/version.h" #define LIBAVDEVICE_VERSION_MAJOR 55 #define LIBAVDEVICE_VERSION_MINOR 10 #define LIBAVDEVICE_VERSION_MICRO 100 #define LIBAVDEVICE_VERSION_INT AV_VERSION_INT(LIBAVDEVICE_VERSION_MAJOR, \ LIBAVDEVICE_VERSION_MINOR, \ LIBAVDEVICE_VERSION_MICRO) #define LIBAVDEVICE_VERSION AV_VERSION(LIBAVDEVICE_VERSION_MAJOR, \ LIBAVDEVICE_VERSION_MINOR, \ LIBAVDEVICE_VERSION_MICRO) #define LIBAVDEVICE_BUILD LIBAVDEVICE_VERSION_INT #define LIBAVDEVICE_IDENT "Lavd" AV_STRINGIFY(LIBAVDEVICE_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #endif /* AVDEVICE_VERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavfilter/asrc_abuffer.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_ASRC_ABUFFER_H #define AVFILTER_ASRC_ABUFFER_H #include "avfilter.h" /** * @file * memory buffer source for audio * * @deprecated use buffersrc.h instead. */ /** * Queue an audio buffer to the audio buffer source. * * @param abuffersrc audio source buffer context * @param data pointers to the samples planes * @param linesize linesizes of each audio buffer plane * @param nb_samples number of samples per channel * @param sample_fmt sample format of the audio data * @param ch_layout channel layout of the audio data * @param planar flag to indicate if audio data is planar or packed * @param pts presentation timestamp of the audio buffer * @param flags unused * * @deprecated use av_buffersrc_add_ref() instead. */ attribute_deprecated int av_asrc_buffer_add_samples(AVFilterContext *abuffersrc, uint8_t *data[8], int linesize[8], int nb_samples, int sample_rate, int sample_fmt, int64_t ch_layout, int planar, int64_t pts, int av_unused flags); /** * Queue an audio buffer to the audio buffer source. * * This is similar to av_asrc_buffer_add_samples(), but the samples * are stored in a buffer with known size. * * @param abuffersrc audio source buffer context * @param buf pointer to the samples data, packed is assumed * @param size the size in bytes of the buffer, it must contain an * integer number of samples * @param sample_fmt sample format of the audio data * @param ch_layout channel layout of the audio data * @param pts presentation timestamp of the audio buffer * @param flags unused * * @deprecated use av_buffersrc_add_ref() instead. */ attribute_deprecated int av_asrc_buffer_add_buffer(AVFilterContext *abuffersrc, uint8_t *buf, int buf_size, int sample_rate, int sample_fmt, int64_t ch_layout, int planar, int64_t pts, int av_unused flags); /** * Queue an audio buffer to the audio buffer source. * * @param abuffersrc audio source buffer context * @param samplesref buffer ref to queue * @param flags unused * * @deprecated use av_buffersrc_add_ref() instead. */ attribute_deprecated int av_asrc_buffer_add_audio_buffer_ref(AVFilterContext *abuffersrc, AVFilterBufferRef *samplesref, int av_unused flags); #endif /* AVFILTER_ASRC_ABUFFER_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavfilter/avcodec.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_AVCODEC_H #define AVFILTER_AVCODEC_H /** * @file * libavcodec/libavfilter gluing utilities * * This should be included in an application ONLY if the installed * libavfilter has been compiled with libavcodec support, otherwise * symbols defined below will not be available. */ #include "avfilter.h" #if FF_API_AVFILTERBUFFER /** * Create and return a picref reference from the data and properties * contained in frame. * * @param perms permissions to assign to the new buffer reference * @deprecated avfilter APIs work natively with AVFrame instead. */ attribute_deprecated AVFilterBufferRef *avfilter_get_video_buffer_ref_from_frame(const AVFrame *frame, int perms); /** * Create and return a picref reference from the data and properties * contained in frame. * * @param perms permissions to assign to the new buffer reference * @deprecated avfilter APIs work natively with AVFrame instead. */ attribute_deprecated AVFilterBufferRef *avfilter_get_audio_buffer_ref_from_frame(const AVFrame *frame, int perms); /** * Create and return a buffer reference from the data and properties * contained in frame. * * @param perms permissions to assign to the new buffer reference * @deprecated avfilter APIs work natively with AVFrame instead. */ attribute_deprecated AVFilterBufferRef *avfilter_get_buffer_ref_from_frame(enum AVMediaType type, const AVFrame *frame, int perms); #endif #if FF_API_FILL_FRAME /** * Fill an AVFrame with the information stored in samplesref. * * @param frame an already allocated AVFrame * @param samplesref an audio buffer reference * @return >= 0 in case of success, a negative AVERROR code in case of * failure * @deprecated Use avfilter_copy_buf_props() instead. */ attribute_deprecated int avfilter_fill_frame_from_audio_buffer_ref(AVFrame *frame, const AVFilterBufferRef *samplesref); /** * Fill an AVFrame with the information stored in picref. * * @param frame an already allocated AVFrame * @param picref a video buffer reference * @return >= 0 in case of success, a negative AVERROR code in case of * failure * @deprecated Use avfilter_copy_buf_props() instead. */ attribute_deprecated int avfilter_fill_frame_from_video_buffer_ref(AVFrame *frame, const AVFilterBufferRef *picref); /** * Fill an AVFrame with information stored in ref. * * @param frame an already allocated AVFrame * @param ref a video or audio buffer reference * @return >= 0 in case of success, a negative AVERROR code in case of * failure * @deprecated Use avfilter_copy_buf_props() instead. */ attribute_deprecated int avfilter_fill_frame_from_buffer_ref(AVFrame *frame, const AVFilterBufferRef *ref); #endif #endif /* AVFILTER_AVCODEC_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavfilter/avfilter.h ================================================ /* * filter layer * Copyright (c) 2007 Bobby Bingham * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_AVFILTER_H #define AVFILTER_AVFILTER_H /** * @file * @ingroup lavfi * Main libavfilter public API header */ /** * @defgroup lavfi Libavfilter - graph-based frame editing library * @{ */ #include #include "libavutil/attributes.h" #include "libavutil/avutil.h" #include "libavutil/dict.h" #include "libavutil/frame.h" #include "libavutil/log.h" #include "libavutil/samplefmt.h" #include "libavutil/pixfmt.h" #include "libavutil/rational.h" #include "libavfilter/version.h" /** * Return the LIBAVFILTER_VERSION_INT constant. */ unsigned avfilter_version(void); /** * Return the libavfilter build-time configuration. */ const char *avfilter_configuration(void); /** * Return the libavfilter license. */ const char *avfilter_license(void); typedef struct AVFilterContext AVFilterContext; typedef struct AVFilterLink AVFilterLink; typedef struct AVFilterPad AVFilterPad; typedef struct AVFilterFormats AVFilterFormats; #if FF_API_AVFILTERBUFFER /** * A reference-counted buffer data type used by the filter system. Filters * should not store pointers to this structure directly, but instead use the * AVFilterBufferRef structure below. */ typedef struct AVFilterBuffer { uint8_t *data[8]; ///< buffer data for each plane/channel /** * pointers to the data planes/channels. * * For video, this should simply point to data[]. * * For planar audio, each channel has a separate data pointer, and * linesize[0] contains the size of each channel buffer. * For packed audio, there is just one data pointer, and linesize[0] * contains the total size of the buffer for all channels. * * Note: Both data and extended_data will always be set, but for planar * audio with more channels that can fit in data, extended_data must be used * in order to access all channels. */ uint8_t **extended_data; int linesize[8]; ///< number of bytes per line /** private data to be used by a custom free function */ void *priv; /** * A pointer to the function to deallocate this buffer if the default * function is not sufficient. This could, for example, add the memory * back into a memory pool to be reused later without the overhead of * reallocating it from scratch. */ void (*free)(struct AVFilterBuffer *buf); int format; ///< media format int w, h; ///< width and height of the allocated buffer unsigned refcount; ///< number of references to this buffer } AVFilterBuffer; #define AV_PERM_READ 0x01 ///< can read from the buffer #define AV_PERM_WRITE 0x02 ///< can write to the buffer #define AV_PERM_PRESERVE 0x04 ///< nobody else can overwrite the buffer #define AV_PERM_REUSE 0x08 ///< can output the buffer multiple times, with the same contents each time #define AV_PERM_REUSE2 0x10 ///< can output the buffer multiple times, modified each time #define AV_PERM_NEG_LINESIZES 0x20 ///< the buffer requested can have negative linesizes #define AV_PERM_ALIGN 0x40 ///< the buffer must be aligned #define AVFILTER_ALIGN 16 //not part of ABI /** * Audio specific properties in a reference to an AVFilterBuffer. Since * AVFilterBufferRef is common to different media formats, audio specific * per reference properties must be separated out. */ typedef struct AVFilterBufferRefAudioProps { uint64_t channel_layout; ///< channel layout of audio buffer int nb_samples; ///< number of audio samples per channel int sample_rate; ///< audio buffer sample rate int channels; ///< number of channels (do not access directly) } AVFilterBufferRefAudioProps; /** * Video specific properties in a reference to an AVFilterBuffer. Since * AVFilterBufferRef is common to different media formats, video specific * per reference properties must be separated out. */ typedef struct AVFilterBufferRefVideoProps { int w; ///< image width int h; ///< image height AVRational sample_aspect_ratio; ///< sample aspect ratio int interlaced; ///< is frame interlaced int top_field_first; ///< field order enum AVPictureType pict_type; ///< picture type of the frame int key_frame; ///< 1 -> keyframe, 0-> not int qp_table_linesize; ///< qp_table stride int qp_table_size; ///< qp_table size int8_t *qp_table; ///< array of Quantization Parameters } AVFilterBufferRefVideoProps; /** * A reference to an AVFilterBuffer. Since filters can manipulate the origin of * a buffer to, for example, crop image without any memcpy, the buffer origin * and dimensions are per-reference properties. Linesize is also useful for * image flipping, frame to field filters, etc, and so is also per-reference. * * TODO: add anything necessary for frame reordering */ typedef struct AVFilterBufferRef { AVFilterBuffer *buf; ///< the buffer that this is a reference to uint8_t *data[8]; ///< picture/audio data for each plane /** * pointers to the data planes/channels. * * For video, this should simply point to data[]. * * For planar audio, each channel has a separate data pointer, and * linesize[0] contains the size of each channel buffer. * For packed audio, there is just one data pointer, and linesize[0] * contains the total size of the buffer for all channels. * * Note: Both data and extended_data will always be set, but for planar * audio with more channels that can fit in data, extended_data must be used * in order to access all channels. */ uint8_t **extended_data; int linesize[8]; ///< number of bytes per line AVFilterBufferRefVideoProps *video; ///< video buffer specific properties AVFilterBufferRefAudioProps *audio; ///< audio buffer specific properties /** * presentation timestamp. The time unit may change during * filtering, as it is specified in the link and the filter code * may need to rescale the PTS accordingly. */ int64_t pts; int64_t pos; ///< byte position in stream, -1 if unknown int format; ///< media format int perms; ///< permissions, see the AV_PERM_* flags enum AVMediaType type; ///< media type of buffer data AVDictionary *metadata; ///< dictionary containing metadata key=value tags } AVFilterBufferRef; /** * Copy properties of src to dst, without copying the actual data */ attribute_deprecated void avfilter_copy_buffer_ref_props(AVFilterBufferRef *dst, AVFilterBufferRef *src); /** * Add a new reference to a buffer. * * @param ref an existing reference to the buffer * @param pmask a bitmask containing the allowable permissions in the new * reference * @return a new reference to the buffer with the same properties as the * old, excluding any permissions denied by pmask */ attribute_deprecated AVFilterBufferRef *avfilter_ref_buffer(AVFilterBufferRef *ref, int pmask); /** * Remove a reference to a buffer. If this is the last reference to the * buffer, the buffer itself is also automatically freed. * * @param ref reference to the buffer, may be NULL * * @note it is recommended to use avfilter_unref_bufferp() instead of this * function */ attribute_deprecated void avfilter_unref_buffer(AVFilterBufferRef *ref); /** * Remove a reference to a buffer and set the pointer to NULL. * If this is the last reference to the buffer, the buffer itself * is also automatically freed. * * @param ref pointer to the buffer reference */ attribute_deprecated void avfilter_unref_bufferp(AVFilterBufferRef **ref); #endif /** * Get the number of channels of a buffer reference. */ attribute_deprecated int avfilter_ref_get_channels(AVFilterBufferRef *ref); #if FF_API_AVFILTERPAD_PUBLIC /** * A filter pad used for either input or output. * * See doc/filter_design.txt for details on how to implement the methods. * * @warning this struct might be removed from public API. * users should call avfilter_pad_get_name() and avfilter_pad_get_type() * to access the name and type fields; there should be no need to access * any other fields from outside of libavfilter. */ struct AVFilterPad { /** * Pad name. The name is unique among inputs and among outputs, but an * input may have the same name as an output. This may be NULL if this * pad has no need to ever be referenced by name. */ const char *name; /** * AVFilterPad type. */ enum AVMediaType type; /** * Input pads: * Minimum required permissions on incoming buffers. Any buffer with * insufficient permissions will be automatically copied by the filter * system to a new buffer which provides the needed access permissions. * * Output pads: * Guaranteed permissions on outgoing buffers. Any buffer pushed on the * link must have at least these permissions; this fact is checked by * asserts. It can be used to optimize buffer allocation. */ attribute_deprecated int min_perms; /** * Input pads: * Permissions which are not accepted on incoming buffers. Any buffer * which has any of these permissions set will be automatically copied * by the filter system to a new buffer which does not have those * permissions. This can be used to easily disallow buffers with * AV_PERM_REUSE. * * Output pads: * Permissions which are automatically removed on outgoing buffers. It * can be used to optimize buffer allocation. */ attribute_deprecated int rej_perms; /** * @deprecated unused */ int (*start_frame)(AVFilterLink *link, AVFilterBufferRef *picref); /** * Callback function to get a video buffer. If NULL, the filter system will * use ff_default_get_video_buffer(). * * Input video pads only. */ AVFrame *(*get_video_buffer)(AVFilterLink *link, int w, int h); /** * Callback function to get an audio buffer. If NULL, the filter system will * use ff_default_get_audio_buffer(). * * Input audio pads only. */ AVFrame *(*get_audio_buffer)(AVFilterLink *link, int nb_samples); /** * @deprecated unused */ int (*end_frame)(AVFilterLink *link); /** * @deprecated unused */ int (*draw_slice)(AVFilterLink *link, int y, int height, int slice_dir); /** * Filtering callback. This is where a filter receives a frame with * audio/video data and should do its processing. * * Input pads only. * * @return >= 0 on success, a negative AVERROR on error. This function * must ensure that frame is properly unreferenced on error if it * hasn't been passed on to another filter. */ int (*filter_frame)(AVFilterLink *link, AVFrame *frame); /** * Frame poll callback. This returns the number of immediately available * samples. It should return a positive value if the next request_frame() * is guaranteed to return one frame (with no delay). * * Defaults to just calling the source poll_frame() method. * * Output pads only. */ int (*poll_frame)(AVFilterLink *link); /** * Frame request callback. A call to this should result in at least one * frame being output over the given link. This should return zero on * success, and another value on error. * See ff_request_frame() for the error codes with a specific * meaning. * * Output pads only. */ int (*request_frame)(AVFilterLink *link); /** * Link configuration callback. * * For output pads, this should set the following link properties: * video: width, height, sample_aspect_ratio, time_base * audio: sample_rate. * * This should NOT set properties such as format, channel_layout, etc which * are negotiated between filters by the filter system using the * query_formats() callback before this function is called. * * For input pads, this should check the properties of the link, and update * the filter's internal state as necessary. * * For both input and output pads, this should return zero on success, * and another value on error. */ int (*config_props)(AVFilterLink *link); /** * The filter expects a fifo to be inserted on its input link, * typically because it has a delay. * * input pads only. */ int needs_fifo; /** * The filter expects writable frames from its input link, * duplicating data buffers if needed. * * input pads only. */ int needs_writable; }; #endif /** * Get the number of elements in a NULL-terminated array of AVFilterPads (e.g. * AVFilter.inputs/outputs). */ int avfilter_pad_count(const AVFilterPad *pads); /** * Get the name of an AVFilterPad. * * @param pads an array of AVFilterPads * @param pad_idx index of the pad in the array it; is the caller's * responsibility to ensure the index is valid * * @return name of the pad_idx'th pad in pads */ const char *avfilter_pad_get_name(const AVFilterPad *pads, int pad_idx); /** * Get the type of an AVFilterPad. * * @param pads an array of AVFilterPads * @param pad_idx index of the pad in the array; it is the caller's * responsibility to ensure the index is valid * * @return type of the pad_idx'th pad in pads */ enum AVMediaType avfilter_pad_get_type(const AVFilterPad *pads, int pad_idx); /** * The number of the filter inputs is not determined just by AVFilter.inputs. * The filter might add additional inputs during initialization depending on the * options supplied to it. */ #define AVFILTER_FLAG_DYNAMIC_INPUTS (1 << 0) /** * The number of the filter outputs is not determined just by AVFilter.outputs. * The filter might add additional outputs during initialization depending on * the options supplied to it. */ #define AVFILTER_FLAG_DYNAMIC_OUTPUTS (1 << 1) /** * The filter supports multithreading by splitting frames into multiple parts * and processing them concurrently. */ #define AVFILTER_FLAG_SLICE_THREADS (1 << 2) /** * Some filters support a generic "enable" expression option that can be used * to enable or disable a filter in the timeline. Filters supporting this * option have this flag set. When the enable expression is false, the default * no-op filter_frame() function is called in place of the filter_frame() * callback defined on each input pad, thus the frame is passed unchanged to * the next filters. */ #define AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC (1 << 16) /** * Same as AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, except that the filter will * have its filter_frame() callback(s) called as usual even when the enable * expression is false. The filter will disable filtering within the * filter_frame() callback(s) itself, for example executing code depending on * the AVFilterContext->is_disabled value. */ #define AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL (1 << 17) /** * Handy mask to test whether the filter supports or no the timeline feature * (internally or generically). */ #define AVFILTER_FLAG_SUPPORT_TIMELINE (AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL) /** * Filter definition. This defines the pads a filter contains, and all the * callback functions used to interact with the filter. */ typedef struct AVFilter { /** * Filter name. Must be non-NULL and unique among filters. */ const char *name; /** * A description of the filter. May be NULL. * * You should use the NULL_IF_CONFIG_SMALL() macro to define it. */ const char *description; /** * List of inputs, terminated by a zeroed element. * * NULL if there are no (static) inputs. Instances of filters with * AVFILTER_FLAG_DYNAMIC_INPUTS set may have more inputs than present in * this list. */ const AVFilterPad *inputs; /** * List of outputs, terminated by a zeroed element. * * NULL if there are no (static) outputs. Instances of filters with * AVFILTER_FLAG_DYNAMIC_OUTPUTS set may have more outputs than present in * this list. */ const AVFilterPad *outputs; /** * A class for the private data, used to declare filter private AVOptions. * This field is NULL for filters that do not declare any options. * * If this field is non-NULL, the first member of the filter private data * must be a pointer to AVClass, which will be set by libavfilter generic * code to this class. */ const AVClass *priv_class; /** * A combination of AVFILTER_FLAG_* */ int flags; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavfilter and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * Filter initialization function. * * This callback will be called only once during the filter lifetime, after * all the options have been set, but before links between filters are * established and format negotiation is done. * * Basic filter initialization should be done here. Filters with dynamic * inputs and/or outputs should create those inputs/outputs here based on * provided options. No more changes to this filter's inputs/outputs can be * done after this callback. * * This callback must not assume that the filter links exist or frame * parameters are known. * * @ref AVFilter.uninit "uninit" is guaranteed to be called even if * initialization fails, so this callback does not have to clean up on * failure. * * @return 0 on success, a negative AVERROR on failure */ int (*init)(AVFilterContext *ctx); /** * Should be set instead of @ref AVFilter.init "init" by the filters that * want to pass a dictionary of AVOptions to nested contexts that are * allocated during init. * * On return, the options dict should be freed and replaced with one that * contains all the options which could not be processed by this filter (or * with NULL if all the options were processed). * * Otherwise the semantics is the same as for @ref AVFilter.init "init". */ int (*init_dict)(AVFilterContext *ctx, AVDictionary **options); /** * Filter uninitialization function. * * Called only once right before the filter is freed. Should deallocate any * memory held by the filter, release any buffer references, etc. It does * not need to deallocate the AVFilterContext.priv memory itself. * * This callback may be called even if @ref AVFilter.init "init" was not * called or failed, so it must be prepared to handle such a situation. */ void (*uninit)(AVFilterContext *ctx); /** * Query formats supported by the filter on its inputs and outputs. * * This callback is called after the filter is initialized (so the inputs * and outputs are fixed), shortly before the format negotiation. This * callback may be called more than once. * * This callback must set AVFilterLink.out_formats on every input link and * AVFilterLink.in_formats on every output link to a list of pixel/sample * formats that the filter supports on that link. For audio links, this * filter must also set @ref AVFilterLink.in_samplerates "in_samplerates" / * @ref AVFilterLink.out_samplerates "out_samplerates" and * @ref AVFilterLink.in_channel_layouts "in_channel_layouts" / * @ref AVFilterLink.out_channel_layouts "out_channel_layouts" analogously. * * This callback may be NULL for filters with one input, in which case * libavfilter assumes that it supports all input formats and preserves * them on output. * * @return zero on success, a negative value corresponding to an * AVERROR code otherwise */ int (*query_formats)(AVFilterContext *); int priv_size; ///< size of private data to allocate for the filter /** * Used by the filter registration system. Must not be touched by any other * code. */ struct AVFilter *next; /** * Make the filter instance process a command. * * @param cmd the command to process, for handling simplicity all commands must be alphanumeric only * @param arg the argument for the command * @param res a buffer with size res_size where the filter(s) can return a response. This must not change when the command is not supported. * @param flags if AVFILTER_CMD_FLAG_FAST is set and the command would be * time consuming then a filter should treat it like an unsupported command * * @returns >=0 on success otherwise an error code. * AVERROR(ENOSYS) on unsupported commands */ int (*process_command)(AVFilterContext *, const char *cmd, const char *arg, char *res, int res_len, int flags); /** * Filter initialization function, alternative to the init() * callback. Args contains the user-supplied parameters, opaque is * used for providing binary data. */ int (*init_opaque)(AVFilterContext *ctx, void *opaque); } AVFilter; /** * Process multiple parts of the frame concurrently. */ #define AVFILTER_THREAD_SLICE (1 << 0) typedef struct AVFilterInternal AVFilterInternal; /** An instance of a filter */ struct AVFilterContext { const AVClass *av_class; ///< needed for av_log() and filters common options const AVFilter *filter; ///< the AVFilter of which this is an instance char *name; ///< name of this filter instance AVFilterPad *input_pads; ///< array of input pads AVFilterLink **inputs; ///< array of pointers to input links #if FF_API_FOO_COUNT attribute_deprecated unsigned input_count; ///< @deprecated use nb_inputs #endif unsigned nb_inputs; ///< number of input pads AVFilterPad *output_pads; ///< array of output pads AVFilterLink **outputs; ///< array of pointers to output links #if FF_API_FOO_COUNT attribute_deprecated unsigned output_count; ///< @deprecated use nb_outputs #endif unsigned nb_outputs; ///< number of output pads void *priv; ///< private data for use by the filter struct AVFilterGraph *graph; ///< filtergraph this filter belongs to /** * Type of multithreading being allowed/used. A combination of * AVFILTER_THREAD_* flags. * * May be set by the caller before initializing the filter to forbid some * or all kinds of multithreading for this filter. The default is allowing * everything. * * When the filter is initialized, this field is combined using bit AND with * AVFilterGraph.thread_type to get the final mask used for determining * allowed threading types. I.e. a threading type needs to be set in both * to be allowed. * * After the filter is initialzed, libavfilter sets this field to the * threading type that is actually used (0 for no multithreading). */ int thread_type; /** * An opaque struct for libavfilter internal use. */ AVFilterInternal *internal; struct AVFilterCommand *command_queue; char *enable_str; ///< enable expression string void *enable; ///< parsed expression (AVExpr*) double *var_values; ///< variable values for the enable expression int is_disabled; ///< the enabled state from the last expression evaluation }; /** * A link between two filters. This contains pointers to the source and * destination filters between which this link exists, and the indexes of * the pads involved. In addition, this link also contains the parameters * which have been negotiated and agreed upon between the filter, such as * image dimensions, format, etc. */ struct AVFilterLink { AVFilterContext *src; ///< source filter AVFilterPad *srcpad; ///< output pad on the source filter AVFilterContext *dst; ///< dest filter AVFilterPad *dstpad; ///< input pad on the dest filter enum AVMediaType type; ///< filter media type /* These parameters apply only to video */ int w; ///< agreed upon image width int h; ///< agreed upon image height AVRational sample_aspect_ratio; ///< agreed upon sample aspect ratio /* These parameters apply only to audio */ uint64_t channel_layout; ///< channel layout of current buffer (see libavutil/channel_layout.h) int sample_rate; ///< samples per second int format; ///< agreed upon media format /** * Define the time base used by the PTS of the frames/samples * which will pass through this link. * During the configuration stage, each filter is supposed to * change only the output timebase, while the timebase of the * input link is assumed to be an unchangeable property. */ AVRational time_base; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavfilter and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * Lists of formats and channel layouts supported by the input and output * filters respectively. These lists are used for negotiating the format * to actually be used, which will be loaded into the format and * channel_layout members, above, when chosen. * */ AVFilterFormats *in_formats; AVFilterFormats *out_formats; /** * Lists of channel layouts and sample rates used for automatic * negotiation. */ AVFilterFormats *in_samplerates; AVFilterFormats *out_samplerates; struct AVFilterChannelLayouts *in_channel_layouts; struct AVFilterChannelLayouts *out_channel_layouts; /** * Audio only, the destination filter sets this to a non-zero value to * request that buffers with the given number of samples should be sent to * it. AVFilterPad.needs_fifo must also be set on the corresponding input * pad. * Last buffer before EOF will be padded with silence. */ int request_samples; /** stage of the initialization of the link properties (dimensions, etc) */ enum { AVLINK_UNINIT = 0, ///< not started AVLINK_STARTINIT, ///< started, but incomplete AVLINK_INIT ///< complete } init_state; struct AVFilterPool *pool; /** * Graph the filter belongs to. */ struct AVFilterGraph *graph; /** * Current timestamp of the link, as defined by the most recent * frame(s), in AV_TIME_BASE units. */ int64_t current_pts; /** * Index in the age array. */ int age_index; /** * Frame rate of the stream on the link, or 1/0 if unknown; * if left to 0/0, will be automatically be copied from the first input * of the source filter if it exists. * * Sources should set it to the best estimation of the real frame rate. * Filters should update it if necessary depending on their function. * Sinks can use it to set a default output frame rate. * It is similar to the r_frame_rate field in AVStream. */ AVRational frame_rate; /** * Buffer partially filled with samples to achieve a fixed/minimum size. */ AVFrame *partial_buf; /** * Size of the partial buffer to allocate. * Must be between min_samples and max_samples. */ int partial_buf_size; /** * Minimum number of samples to filter at once. If filter_frame() is * called with fewer samples, it will accumulate them in partial_buf. * This field and the related ones must not be changed after filtering * has started. * If 0, all related fields are ignored. */ int min_samples; /** * Maximum number of samples to filter at once. If filter_frame() is * called with more samples, it will split them. */ int max_samples; /** * The buffer reference currently being received across the link by the * destination filter. This is used internally by the filter system to * allow automatic copying of buffers which do not have sufficient * permissions for the destination. This should not be accessed directly * by the filters. */ AVFilterBufferRef *cur_buf_copy; /** * True if the link is closed. * If set, all attemps of start_frame, filter_frame or request_frame * will fail with AVERROR_EOF, and if necessary the reference will be * destroyed. * If request_frame returns AVERROR_EOF, this flag is set on the * corresponding link. * It can be set also be set by either the source or the destination * filter. */ int closed; /** * Number of channels. */ int channels; /** * True if a frame is being requested on the link. * Used internally by the framework. */ unsigned frame_requested; /** * Link processing flags. */ unsigned flags; /** * Number of past frames sent through the link. */ int64_t frame_count; }; /** * Link two filters together. * * @param src the source filter * @param srcpad index of the output pad on the source filter * @param dst the destination filter * @param dstpad index of the input pad on the destination filter * @return zero on success */ int avfilter_link(AVFilterContext *src, unsigned srcpad, AVFilterContext *dst, unsigned dstpad); /** * Free the link in *link, and set its pointer to NULL. */ void avfilter_link_free(AVFilterLink **link); /** * Get the number of channels of a link. */ int avfilter_link_get_channels(AVFilterLink *link); /** * Set the closed field of a link. */ void avfilter_link_set_closed(AVFilterLink *link, int closed); /** * Negotiate the media format, dimensions, etc of all inputs to a filter. * * @param filter the filter to negotiate the properties for its inputs * @return zero on successful negotiation */ int avfilter_config_links(AVFilterContext *filter); #if FF_API_AVFILTERBUFFER /** * Create a buffer reference wrapped around an already allocated image * buffer. * * @param data pointers to the planes of the image to reference * @param linesize linesizes for the planes of the image to reference * @param perms the required access permissions * @param w the width of the image specified by the data and linesize arrays * @param h the height of the image specified by the data and linesize arrays * @param format the pixel format of the image specified by the data and linesize arrays */ attribute_deprecated AVFilterBufferRef * avfilter_get_video_buffer_ref_from_arrays(uint8_t * const data[4], const int linesize[4], int perms, int w, int h, enum AVPixelFormat format); /** * Create an audio buffer reference wrapped around an already * allocated samples buffer. * * See avfilter_get_audio_buffer_ref_from_arrays_channels() for a version * that can handle unknown channel layouts. * * @param data pointers to the samples plane buffers * @param linesize linesize for the samples plane buffers * @param perms the required access permissions * @param nb_samples number of samples per channel * @param sample_fmt the format of each sample in the buffer to allocate * @param channel_layout the channel layout of the buffer */ attribute_deprecated AVFilterBufferRef *avfilter_get_audio_buffer_ref_from_arrays(uint8_t **data, int linesize, int perms, int nb_samples, enum AVSampleFormat sample_fmt, uint64_t channel_layout); /** * Create an audio buffer reference wrapped around an already * allocated samples buffer. * * @param data pointers to the samples plane buffers * @param linesize linesize for the samples plane buffers * @param perms the required access permissions * @param nb_samples number of samples per channel * @param sample_fmt the format of each sample in the buffer to allocate * @param channels the number of channels of the buffer * @param channel_layout the channel layout of the buffer, * must be either 0 or consistent with channels */ attribute_deprecated AVFilterBufferRef *avfilter_get_audio_buffer_ref_from_arrays_channels(uint8_t **data, int linesize, int perms, int nb_samples, enum AVSampleFormat sample_fmt, int channels, uint64_t channel_layout); #endif #define AVFILTER_CMD_FLAG_ONE 1 ///< Stop once a filter understood the command (for target=all for example), fast filters are favored automatically #define AVFILTER_CMD_FLAG_FAST 2 ///< Only execute command when its fast (like a video out that supports contrast adjustment in hw) /** * Make the filter instance process a command. * It is recommended to use avfilter_graph_send_command(). */ int avfilter_process_command(AVFilterContext *filter, const char *cmd, const char *arg, char *res, int res_len, int flags); /** Initialize the filter system. Register all builtin filters. */ void avfilter_register_all(void); #if FF_API_OLD_FILTER_REGISTER /** Uninitialize the filter system. Unregister all filters. */ attribute_deprecated void avfilter_uninit(void); #endif /** * Register a filter. This is only needed if you plan to use * avfilter_get_by_name later to lookup the AVFilter structure by name. A * filter can still by instantiated with avfilter_graph_alloc_filter even if it * is not registered. * * @param filter the filter to register * @return 0 if the registration was successful, a negative value * otherwise */ int avfilter_register(AVFilter *filter); /** * Get a filter definition matching the given name. * * @param name the filter name to find * @return the filter definition, if any matching one is registered. * NULL if none found. */ #if !FF_API_NOCONST_GET_NAME const #endif AVFilter *avfilter_get_by_name(const char *name); /** * Iterate over all registered filters. * @return If prev is non-NULL, next registered filter after prev or NULL if * prev is the last filter. If prev is NULL, return the first registered filter. */ const AVFilter *avfilter_next(const AVFilter *prev); #if FF_API_OLD_FILTER_REGISTER /** * If filter is NULL, returns a pointer to the first registered filter pointer, * if filter is non-NULL, returns the next pointer after filter. * If the returned pointer points to NULL, the last registered filter * was already reached. * @deprecated use avfilter_next() */ attribute_deprecated AVFilter **av_filter_next(AVFilter **filter); #endif #if FF_API_AVFILTER_OPEN /** * Create a filter instance. * * @param filter_ctx put here a pointer to the created filter context * on success, NULL on failure * @param filter the filter to create an instance of * @param inst_name Name to give to the new instance. Can be NULL for none. * @return >= 0 in case of success, a negative error code otherwise * @deprecated use avfilter_graph_alloc_filter() instead */ attribute_deprecated int avfilter_open(AVFilterContext **filter_ctx, AVFilter *filter, const char *inst_name); #endif #if FF_API_AVFILTER_INIT_FILTER /** * Initialize a filter. * * @param filter the filter to initialize * @param args A string of parameters to use when initializing the filter. * The format and meaning of this string varies by filter. * @param opaque Any extra non-string data needed by the filter. The meaning * of this parameter varies by filter. * @return zero on success */ attribute_deprecated int avfilter_init_filter(AVFilterContext *filter, const char *args, void *opaque); #endif /** * Initialize a filter with the supplied parameters. * * @param ctx uninitialized filter context to initialize * @param args Options to initialize the filter with. This must be a * ':'-separated list of options in the 'key=value' form. * May be NULL if the options have been set directly using the * AVOptions API or there are no options that need to be set. * @return 0 on success, a negative AVERROR on failure */ int avfilter_init_str(AVFilterContext *ctx, const char *args); /** * Initialize a filter with the supplied dictionary of options. * * @param ctx uninitialized filter context to initialize * @param options An AVDictionary filled with options for this filter. On * return this parameter will be destroyed and replaced with * a dict containing options that were not found. This dictionary * must be freed by the caller. * May be NULL, then this function is equivalent to * avfilter_init_str() with the second parameter set to NULL. * @return 0 on success, a negative AVERROR on failure * * @note This function and avfilter_init_str() do essentially the same thing, * the difference is in manner in which the options are passed. It is up to the * calling code to choose whichever is more preferable. The two functions also * behave differently when some of the provided options are not declared as * supported by the filter. In such a case, avfilter_init_str() will fail, but * this function will leave those extra options in the options AVDictionary and * continue as usual. */ int avfilter_init_dict(AVFilterContext *ctx, AVDictionary **options); /** * Free a filter context. This will also remove the filter from its * filtergraph's list of filters. * * @param filter the filter to free */ void avfilter_free(AVFilterContext *filter); /** * Insert a filter in the middle of an existing link. * * @param link the link into which the filter should be inserted * @param filt the filter to be inserted * @param filt_srcpad_idx the input pad on the filter to connect * @param filt_dstpad_idx the output pad on the filter to connect * @return zero on success */ int avfilter_insert_filter(AVFilterLink *link, AVFilterContext *filt, unsigned filt_srcpad_idx, unsigned filt_dstpad_idx); #if FF_API_AVFILTERBUFFER /** * Copy the frame properties of src to dst, without copying the actual * image data. * * @return 0 on success, a negative number on error. */ attribute_deprecated int avfilter_copy_frame_props(AVFilterBufferRef *dst, const AVFrame *src); /** * Copy the frame properties and data pointers of src to dst, without copying * the actual data. * * @return 0 on success, a negative number on error. */ attribute_deprecated int avfilter_copy_buf_props(AVFrame *dst, const AVFilterBufferRef *src); #endif /** * @return AVClass for AVFilterContext. * * @see av_opt_find(). */ const AVClass *avfilter_get_class(void); typedef struct AVFilterGraphInternal AVFilterGraphInternal; /** * A function pointer passed to the @ref AVFilterGraph.execute callback to be * executed multiple times, possibly in parallel. * * @param ctx the filter context the job belongs to * @param arg an opaque parameter passed through from @ref * AVFilterGraph.execute * @param jobnr the index of the job being executed * @param nb_jobs the total number of jobs * * @return 0 on success, a negative AVERROR on error */ typedef int (avfilter_action_func)(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs); /** * A function executing multiple jobs, possibly in parallel. * * @param ctx the filter context to which the jobs belong * @param func the function to be called multiple times * @param arg the argument to be passed to func * @param ret a nb_jobs-sized array to be filled with return values from each * invocation of func * @param nb_jobs the number of jobs to execute * * @return 0 on success, a negative AVERROR on error */ typedef int (avfilter_execute_func)(AVFilterContext *ctx, avfilter_action_func *func, void *arg, int *ret, int nb_jobs); typedef struct AVFilterGraph { const AVClass *av_class; #if FF_API_FOO_COUNT attribute_deprecated unsigned filter_count_unused; #endif AVFilterContext **filters; #if !FF_API_FOO_COUNT unsigned nb_filters; #endif char *scale_sws_opts; ///< sws options to use for the auto-inserted scale filters char *resample_lavr_opts; ///< libavresample options to use for the auto-inserted resample filters #if FF_API_FOO_COUNT unsigned nb_filters; #endif /** * Type of multithreading allowed for filters in this graph. A combination * of AVFILTER_THREAD_* flags. * * May be set by the caller at any point, the setting will apply to all * filters initialized after that. The default is allowing everything. * * When a filter in this graph is initialized, this field is combined using * bit AND with AVFilterContext.thread_type to get the final mask used for * determining allowed threading types. I.e. a threading type needs to be * set in both to be allowed. */ int thread_type; /** * Maximum number of threads used by filters in this graph. May be set by * the caller before adding any filters to the filtergraph. Zero (the * default) means that the number of threads is determined automatically. */ int nb_threads; /** * Opaque object for libavfilter internal use. */ AVFilterGraphInternal *internal; /** * Opaque user data. May be set by the caller to an arbitrary value, e.g. to * be used from callbacks like @ref AVFilterGraph.execute. * Libavfilter will not touch this field in any way. */ void *opaque; /** * This callback may be set by the caller immediately after allocating the * graph and before adding any filters to it, to provide a custom * multithreading implementation. * * If set, filters with slice threading capability will call this callback * to execute multiple jobs in parallel. * * If this field is left unset, libavfilter will use its internal * implementation, which may or may not be multithreaded depending on the * platform and build options. */ avfilter_execute_func *execute; char *aresample_swr_opts; ///< swr options to use for the auto-inserted aresample filters, Access ONLY through AVOptions /** * Private fields * * The following fields are for internal use only. * Their type, offset, number and semantic can change without notice. */ AVFilterLink **sink_links; int sink_links_count; unsigned disable_auto_convert; } AVFilterGraph; /** * Allocate a filter graph. */ AVFilterGraph *avfilter_graph_alloc(void); /** * Create a new filter instance in a filter graph. * * @param graph graph in which the new filter will be used * @param filter the filter to create an instance of * @param name Name to give to the new instance (will be copied to * AVFilterContext.name). This may be used by the caller to identify * different filters, libavfilter itself assigns no semantics to * this parameter. May be NULL. * * @return the context of the newly created filter instance (note that it is * also retrievable directly through AVFilterGraph.filters or with * avfilter_graph_get_filter()) on success or NULL or failure. */ AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph, const AVFilter *filter, const char *name); /** * Get a filter instance with name name from graph. * * @return the pointer to the found filter instance or NULL if it * cannot be found. */ AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name); #if FF_API_AVFILTER_OPEN /** * Add an existing filter instance to a filter graph. * * @param graphctx the filter graph * @param filter the filter to be added * * @deprecated use avfilter_graph_alloc_filter() to allocate a filter in a * filter graph */ attribute_deprecated int avfilter_graph_add_filter(AVFilterGraph *graphctx, AVFilterContext *filter); #endif /** * Create and add a filter instance into an existing graph. * The filter instance is created from the filter filt and inited * with the parameters args and opaque. * * In case of success put in *filt_ctx the pointer to the created * filter instance, otherwise set *filt_ctx to NULL. * * @param name the instance name to give to the created filter instance * @param graph_ctx the filter graph * @return a negative AVERROR error code in case of failure, a non * negative value otherwise */ int avfilter_graph_create_filter(AVFilterContext **filt_ctx, const AVFilter *filt, const char *name, const char *args, void *opaque, AVFilterGraph *graph_ctx); /** * Enable or disable automatic format conversion inside the graph. * * Note that format conversion can still happen inside explicitly inserted * scale and aresample filters. * * @param flags any of the AVFILTER_AUTO_CONVERT_* constants */ void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags); enum { AVFILTER_AUTO_CONVERT_ALL = 0, /**< all automatic conversions enabled */ AVFILTER_AUTO_CONVERT_NONE = -1, /**< all automatic conversions disabled */ }; /** * Check validity and configure all the links and formats in the graph. * * @param graphctx the filter graph * @param log_ctx context used for logging * @return >= 0 in case of success, a negative AVERROR code otherwise */ int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx); /** * Free a graph, destroy its links, and set *graph to NULL. * If *graph is NULL, do nothing. */ void avfilter_graph_free(AVFilterGraph **graph); /** * A linked-list of the inputs/outputs of the filter chain. * * This is mainly useful for avfilter_graph_parse() / avfilter_graph_parse2(), * where it is used to communicate open (unlinked) inputs and outputs from and * to the caller. * This struct specifies, per each not connected pad contained in the graph, the * filter context and the pad index required for establishing a link. */ typedef struct AVFilterInOut { /** unique name for this input/output in the list */ char *name; /** filter context associated to this input/output */ AVFilterContext *filter_ctx; /** index of the filt_ctx pad to use for linking */ int pad_idx; /** next input/input in the list, NULL if this is the last */ struct AVFilterInOut *next; } AVFilterInOut; /** * Allocate a single AVFilterInOut entry. * Must be freed with avfilter_inout_free(). * @return allocated AVFilterInOut on success, NULL on failure. */ AVFilterInOut *avfilter_inout_alloc(void); /** * Free the supplied list of AVFilterInOut and set *inout to NULL. * If *inout is NULL, do nothing. */ void avfilter_inout_free(AVFilterInOut **inout); #if AV_HAVE_INCOMPATIBLE_LIBAV_ABI || !FF_API_OLD_GRAPH_PARSE /** * Add a graph described by a string to a graph. * * @note The caller must provide the lists of inputs and outputs, * which therefore must be known before calling the function. * * @note The inputs parameter describes inputs of the already existing * part of the graph; i.e. from the point of view of the newly created * part, they are outputs. Similarly the outputs parameter describes * outputs of the already existing filters, which are provided as * inputs to the parsed filters. * * @param graph the filter graph where to link the parsed grap context * @param filters string to be parsed * @param inputs linked list to the inputs of the graph * @param outputs linked list to the outputs of the graph * @return zero on success, a negative AVERROR code on error */ int avfilter_graph_parse(AVFilterGraph *graph, const char *filters, AVFilterInOut *inputs, AVFilterInOut *outputs, void *log_ctx); #else /** * Add a graph described by a string to a graph. * * @param graph the filter graph where to link the parsed graph context * @param filters string to be parsed * @param inputs pointer to a linked list to the inputs of the graph, may be NULL. * If non-NULL, *inputs is updated to contain the list of open inputs * after the parsing, should be freed with avfilter_inout_free(). * @param outputs pointer to a linked list to the outputs of the graph, may be NULL. * If non-NULL, *outputs is updated to contain the list of open outputs * after the parsing, should be freed with avfilter_inout_free(). * @return non negative on success, a negative AVERROR code on error * @deprecated Use avfilter_graph_parse_ptr() instead. */ attribute_deprecated int avfilter_graph_parse(AVFilterGraph *graph, const char *filters, AVFilterInOut **inputs, AVFilterInOut **outputs, void *log_ctx); #endif /** * Add a graph described by a string to a graph. * * @param graph the filter graph where to link the parsed graph context * @param filters string to be parsed * @param inputs pointer to a linked list to the inputs of the graph, may be NULL. * If non-NULL, *inputs is updated to contain the list of open inputs * after the parsing, should be freed with avfilter_inout_free(). * @param outputs pointer to a linked list to the outputs of the graph, may be NULL. * If non-NULL, *outputs is updated to contain the list of open outputs * after the parsing, should be freed with avfilter_inout_free(). * @return non negative on success, a negative AVERROR code on error */ int avfilter_graph_parse_ptr(AVFilterGraph *graph, const char *filters, AVFilterInOut **inputs, AVFilterInOut **outputs, void *log_ctx); /** * Add a graph described by a string to a graph. * * @param[in] graph the filter graph where to link the parsed graph context * @param[in] filters string to be parsed * @param[out] inputs a linked list of all free (unlinked) inputs of the * parsed graph will be returned here. It is to be freed * by the caller using avfilter_inout_free(). * @param[out] outputs a linked list of all free (unlinked) outputs of the * parsed graph will be returned here. It is to be freed by the * caller using avfilter_inout_free(). * @return zero on success, a negative AVERROR code on error * * @note This function returns the inputs and outputs that are left * unlinked after parsing the graph and the caller then deals with * them. * @note This function makes no reference whatsoever to already * existing parts of the graph and the inputs parameter will on return * contain inputs of the newly parsed part of the graph. Analogously * the outputs parameter will contain outputs of the newly created * filters. */ int avfilter_graph_parse2(AVFilterGraph *graph, const char *filters, AVFilterInOut **inputs, AVFilterInOut **outputs); /** * Send a command to one or more filter instances. * * @param graph the filter graph * @param target the filter(s) to which the command should be sent * "all" sends to all filters * otherwise it can be a filter or filter instance name * which will send the command to all matching filters. * @param cmd the command to send, for handling simplicity all commands must be alphanumeric only * @param arg the argument for the command * @param res a buffer with size res_size where the filter(s) can return a response. * * @returns >=0 on success otherwise an error code. * AVERROR(ENOSYS) on unsupported commands */ int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags); /** * Queue a command for one or more filter instances. * * @param graph the filter graph * @param target the filter(s) to which the command should be sent * "all" sends to all filters * otherwise it can be a filter or filter instance name * which will send the command to all matching filters. * @param cmd the command to sent, for handling simplicity all commands must be alphanummeric only * @param arg the argument for the command * @param ts time at which the command should be sent to the filter * * @note As this executes commands after this function returns, no return code * from the filter is provided, also AVFILTER_CMD_FLAG_ONE is not supported. */ int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, int flags, double ts); /** * Dump a graph into a human-readable string representation. * * @param graph the graph to dump * @param options formatting options; currently ignored * @return a string, or NULL in case of memory allocation failure; * the string must be freed using av_free */ char *avfilter_graph_dump(AVFilterGraph *graph, const char *options); /** * Request a frame on the oldest sink link. * * If the request returns AVERROR_EOF, try the next. * * Note that this function is not meant to be the sole scheduling mechanism * of a filtergraph, only a convenience function to help drain a filtergraph * in a balanced way under normal circumstances. * * Also note that AVERROR_EOF does not mean that frames did not arrive on * some of the sinks during the process. * When there are multiple sink links, in case the requested link * returns an EOF, this may cause a filter to flush pending frames * which are sent to another sink link, although unrequested. * * @return the return value of ff_request_frame(), * or AVERROR_EOF if all links returned AVERROR_EOF */ int avfilter_graph_request_oldest(AVFilterGraph *graph); /** * @} */ #endif /* AVFILTER_AVFILTER_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavfilter/avfiltergraph.h ================================================ /* * Filter graphs * copyright (c) 2007 Bobby Bingham * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_AVFILTERGRAPH_H #define AVFILTER_AVFILTERGRAPH_H #include "avfilter.h" #include "libavutil/log.h" #endif /* AVFILTER_AVFILTERGRAPH_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavfilter/buffersink.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_BUFFERSINK_H #define AVFILTER_BUFFERSINK_H /** * @file * @ingroup lavfi_buffersink * memory buffer sink API for audio and video */ #include "avfilter.h" /** * @defgroup lavfi_buffersink Buffer sink API * @ingroup lavfi * @{ */ #if FF_API_AVFILTERBUFFER /** * Get an audio/video buffer data from buffer_sink and put it in bufref. * * This function works with both audio and video buffer sinks. * * @param buffer_sink pointer to a buffersink or abuffersink context * @param flags a combination of AV_BUFFERSINK_FLAG_* flags * @return >= 0 in case of success, a negative AVERROR code in case of * failure */ attribute_deprecated int av_buffersink_get_buffer_ref(AVFilterContext *buffer_sink, AVFilterBufferRef **bufref, int flags); /** * Get the number of immediately available frames. */ attribute_deprecated int av_buffersink_poll_frame(AVFilterContext *ctx); /** * Get a buffer with filtered data from sink and put it in buf. * * @param ctx pointer to a context of a buffersink or abuffersink AVFilter. * @param buf pointer to the buffer will be written here if buf is non-NULL. buf * must be freed by the caller using avfilter_unref_buffer(). * Buf may also be NULL to query whether a buffer is ready to be * output. * * @return >= 0 in case of success, a negative AVERROR code in case of * failure. */ attribute_deprecated int av_buffersink_read(AVFilterContext *ctx, AVFilterBufferRef **buf); /** * Same as av_buffersink_read, but with the ability to specify the number of * samples read. This function is less efficient than av_buffersink_read(), * because it copies the data around. * * @param ctx pointer to a context of the abuffersink AVFilter. * @param buf pointer to the buffer will be written here if buf is non-NULL. buf * must be freed by the caller using avfilter_unref_buffer(). buf * will contain exactly nb_samples audio samples, except at the end * of stream, when it can contain less than nb_samples. * Buf may also be NULL to query whether a buffer is ready to be * output. * * @warning do not mix this function with av_buffersink_read(). Use only one or * the other with a single sink, not both. */ attribute_deprecated int av_buffersink_read_samples(AVFilterContext *ctx, AVFilterBufferRef **buf, int nb_samples); #endif /** * Get a frame with filtered data from sink and put it in frame. * * @param ctx pointer to a buffersink or abuffersink filter context. * @param frame pointer to an allocated frame that will be filled with data. * The data must be freed using av_frame_unref() / av_frame_free() * @param flags a combination of AV_BUFFERSINK_FLAG_* flags * * @return >= 0 in for success, a negative AVERROR code for failure. */ int av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags); /** * Tell av_buffersink_get_buffer_ref() to read video/samples buffer * reference, but not remove it from the buffer. This is useful if you * need only to read a video/samples buffer, without to fetch it. */ #define AV_BUFFERSINK_FLAG_PEEK 1 /** * Tell av_buffersink_get_buffer_ref() not to request a frame from its input. * If a frame is already buffered, it is read (and removed from the buffer), * but if no frame is present, return AVERROR(EAGAIN). */ #define AV_BUFFERSINK_FLAG_NO_REQUEST 2 /** * Struct to use for initializing a buffersink context. */ typedef struct { const enum AVPixelFormat *pixel_fmts; ///< list of allowed pixel formats, terminated by AV_PIX_FMT_NONE } AVBufferSinkParams; /** * Create an AVBufferSinkParams structure. * * Must be freed with av_free(). */ AVBufferSinkParams *av_buffersink_params_alloc(void); /** * Struct to use for initializing an abuffersink context. */ typedef struct { const enum AVSampleFormat *sample_fmts; ///< list of allowed sample formats, terminated by AV_SAMPLE_FMT_NONE const int64_t *channel_layouts; ///< list of allowed channel layouts, terminated by -1 const int *channel_counts; ///< list of allowed channel counts, terminated by -1 int all_channel_counts; ///< if not 0, accept any channel count or layout int *sample_rates; ///< list of allowed sample rates, terminated by -1 } AVABufferSinkParams; /** * Create an AVABufferSinkParams structure. * * Must be freed with av_free(). */ AVABufferSinkParams *av_abuffersink_params_alloc(void); /** * Set the frame size for an audio buffer sink. * * All calls to av_buffersink_get_buffer_ref will return a buffer with * exactly the specified number of samples, or AVERROR(EAGAIN) if there is * not enough. The last buffer at EOF will be padded with 0. */ void av_buffersink_set_frame_size(AVFilterContext *ctx, unsigned frame_size); /** * Get the frame rate of the input. */ AVRational av_buffersink_get_frame_rate(AVFilterContext *ctx); /** * Get a frame with filtered data from sink and put it in frame. * * @param ctx pointer to a context of a buffersink or abuffersink AVFilter. * @param frame pointer to an allocated frame that will be filled with data. * The data must be freed using av_frame_unref() / av_frame_free() * * @return * - >= 0 if a frame was successfully returned. * - AVERROR(EAGAIN) if no frames are available at this point; more * input frames must be added to the filtergraph to get more output. * - AVERROR_EOF if there will be no more output frames on this sink. * - A different negative AVERROR code in other failure cases. */ int av_buffersink_get_frame(AVFilterContext *ctx, AVFrame *frame); /** * Same as av_buffersink_get_frame(), but with the ability to specify the number * of samples read. This function is less efficient than * av_buffersink_get_frame(), because it copies the data around. * * @param ctx pointer to a context of the abuffersink AVFilter. * @param frame pointer to an allocated frame that will be filled with data. * The data must be freed using av_frame_unref() / av_frame_free() * frame will contain exactly nb_samples audio samples, except at * the end of stream, when it can contain less than nb_samples. * * @return The return codes have the same meaning as for * av_buffersink_get_samples(). * * @warning do not mix this function with av_buffersink_get_frame(). Use only one or * the other with a single sink, not both. */ int av_buffersink_get_samples(AVFilterContext *ctx, AVFrame *frame, int nb_samples); /** * @} */ #endif /* AVFILTER_BUFFERSINK_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavfilter/buffersrc.h ================================================ /* * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_BUFFERSRC_H #define AVFILTER_BUFFERSRC_H /** * @file * @ingroup lavfi_buffersrc * Memory buffer source API. */ #include "libavcodec/avcodec.h" #include "avfilter.h" /** * @defgroup lavfi_buffersrc Buffer source API * @ingroup lavfi * @{ */ enum { /** * Do not check for format changes. */ AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = 1, #if FF_API_AVFILTERBUFFER /** * Ignored */ AV_BUFFERSRC_FLAG_NO_COPY = 2, #endif /** * Immediately push the frame to the output. */ AV_BUFFERSRC_FLAG_PUSH = 4, /** * Keep a reference to the frame. * If the frame if reference-counted, create a new reference; otherwise * copy the frame data. */ AV_BUFFERSRC_FLAG_KEEP_REF = 8, }; /** * Add buffer data in picref to buffer_src. * * @param buffer_src pointer to a buffer source context * @param picref a buffer reference, or NULL to mark EOF * @param flags a combination of AV_BUFFERSRC_FLAG_* * @return >= 0 in case of success, a negative AVERROR code * in case of failure */ int av_buffersrc_add_ref(AVFilterContext *buffer_src, AVFilterBufferRef *picref, int flags); /** * Get the number of failed requests. * * A failed request is when the request_frame method is called while no * frame is present in the buffer. * The number is reset when a frame is added. */ unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src); #if FF_API_AVFILTERBUFFER /** * Add a buffer to a filtergraph. * * @param ctx an instance of the buffersrc filter * @param buf buffer containing frame data to be passed down the filtergraph. * This function will take ownership of buf, the user must not free it. * A NULL buf signals EOF -- i.e. no more frames will be sent to this filter. * * @deprecated use av_buffersrc_write_frame() or av_buffersrc_add_frame() */ attribute_deprecated int av_buffersrc_buffer(AVFilterContext *ctx, AVFilterBufferRef *buf); #endif /** * Add a frame to the buffer source. * * @param ctx an instance of the buffersrc filter * @param frame frame to be added. If the frame is reference counted, this * function will make a new reference to it. Otherwise the frame data will be * copied. * * @return 0 on success, a negative AVERROR on error * * This function is equivalent to av_buffersrc_add_frame_flags() with the * AV_BUFFERSRC_FLAG_KEEP_REF flag. */ int av_buffersrc_write_frame(AVFilterContext *ctx, const AVFrame *frame); /** * Add a frame to the buffer source. * * @param ctx an instance of the buffersrc filter * @param frame frame to be added. If the frame is reference counted, this * function will take ownership of the reference(s) and reset the frame. * Otherwise the frame data will be copied. If this function returns an error, * the input frame is not touched. * * @return 0 on success, a negative AVERROR on error. * * @note the difference between this function and av_buffersrc_write_frame() is * that av_buffersrc_write_frame() creates a new reference to the input frame, * while this function takes ownership of the reference passed to it. * * This function is equivalent to av_buffersrc_add_frame_flags() without the * AV_BUFFERSRC_FLAG_KEEP_REF flag. */ int av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame); /** * Add a frame to the buffer source. * * By default, if the frame is reference-counted, this function will take * ownership of the reference(s) and reset the frame. This can be controled * using the flags. * * If this function returns an error, the input frame is not touched. * * @param buffer_src pointer to a buffer source context * @param frame a frame, or NULL to mark EOF * @param flags a combination of AV_BUFFERSRC_FLAG_* * @return >= 0 in case of success, a negative AVERROR code * in case of failure */ int av_buffersrc_add_frame_flags(AVFilterContext *buffer_src, AVFrame *frame, int flags); /** * @} */ #endif /* AVFILTER_BUFFERSRC_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavfilter/version.h ================================================ /* * Version macros. * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_VERSION_H #define AVFILTER_VERSION_H /** * @file * @ingroup lavfi * Libavfilter version macros */ #include "libavutil/version.h" #define LIBAVFILTER_VERSION_MAJOR 4 #define LIBAVFILTER_VERSION_MINOR 2 #define LIBAVFILTER_VERSION_MICRO 100 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \ LIBAVFILTER_VERSION_MINOR, \ LIBAVFILTER_VERSION_MICRO) #define LIBAVFILTER_VERSION AV_VERSION(LIBAVFILTER_VERSION_MAJOR, \ LIBAVFILTER_VERSION_MINOR, \ LIBAVFILTER_VERSION_MICRO) #define LIBAVFILTER_BUILD LIBAVFILTER_VERSION_INT #define LIBAVFILTER_IDENT "Lavfi" AV_STRINGIFY(LIBAVFILTER_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #ifndef FF_API_AVFILTERPAD_PUBLIC #define FF_API_AVFILTERPAD_PUBLIC (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_FOO_COUNT #define FF_API_FOO_COUNT (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_FILL_FRAME #define FF_API_FILL_FRAME (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_BUFFERSRC_BUFFER #define FF_API_BUFFERSRC_BUFFER (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_AVFILTERBUFFER #define FF_API_AVFILTERBUFFER (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_OLD_FILTER_OPTS #define FF_API_OLD_FILTER_OPTS (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_ACONVERT_FILTER #define FF_API_ACONVERT_FILTER (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_AVFILTER_OPEN #define FF_API_AVFILTER_OPEN (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_AVFILTER_INIT_FILTER #define FF_API_AVFILTER_INIT_FILTER (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_OLD_FILTER_REGISTER #define FF_API_OLD_FILTER_REGISTER (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_OLD_GRAPH_PARSE #define FF_API_OLD_GRAPH_PARSE (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_DRAWTEXT_OLD_TIMELINE #define FF_API_DRAWTEXT_OLD_TIMELINE (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_NOCONST_GET_NAME #define FF_API_NOCONST_GET_NAME (LIBAVFILTER_VERSION_MAJOR < 5) #endif #ifndef FF_API_INTERLACE_LOWPASS_SET #define FF_API_INTERLACE_LOWPASS_SET (LIBAVFILTER_VERSION_MAJOR < 5) #endif #endif /* AVFILTER_VERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavformat/avformat.h ================================================ /* * copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_AVFORMAT_H #define AVFORMAT_AVFORMAT_H /** * @file * @ingroup libavf * Main libavformat public API header */ /** * @defgroup libavf I/O and Muxing/Demuxing Library * @{ * * Libavformat (lavf) is a library for dealing with various media container * formats. Its main two purposes are demuxing - i.e. splitting a media file * into component streams, and the reverse process of muxing - writing supplied * data in a specified container format. It also has an @ref lavf_io * "I/O module" which supports a number of protocols for accessing the data (e.g. * file, tcp, http and others). Before using lavf, you need to call * av_register_all() to register all compiled muxers, demuxers and protocols. * Unless you are absolutely sure you won't use libavformat's network * capabilities, you should also call avformat_network_init(). * * A supported input format is described by an AVInputFormat struct, conversely * an output format is described by AVOutputFormat. You can iterate over all * registered input/output formats using the av_iformat_next() / * av_oformat_next() functions. The protocols layer is not part of the public * API, so you can only get the names of supported protocols with the * avio_enum_protocols() function. * * Main lavf structure used for both muxing and demuxing is AVFormatContext, * which exports all information about the file being read or written. As with * most Libavformat structures, its size is not part of public ABI, so it cannot be * allocated on stack or directly with av_malloc(). To create an * AVFormatContext, use avformat_alloc_context() (some functions, like * avformat_open_input() might do that for you). * * Most importantly an AVFormatContext contains: * @li the @ref AVFormatContext.iformat "input" or @ref AVFormatContext.oformat * "output" format. It is either autodetected or set by user for input; * always set by user for output. * @li an @ref AVFormatContext.streams "array" of AVStreams, which describe all * elementary streams stored in the file. AVStreams are typically referred to * using their index in this array. * @li an @ref AVFormatContext.pb "I/O context". It is either opened by lavf or * set by user for input, always set by user for output (unless you are dealing * with an AVFMT_NOFILE format). * * @section lavf_options Passing options to (de)muxers * Lavf allows to configure muxers and demuxers using the @ref avoptions * mechanism. Generic (format-independent) libavformat options are provided by * AVFormatContext, they can be examined from a user program by calling * av_opt_next() / av_opt_find() on an allocated AVFormatContext (or its AVClass * from avformat_get_class()). Private (format-specific) options are provided by * AVFormatContext.priv_data if and only if AVInputFormat.priv_class / * AVOutputFormat.priv_class of the corresponding format struct is non-NULL. * Further options may be provided by the @ref AVFormatContext.pb "I/O context", * if its AVClass is non-NULL, and the protocols layer. See the discussion on * nesting in @ref avoptions documentation to learn how to access those. * * @defgroup lavf_decoding Demuxing * @{ * Demuxers read a media file and split it into chunks of data (@em packets). A * @ref AVPacket "packet" contains one or more encoded frames which belongs to a * single elementary stream. In the lavf API this process is represented by the * avformat_open_input() function for opening a file, av_read_frame() for * reading a single packet and finally avformat_close_input(), which does the * cleanup. * * @section lavf_decoding_open Opening a media file * The minimum information required to open a file is its URL or filename, which * is passed to avformat_open_input(), as in the following code: * @code * const char *url = "in.mp3"; * AVFormatContext *s = NULL; * int ret = avformat_open_input(&s, url, NULL, NULL); * if (ret < 0) * abort(); * @endcode * The above code attempts to allocate an AVFormatContext, open the * specified file (autodetecting the format) and read the header, exporting the * information stored there into s. Some formats do not have a header or do not * store enough information there, so it is recommended that you call the * avformat_find_stream_info() function which tries to read and decode a few * frames to find missing information. * * In some cases you might want to preallocate an AVFormatContext yourself with * avformat_alloc_context() and do some tweaking on it before passing it to * avformat_open_input(). One such case is when you want to use custom functions * for reading input data instead of lavf internal I/O layer. * To do that, create your own AVIOContext with avio_alloc_context(), passing * your reading callbacks to it. Then set the @em pb field of your * AVFormatContext to newly created AVIOContext. * * Since the format of the opened file is in general not known until after * avformat_open_input() has returned, it is not possible to set demuxer private * options on a preallocated context. Instead, the options should be passed to * avformat_open_input() wrapped in an AVDictionary: * @code * AVDictionary *options = NULL; * av_dict_set(&options, "video_size", "640x480", 0); * av_dict_set(&options, "pixel_format", "rgb24", 0); * * if (avformat_open_input(&s, url, NULL, &options) < 0) * abort(); * av_dict_free(&options); * @endcode * This code passes the private options 'video_size' and 'pixel_format' to the * demuxer. They would be necessary for e.g. the rawvideo demuxer, since it * cannot know how to interpret raw video data otherwise. If the format turns * out to be something different than raw video, those options will not be * recognized by the demuxer and therefore will not be applied. Such unrecognized * options are then returned in the options dictionary (recognized options are * consumed). The calling program can handle such unrecognized options as it * wishes, e.g. * @code * AVDictionaryEntry *e; * if (e = av_dict_get(options, "", NULL, AV_DICT_IGNORE_SUFFIX)) { * fprintf(stderr, "Option %s not recognized by the demuxer.\n", e->key); * abort(); * } * @endcode * * After you have finished reading the file, you must close it with * avformat_close_input(). It will free everything associated with the file. * * @section lavf_decoding_read Reading from an opened file * Reading data from an opened AVFormatContext is done by repeatedly calling * av_read_frame() on it. Each call, if successful, will return an AVPacket * containing encoded data for one AVStream, identified by * AVPacket.stream_index. This packet may be passed straight into the libavcodec * decoding functions avcodec_decode_video2(), avcodec_decode_audio4() or * avcodec_decode_subtitle2() if the caller wishes to decode the data. * * AVPacket.pts, AVPacket.dts and AVPacket.duration timing information will be * set if known. They may also be unset (i.e. AV_NOPTS_VALUE for * pts/dts, 0 for duration) if the stream does not provide them. The timing * information will be in AVStream.time_base units, i.e. it has to be * multiplied by the timebase to convert them to seconds. * * If AVPacket.buf is set on the returned packet, then the packet is * allocated dynamically and the user may keep it indefinitely. * Otherwise, if AVPacket.buf is NULL, the packet data is backed by a * static storage somewhere inside the demuxer and the packet is only valid * until the next av_read_frame() call or closing the file. If the caller * requires a longer lifetime, av_dup_packet() will make an av_malloc()ed copy * of it. * In both cases, the packet must be freed with av_free_packet() when it is no * longer needed. * * @section lavf_decoding_seek Seeking * @} * * @defgroup lavf_encoding Muxing * @{ * Muxers take encoded data in the form of @ref AVPacket "AVPackets" and write * it into files or other output bytestreams in the specified container format. * * The main API functions for muxing are avformat_write_header() for writing the * file header, av_write_frame() / av_interleaved_write_frame() for writing the * packets and av_write_trailer() for finalizing the file. * * At the beginning of the muxing process, the caller must first call * avformat_alloc_context() to create a muxing context. The caller then sets up * the muxer by filling the various fields in this context: * * - The @ref AVFormatContext.oformat "oformat" field must be set to select the * muxer that will be used. * - Unless the format is of the AVFMT_NOFILE type, the @ref AVFormatContext.pb * "pb" field must be set to an opened IO context, either returned from * avio_open2() or a custom one. * - Unless the format is of the AVFMT_NOSTREAMS type, at least one stream must * be created with the avformat_new_stream() function. The caller should fill * the @ref AVStream.codec "stream codec context" information, such as the * codec @ref AVCodecContext.codec_type "type", @ref AVCodecContext.codec_id * "id" and other parameters (e.g. width / height, the pixel or sample format, * etc.) as known. The @ref AVCodecContext.time_base "codec timebase" should * be set to the timebase that the caller desires to use for this stream (note * that the timebase actually used by the muxer can be different, as will be * described later). * - The caller may fill in additional information, such as @ref * AVFormatContext.metadata "global" or @ref AVStream.metadata "per-stream" * metadata, @ref AVFormatContext.chapters "chapters", @ref * AVFormatContext.programs "programs", etc. as described in the * AVFormatContext documentation. Whether such information will actually be * stored in the output depends on what the container format and the muxer * support. * * When the muxing context is fully set up, the caller must call * avformat_write_header() to initialize the muxer internals and write the file * header. Whether anything actually is written to the IO context at this step * depends on the muxer, but this function must always be called. Any muxer * private options must be passed in the options parameter to this function. * * The data is then sent to the muxer by repeatedly calling av_write_frame() or * av_interleaved_write_frame() (consult those functions' documentation for * discussion on the difference between them; only one of them may be used with * a single muxing context, they should not be mixed). Do note that the timing * information on the packets sent to the muxer must be in the corresponding * AVStream's timebase. That timebase is set by the muxer (in the * avformat_write_header() step) and may be different from the timebase the * caller set on the codec context. * * Once all the data has been written, the caller must call av_write_trailer() * to flush any buffered packets and finalize the output file, then close the IO * context (if any) and finally free the muxing context with * avformat_free_context(). * @} * * @defgroup lavf_io I/O Read/Write * @{ * @} * * @defgroup lavf_codec Demuxers * @{ * @defgroup lavf_codec_native Native Demuxers * @{ * @} * @defgroup lavf_codec_wrappers External library wrappers * @{ * @} * @} * @defgroup lavf_protos I/O Protocols * @{ * @} * @defgroup lavf_internal Internal * @{ * @} * @} * */ #include #include /* FILE */ #include "libavcodec/avcodec.h" #include "libavutil/dict.h" #include "libavutil/log.h" #include "avio.h" #include "libavformat/version.h" struct AVFormatContext; struct AVDeviceInfoList; /** * @defgroup metadata_api Public Metadata API * @{ * @ingroup libavf * The metadata API allows libavformat to export metadata tags to a client * application when demuxing. Conversely it allows a client application to * set metadata when muxing. * * Metadata is exported or set as pairs of key/value strings in the 'metadata' * fields of the AVFormatContext, AVStream, AVChapter and AVProgram structs * using the @ref lavu_dict "AVDictionary" API. Like all strings in FFmpeg, * metadata is assumed to be UTF-8 encoded Unicode. Note that metadata * exported by demuxers isn't checked to be valid UTF-8 in most cases. * * Important concepts to keep in mind: * - Keys are unique; there can never be 2 tags with the same key. This is * also meant semantically, i.e., a demuxer should not knowingly produce * several keys that are literally different but semantically identical. * E.g., key=Author5, key=Author6. In this example, all authors must be * placed in the same tag. * - Metadata is flat, not hierarchical; there are no subtags. If you * want to store, e.g., the email address of the child of producer Alice * and actor Bob, that could have key=alice_and_bobs_childs_email_address. * - Several modifiers can be applied to the tag name. This is done by * appending a dash character ('-') and the modifier name in the order * they appear in the list below -- e.g. foo-eng-sort, not foo-sort-eng. * - language -- a tag whose value is localized for a particular language * is appended with the ISO 639-2/B 3-letter language code. * For example: Author-ger=Michael, Author-eng=Mike * The original/default language is in the unqualified "Author" tag. * A demuxer should set a default if it sets any translated tag. * - sorting -- a modified version of a tag that should be used for * sorting will have '-sort' appended. E.g. artist="The Beatles", * artist-sort="Beatles, The". * * - Demuxers attempt to export metadata in a generic format, however tags * with no generic equivalents are left as they are stored in the container. * Follows a list of generic tag names: * @verbatim album -- name of the set this work belongs to album_artist -- main creator of the set/album, if different from artist. e.g. "Various Artists" for compilation albums. artist -- main creator of the work comment -- any additional description of the file. composer -- who composed the work, if different from artist. copyright -- name of copyright holder. creation_time-- date when the file was created, preferably in ISO 8601. date -- date when the work was created, preferably in ISO 8601. disc -- number of a subset, e.g. disc in a multi-disc collection. encoder -- name/settings of the software/hardware that produced the file. encoded_by -- person/group who created the file. filename -- original name of the file. genre -- . language -- main language in which the work is performed, preferably in ISO 639-2 format. Multiple languages can be specified by separating them with commas. performer -- artist who performed the work, if different from artist. E.g for "Also sprach Zarathustra", artist would be "Richard Strauss" and performer "London Philharmonic Orchestra". publisher -- name of the label/publisher. service_name -- name of the service in broadcasting (channel name). service_provider -- name of the service provider in broadcasting. title -- name of the work. track -- number of this work in the set, can be in form current/total. variant_bitrate -- the total bitrate of the bitrate variant that the current stream is part of @endverbatim * * Look in the examples section for an application example how to use the Metadata API. * * @} */ /* packet functions */ /** * Allocate and read the payload of a packet and initialize its * fields with default values. * * @param s associated IO context * @param pkt packet * @param size desired payload size * @return >0 (read size) if OK, AVERROR_xxx otherwise */ int av_get_packet(AVIOContext *s, AVPacket *pkt, int size); /** * Read data and append it to the current content of the AVPacket. * If pkt->size is 0 this is identical to av_get_packet. * Note that this uses av_grow_packet and thus involves a realloc * which is inefficient. Thus this function should only be used * when there is no reasonable way to know (an upper bound of) * the final size. * * @param s associated IO context * @param pkt packet * @param size amount of data to read * @return >0 (read size) if OK, AVERROR_xxx otherwise, previous data * will not be lost even if an error occurs. */ int av_append_packet(AVIOContext *s, AVPacket *pkt, int size); /*************************************************/ /* fractional numbers for exact pts handling */ /** * The exact value of the fractional number is: 'val + num / den'. * num is assumed to be 0 <= num < den. */ typedef struct AVFrac { int64_t val, num, den; } AVFrac; /*************************************************/ /* input/output formats */ struct AVCodecTag; /** * This structure contains the data a format has to probe a file. */ typedef struct AVProbeData { const char *filename; unsigned char *buf; /**< Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero. */ int buf_size; /**< Size of buf except extra allocated bytes */ } AVProbeData; #define AVPROBE_SCORE_RETRY (AVPROBE_SCORE_MAX/4) #define AVPROBE_SCORE_STREAM_RETRY (AVPROBE_SCORE_MAX/4-1) #define AVPROBE_SCORE_EXTENSION 50 ///< score for file extension #define AVPROBE_SCORE_MAX 100 ///< maximum score #define AVPROBE_PADDING_SIZE 32 ///< extra allocated bytes at the end of the probe buffer /// Demuxer will use avio_open, no opened file should be provided by the caller. #define AVFMT_NOFILE 0x0001 #define AVFMT_NEEDNUMBER 0x0002 /**< Needs '%d' in filename. */ #define AVFMT_SHOW_IDS 0x0008 /**< Show format stream IDs numbers. */ #define AVFMT_RAWPICTURE 0x0020 /**< Format wants AVPicture structure for raw picture data. */ #define AVFMT_GLOBALHEADER 0x0040 /**< Format wants global header. */ #define AVFMT_NOTIMESTAMPS 0x0080 /**< Format does not need / have any timestamps. */ #define AVFMT_GENERIC_INDEX 0x0100 /**< Use generic index building code. */ #define AVFMT_TS_DISCONT 0x0200 /**< Format allows timestamp discontinuities. Note, muxers always require valid (monotone) timestamps */ #define AVFMT_VARIABLE_FPS 0x0400 /**< Format allows variable fps. */ #define AVFMT_NODIMENSIONS 0x0800 /**< Format does not need width/height */ #define AVFMT_NOSTREAMS 0x1000 /**< Format does not require any streams */ #define AVFMT_NOBINSEARCH 0x2000 /**< Format does not allow to fall back on binary search via read_timestamp */ #define AVFMT_NOGENSEARCH 0x4000 /**< Format does not allow to fall back on generic search */ #define AVFMT_NO_BYTE_SEEK 0x8000 /**< Format does not allow seeking by bytes */ #define AVFMT_ALLOW_FLUSH 0x10000 /**< Format allows flushing. If not set, the muxer will not receive a NULL packet in the write_packet function. */ #if LIBAVFORMAT_VERSION_MAJOR <= 54 #define AVFMT_TS_NONSTRICT 0x8020000 //we try to be compatible to the ABIs of ffmpeg and major forks #else #define AVFMT_TS_NONSTRICT 0x20000 #endif /**< Format does not require strictly increasing timestamps, but they must still be monotonic */ #define AVFMT_TS_NEGATIVE 0x40000 /**< Format allows muxing negative timestamps. If not set the timestamp will be shifted in av_write_frame and av_interleaved_write_frame so they start from 0. The user or muxer can override this through AVFormatContext.avoid_negative_ts */ #define AVFMT_SEEK_TO_PTS 0x4000000 /**< Seeking is based on PTS */ /** * @addtogroup lavf_encoding * @{ */ typedef struct AVOutputFormat { const char *name; /** * Descriptive name for the format, meant to be more human-readable * than name. You should use the NULL_IF_CONFIG_SMALL() macro * to define it. */ const char *long_name; const char *mime_type; const char *extensions; /**< comma-separated filename extensions */ /* output support */ enum AVCodecID audio_codec; /**< default audio codec */ enum AVCodecID video_codec; /**< default video codec */ enum AVCodecID subtitle_codec; /**< default subtitle codec */ /** * can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_RAWPICTURE, * AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS, * AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS, AVFMT_ALLOW_FLUSH, * AVFMT_TS_NONSTRICT */ int flags; /** * List of supported codec_id-codec_tag pairs, ordered by "better * choice first". The arrays are all terminated by AV_CODEC_ID_NONE. */ const struct AVCodecTag * const *codec_tag; const AVClass *priv_class; ///< AVClass for the private context /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ struct AVOutputFormat *next; /** * size of private data so that it can be allocated in the wrapper */ int priv_data_size; int (*write_header)(struct AVFormatContext *); /** * Write a packet. If AVFMT_ALLOW_FLUSH is set in flags, * pkt can be NULL in order to flush data buffered in the muxer. * When flushing, return 0 if there still is more data to flush, * or 1 if everything was flushed and there is no more buffered * data. */ int (*write_packet)(struct AVFormatContext *, AVPacket *pkt); int (*write_trailer)(struct AVFormatContext *); /** * Currently only used to set pixel format if not YUV420P. */ int (*interleave_packet)(struct AVFormatContext *, AVPacket *out, AVPacket *in, int flush); /** * Test if the given codec can be stored in this container. * * @return 1 if the codec is supported, 0 if it is not. * A negative number if unknown. * MKTAG('A', 'P', 'I', 'C') if the codec is only supported as AV_DISPOSITION_ATTACHED_PIC */ int (*query_codec)(enum AVCodecID id, int std_compliance); void (*get_output_timestamp)(struct AVFormatContext *s, int stream, int64_t *dts, int64_t *wall); /** * Allows sending messages from application to device. */ int (*control_message)(struct AVFormatContext *s, int type, void *data, size_t data_size); /** * Write an uncoded AVFrame. * * See av_write_uncoded_frame() for details. * * The library will free *frame afterwards, but the muxer can prevent it * by setting the pointer to NULL. */ int (*write_uncoded_frame)(struct AVFormatContext *, int stream_index, AVFrame **frame, unsigned flags); /** * Returns device list with it properties. * @see avdevice_list_devices() for more details. */ int (*get_device_list)(struct AVFormatContext *s, struct AVDeviceInfoList *device_list); } AVOutputFormat; /** * @} */ /** * @addtogroup lavf_decoding * @{ */ typedef struct AVInputFormat { /** * A comma separated list of short names for the format. New names * may be appended with a minor bump. */ const char *name; /** * Descriptive name for the format, meant to be more human-readable * than name. You should use the NULL_IF_CONFIG_SMALL() macro * to define it. */ const char *long_name; /** * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS, * AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH, * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS. */ int flags; /** * If extensions are defined, then no probe is done. You should * usually not use extension format guessing because it is not * reliable enough */ const char *extensions; const struct AVCodecTag * const *codec_tag; const AVClass *priv_class; ///< AVClass for the private context /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ struct AVInputFormat *next; /** * Raw demuxers store their codec ID here. */ int raw_codec_id; /** * Size of private data so that it can be allocated in the wrapper. */ int priv_data_size; /** * Tell if a given file has a chance of being parsed as this format. * The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes * big so you do not have to check for that unless you need more. */ int (*read_probe)(AVProbeData *); /** * Read the format header and initialize the AVFormatContext * structure. Return 0 if OK. Only used in raw format right * now. 'avformat_new_stream' should be called to create new streams. */ int (*read_header)(struct AVFormatContext *); /** * Read one packet and put it in 'pkt'. pts and flags are also * set. 'avformat_new_stream' can be called only if the flag * AVFMTCTX_NOHEADER is used and only in the calling thread (not in a * background thread). * @return 0 on success, < 0 on error. * When returning an error, pkt must not have been allocated * or must be freed before returning */ int (*read_packet)(struct AVFormatContext *, AVPacket *pkt); /** * Close the stream. The AVFormatContext and AVStreams are not * freed by this function */ int (*read_close)(struct AVFormatContext *); /** * Seek to a given timestamp relative to the frames in * stream component stream_index. * @param stream_index Must not be -1. * @param flags Selects which direction should be preferred if no exact * match is available. * @return >= 0 on success (but not necessarily the new offset) */ int (*read_seek)(struct AVFormatContext *, int stream_index, int64_t timestamp, int flags); /** * Get the next timestamp in stream[stream_index].time_base units. * @return the timestamp or AV_NOPTS_VALUE if an error occurred */ int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index, int64_t *pos, int64_t pos_limit); /** * Start/resume playing - only meaningful if using a network-based format * (RTSP). */ int (*read_play)(struct AVFormatContext *); /** * Pause playing - only meaningful if using a network-based format * (RTSP). */ int (*read_pause)(struct AVFormatContext *); /** * Seek to timestamp ts. * Seeking will be done so that the point from which all active streams * can be presented successfully will be closest to ts and within min/max_ts. * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL. */ int (*read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags); /** * Returns device list with it properties. * @see avdevice_list_devices() for more details. */ int (*get_device_list)(struct AVFormatContext *s, struct AVDeviceInfoList *device_list); } AVInputFormat; /** * @} */ enum AVStreamParseType { AVSTREAM_PARSE_NONE, AVSTREAM_PARSE_FULL, /**< full parsing and repack */ AVSTREAM_PARSE_HEADERS, /**< Only parse headers, do not repack. */ AVSTREAM_PARSE_TIMESTAMPS, /**< full parsing and interpolation of timestamps for frames not starting on a packet boundary */ AVSTREAM_PARSE_FULL_ONCE, /**< full parsing and repack of the first frame only, only implemented for H.264 currently */ AVSTREAM_PARSE_FULL_RAW=MKTAG(0,'R','A','W'), /**< full parsing and repack with timestamp and position generation by parser for raw this assumes that each packet in the file contains no demuxer level headers and just codec level data, otherwise position generation would fail */ }; typedef struct AVIndexEntry { int64_t pos; int64_t timestamp; /**< * Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are available * when seeking to this entry. That means preferable PTS on keyframe based formats. * But demuxers can choose to store a different timestamp, if it is more convenient for the implementation or nothing better * is known */ #define AVINDEX_KEYFRAME 0x0001 int flags:2; int size:30; //Yeah, trying to keep the size of this small to reduce memory requirements (it is 24 vs. 32 bytes due to possible 8-byte alignment). int min_distance; /**< Minimum distance between this and the previous keyframe, used to avoid unneeded searching. */ } AVIndexEntry; #define AV_DISPOSITION_DEFAULT 0x0001 #define AV_DISPOSITION_DUB 0x0002 #define AV_DISPOSITION_ORIGINAL 0x0004 #define AV_DISPOSITION_COMMENT 0x0008 #define AV_DISPOSITION_LYRICS 0x0010 #define AV_DISPOSITION_KARAOKE 0x0020 /** * Track should be used during playback by default. * Useful for subtitle track that should be displayed * even when user did not explicitly ask for subtitles. */ #define AV_DISPOSITION_FORCED 0x0040 #define AV_DISPOSITION_HEARING_IMPAIRED 0x0080 /**< stream for hearing impaired audiences */ #define AV_DISPOSITION_VISUAL_IMPAIRED 0x0100 /**< stream for visual impaired audiences */ #define AV_DISPOSITION_CLEAN_EFFECTS 0x0200 /**< stream without voice */ /** * The stream is stored in the file as an attached picture/"cover art" (e.g. * APIC frame in ID3v2). The single packet associated with it will be returned * among the first few packets read from the file unless seeking takes place. * It can also be accessed at any time in AVStream.attached_pic. */ #define AV_DISPOSITION_ATTACHED_PIC 0x0400 /** * To specify text track kind (different from subtitles default). */ #define AV_DISPOSITION_CAPTIONS 0x10000 #define AV_DISPOSITION_DESCRIPTIONS 0x20000 #define AV_DISPOSITION_METADATA 0x40000 /** * Options for behavior on timestamp wrap detection. */ #define AV_PTS_WRAP_IGNORE 0 ///< ignore the wrap #define AV_PTS_WRAP_ADD_OFFSET 1 ///< add the format specific offset on wrap detection #define AV_PTS_WRAP_SUB_OFFSET -1 ///< subtract the format specific offset on wrap detection /** * Stream structure. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVStream) must not be used outside libav*. */ typedef struct AVStream { int index; /**< stream index in AVFormatContext */ /** * Format-specific stream ID. * decoding: set by libavformat * encoding: set by the user, replaced by libavformat if left unset */ int id; /** * Codec context associated with this stream. Allocated and freed by * libavformat. * * - decoding: The demuxer exports codec information stored in the headers * here. * - encoding: The user sets codec information, the muxer writes it to the * output. Mandatory fields as specified in AVCodecContext * documentation must be set even if this AVCodecContext is * not actually used for encoding. */ AVCodecContext *codec; void *priv_data; /** * encoding: pts generation when outputting stream */ struct AVFrac pts; /** * This is the fundamental unit of time (in seconds) in terms * of which frame timestamps are represented. * * decoding: set by libavformat * encoding: set by libavformat in avformat_write_header. The muxer may use the * user-provided value of @ref AVCodecContext.time_base "codec->time_base" * as a hint. */ AVRational time_base; /** * Decoding: pts of the first frame of the stream in presentation order, in stream time base. * Only set this if you are absolutely 100% sure that the value you set * it to really is the pts of the first frame. * This may be undefined (AV_NOPTS_VALUE). * @note The ASF header does NOT contain a correct start_time the ASF * demuxer must NOT set this. */ int64_t start_time; /** * Decoding: duration of the stream, in stream time base. * If a source file does not specify a duration, but does specify * a bitrate, this value will be estimated from bitrate and file size. */ int64_t duration; int64_t nb_frames; ///< number of frames in this stream if known or 0 int disposition; /**< AV_DISPOSITION_* bit field */ enum AVDiscard discard; ///< Selects which packets can be discarded at will and do not need to be demuxed. /** * sample aspect ratio (0 if unknown) * - encoding: Set by user. * - decoding: Set by libavformat. */ AVRational sample_aspect_ratio; AVDictionary *metadata; /** * Average framerate */ AVRational avg_frame_rate; /** * For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet * will contain the attached picture. * * decoding: set by libavformat, must not be modified by the caller. * encoding: unused */ AVPacket attached_pic; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * Stream information used internally by av_find_stream_info() */ #define MAX_STD_TIMEBASES (60*12+6) struct { int64_t last_dts; int64_t duration_gcd; int duration_count; int64_t rfps_duration_sum; double (*duration_error)[2][MAX_STD_TIMEBASES]; int64_t codec_info_duration; int64_t codec_info_duration_fields; /** * 0 -> decoder has not been searched for yet. * >0 -> decoder found * <0 -> decoder with codec_id == -found_decoder has not been found */ int found_decoder; int64_t last_duration; /** * Those are used for average framerate estimation. */ int64_t fps_first_dts; int fps_first_dts_idx; int64_t fps_last_dts; int fps_last_dts_idx; } *info; int pts_wrap_bits; /**< number of bits in pts (used for wrapping control) */ #if FF_API_REFERENCE_DTS /* a hack to keep ABI compatibility for ffmpeg and other applications, which accesses parser even * though it should not */ int64_t do_not_use; #endif // Timestamp generation support: /** * Timestamp corresponding to the last dts sync point. * * Initialized when AVCodecParserContext.dts_sync_point >= 0 and * a DTS is received from the underlying container. Otherwise set to * AV_NOPTS_VALUE by default. */ int64_t first_dts; int64_t cur_dts; int64_t last_IP_pts; int last_IP_duration; /** * Number of packets to buffer for codec probing */ #define MAX_PROBE_PACKETS 2500 int probe_packets; /** * Number of frames that have been demuxed during av_find_stream_info() */ int codec_info_nb_frames; /* av_read_frame() support */ enum AVStreamParseType need_parsing; struct AVCodecParserContext *parser; /** * last packet in packet_buffer for this stream when muxing. */ struct AVPacketList *last_in_packet_buffer; AVProbeData probe_data; #define MAX_REORDER_DELAY 16 int64_t pts_buffer[MAX_REORDER_DELAY+1]; AVIndexEntry *index_entries; /**< Only used if the format does not support seeking natively. */ int nb_index_entries; unsigned int index_entries_allocated_size; /** * Real base framerate of the stream. * This is the lowest framerate with which all timestamps can be * represented accurately (it is the least common multiple of all * framerates in the stream). Note, this value is just a guess! * For example, if the time base is 1/90000 and all frames have either * approximately 3600 or 1800 timer ticks, then r_frame_rate will be 50/1. * * Code outside avformat should access this field using: * av_stream_get/set_r_frame_rate(stream) */ AVRational r_frame_rate; /** * Stream Identifier * This is the MPEG-TS stream identifier +1 * 0 means unknown */ int stream_identifier; int64_t interleaver_chunk_size; int64_t interleaver_chunk_duration; /** * stream probing state * -1 -> probing finished * 0 -> no probing requested * rest -> perform probing with request_probe being the minimum score to accept. * NOT PART OF PUBLIC API */ int request_probe; /** * Indicates that everything up to the next keyframe * should be discarded. */ int skip_to_keyframe; /** * Number of samples to skip at the start of the frame decoded from the next packet. */ int skip_samples; /** * Number of internally decoded frames, used internally in libavformat, do not access * its lifetime differs from info which is why it is not in that structure. */ int nb_decoded_frames; /** * Timestamp offset added to timestamps before muxing * NOT PART OF PUBLIC API */ int64_t mux_ts_offset; /** * Internal data to check for wrapping of the time stamp */ int64_t pts_wrap_reference; /** * Options for behavior, when a wrap is detected. * * Defined by AV_PTS_WRAP_ values. * * If correction is enabled, there are two possibilities: * If the first time stamp is near the wrap point, the wrap offset * will be subtracted, which will create negative time stamps. * Otherwise the offset will be added. */ int pts_wrap_behavior; /** * Internal data to prevent doing update_initial_durations() twice */ int update_initial_durations_done; /** * Internal data to generate dts from pts */ int64_t pts_reorder_error[MAX_REORDER_DELAY+1]; uint8_t pts_reorder_error_count[MAX_REORDER_DELAY+1]; /** * Internal data to analyze DTS and detect faulty mpeg streams */ int64_t last_dts_for_order_check; uint8_t dts_ordered; uint8_t dts_misordered; } AVStream; AVRational av_stream_get_r_frame_rate(const AVStream *s); void av_stream_set_r_frame_rate(AVStream *s, AVRational r); #define AV_PROGRAM_RUNNING 1 /** * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVProgram) must not be used outside libav*. */ typedef struct AVProgram { int id; int flags; enum AVDiscard discard; ///< selects which program to discard and which to feed to the caller unsigned int *stream_index; unsigned int nb_stream_indexes; AVDictionary *metadata; int program_num; int pmt_pid; int pcr_pid; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ int64_t start_time; int64_t end_time; int64_t pts_wrap_reference; ///< reference dts for wrap detection int pts_wrap_behavior; ///< behavior on wrap detection } AVProgram; #define AVFMTCTX_NOHEADER 0x0001 /**< signal that no header is present (streams are added dynamically) */ typedef struct AVChapter { int id; ///< unique ID to identify the chapter AVRational time_base; ///< time base in which the start/end timestamps are specified int64_t start, end; ///< chapter start/end time in time_base units AVDictionary *metadata; } AVChapter; /** * Callback used by devices to communicate with application. */ typedef int (*av_format_control_message)(struct AVFormatContext *s, int type, void *data, size_t data_size); /** * The duration of a video can be estimated through various ways, and this enum can be used * to know how the duration was estimated. */ enum AVDurationEstimationMethod { AVFMT_DURATION_FROM_PTS, ///< Duration accurately estimated from PTSes AVFMT_DURATION_FROM_STREAM, ///< Duration estimated from a stream with a known duration AVFMT_DURATION_FROM_BITRATE ///< Duration estimated from bitrate (less accurate) }; typedef struct AVFormatInternal AVFormatInternal; /** * Format I/O context. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVFormatContext) must not be used outside libav*, use * avformat_alloc_context() to create an AVFormatContext. */ typedef struct AVFormatContext { /** * A class for logging and @ref avoptions. Set by avformat_alloc_context(). * Exports (de)muxer private options if they exist. */ const AVClass *av_class; /** * The input container format. * * Demuxing only, set by avformat_open_input(). */ struct AVInputFormat *iformat; /** * The output container format. * * Muxing only, must be set by the caller before avformat_write_header(). */ struct AVOutputFormat *oformat; /** * Format private data. This is an AVOptions-enabled struct * if and only if iformat/oformat.priv_class is not NULL. * * - muxing: set by avformat_write_header() * - demuxing: set by avformat_open_input() */ void *priv_data; /** * I/O context. * * - demuxing: either set by the user before avformat_open_input() (then * the user must close it manually) or set by avformat_open_input(). * - muxing: set by the user before avformat_write_header(). The caller must * take care of closing / freeing the IO context. * * Do NOT set this field if AVFMT_NOFILE flag is set in * iformat/oformat.flags. In such a case, the (de)muxer will handle * I/O in some other way and this field will be NULL. */ AVIOContext *pb; /* stream info */ int ctx_flags; /**< Format-specific flags, see AVFMTCTX_xx */ /** * Number of elements in AVFormatContext.streams. * * Set by avformat_new_stream(), must not be modified by any other code. */ unsigned int nb_streams; /** * A list of all streams in the file. New streams are created with * avformat_new_stream(). * * - demuxing: streams are created by libavformat in avformat_open_input(). * If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams may also * appear in av_read_frame(). * - muxing: streams are created by the user before avformat_write_header(). * * Freed by libavformat in avformat_free_context(). */ AVStream **streams; /** * input or output filename * * - demuxing: set by avformat_open_input() * - muxing: may be set by the caller before avformat_write_header() */ char filename[1024]; /** * Position of the first frame of the component, in * AV_TIME_BASE fractional seconds. NEVER set this value directly: * It is deduced from the AVStream values. * * Demuxing only, set by libavformat. */ int64_t start_time; /** * Duration of the stream, in AV_TIME_BASE fractional * seconds. Only set this value if you know none of the individual stream * durations and also do not set any of them. This is deduced from the * AVStream values if not set. * * Demuxing only, set by libavformat. */ int64_t duration; /** * Total stream bitrate in bit/s, 0 if not * available. Never set it directly if the file_size and the * duration are known as FFmpeg can compute it automatically. */ int bit_rate; unsigned int packet_size; int max_delay; int flags; #define AVFMT_FLAG_GENPTS 0x0001 ///< Generate missing pts even if it requires parsing future frames. #define AVFMT_FLAG_IGNIDX 0x0002 ///< Ignore index. #define AVFMT_FLAG_NONBLOCK 0x0004 ///< Do not block when reading packets from input. #define AVFMT_FLAG_IGNDTS 0x0008 ///< Ignore DTS on frames that contain both DTS & PTS #define AVFMT_FLAG_NOFILLIN 0x0010 ///< Do not infer any values from other values, just return what is stored in the container #define AVFMT_FLAG_NOPARSE 0x0020 ///< Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fillin code works on frames and no parsing -> no frames. Also seeking to frames can not work if parsing to find frame boundaries has been disabled #define AVFMT_FLAG_NOBUFFER 0x0040 ///< Do not buffer frames when possible #define AVFMT_FLAG_CUSTOM_IO 0x0080 ///< The caller has supplied a custom AVIOContext, don't avio_close() it. #define AVFMT_FLAG_DISCARD_CORRUPT 0x0100 ///< Discard frames marked corrupted #define AVFMT_FLAG_FLUSH_PACKETS 0x0200 ///< Flush the AVIOContext every packet. #define AVFMT_FLAG_MP4A_LATM 0x8000 ///< Enable RTP MP4A-LATM payload #define AVFMT_FLAG_SORT_DTS 0x10000 ///< try to interleave outputted packets by dts (using this flag can slow demuxing down) #define AVFMT_FLAG_PRIV_OPT 0x20000 ///< Enable use of private options by delaying codec open (this could be made default once all code is converted) #define AVFMT_FLAG_KEEP_SIDE_DATA 0x40000 ///< Don't merge side data but keep it separate. /** * Maximum size of the data read from input for determining * the input container format. * Demuxing only, set by the caller before avformat_open_input(). */ unsigned int probesize; /** * Maximum duration (in AV_TIME_BASE units) of the data read * from input in avformat_find_stream_info(). * Demuxing only, set by the caller before avformat_find_stream_info(). */ int max_analyze_duration; const uint8_t *key; int keylen; unsigned int nb_programs; AVProgram **programs; /** * Forced video codec_id. * Demuxing: Set by user. */ enum AVCodecID video_codec_id; /** * Forced audio codec_id. * Demuxing: Set by user. */ enum AVCodecID audio_codec_id; /** * Forced subtitle codec_id. * Demuxing: Set by user. */ enum AVCodecID subtitle_codec_id; /** * Maximum amount of memory in bytes to use for the index of each stream. * If the index exceeds this size, entries will be discarded as * needed to maintain a smaller size. This can lead to slower or less * accurate seeking (depends on demuxer). * Demuxers for which a full in-memory index is mandatory will ignore * this. * - muxing: unused * - demuxing: set by user */ unsigned int max_index_size; /** * Maximum amount of memory in bytes to use for buffering frames * obtained from realtime capture devices. */ unsigned int max_picture_buffer; /** * Number of chapters in AVChapter array. * When muxing, chapters are normally written in the file header, * so nb_chapters should normally be initialized before write_header * is called. Some muxers (e.g. mov and mkv) can also write chapters * in the trailer. To write chapters in the trailer, nb_chapters * must be zero when write_header is called and non-zero when * write_trailer is called. * - muxing: set by user * - demuxing: set by libavformat */ unsigned int nb_chapters; AVChapter **chapters; /** * Metadata that applies to the whole file. * * - demuxing: set by libavformat in avformat_open_input() * - muxing: may be set by the caller before avformat_write_header() * * Freed by libavformat in avformat_free_context(). */ AVDictionary *metadata; /** * Start time of the stream in real world time, in microseconds * since the Unix epoch (00:00 1st January 1970). That is, pts=0 in the * stream was captured at this real world time. * Muxing only, set by the caller before avformat_write_header(). */ int64_t start_time_realtime; /** * The number of frames used for determining the framerate in * avformat_find_stream_info(). * Demuxing only, set by the caller before avformat_find_stream_info(). */ int fps_probe_size; /** * Error recognition; higher values will detect more errors but may * misdetect some more or less valid parts as errors. * Demuxing only, set by the caller before avformat_open_input(). */ int error_recognition; /** * Custom interrupt callbacks for the I/O layer. * * demuxing: set by the user before avformat_open_input(). * muxing: set by the user before avformat_write_header() * (mainly useful for AVFMT_NOFILE formats). The callback * should also be passed to avio_open2() if it's used to * open the file. */ AVIOInterruptCB interrupt_callback; /** * Flags to enable debugging. */ int debug; #define FF_FDEBUG_TS 0x0001 /** * Maximum buffering duration for interleaving. * * To ensure all the streams are interleaved correctly, * av_interleaved_write_frame() will wait until it has at least one packet * for each stream before actually writing any packets to the output file. * When some streams are "sparse" (i.e. there are large gaps between * successive packets), this can result in excessive buffering. * * This field specifies the maximum difference between the timestamps of the * first and the last packet in the muxing queue, above which libavformat * will output a packet regardless of whether it has queued a packet for all * the streams. * * Muxing only, set by the caller before avformat_write_header(). */ int64_t max_interleave_delta; /** * Transport stream id. * This will be moved into demuxer private options. Thus no API/ABI compatibility */ int ts_id; /** * Audio preload in microseconds. * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user via AVOptions (NO direct access) * - decoding: unused */ int audio_preload; /** * Max chunk time in microseconds. * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user via AVOptions (NO direct access) * - decoding: unused */ int max_chunk_duration; /** * Max chunk size in bytes * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user via AVOptions (NO direct access) * - decoding: unused */ int max_chunk_size; /** * forces the use of wallclock timestamps as pts/dts of packets * This has undefined results in the presence of B frames. * - encoding: unused * - decoding: Set by user via AVOptions (NO direct access) */ int use_wallclock_as_timestamps; /** * Avoid negative timestamps during muxing. * 0 -> allow negative timestamps * 1 -> avoid negative timestamps * -1 -> choose automatically (default) * Note, this only works when interleave_packet_per_dts is in use. * - encoding: Set by user via AVOptions (NO direct access) * - decoding: unused */ int avoid_negative_ts; /** * avio flags, used to force AVIO_FLAG_DIRECT. * - encoding: unused * - decoding: Set by user via AVOptions (NO direct access) */ int avio_flags; /** * The duration field can be estimated through various ways, and this field can be used * to know how the duration was estimated. * - encoding: unused * - decoding: Read by user via AVOptions (NO direct access) */ enum AVDurationEstimationMethod duration_estimation_method; /** * Skip initial bytes when opening stream * - encoding: unused * - decoding: Set by user via AVOptions (NO direct access) */ unsigned int skip_initial_bytes; /** * Correct single timestamp overflows * - encoding: unused * - decoding: Set by user via AVOptions (NO direct access) */ unsigned int correct_ts_overflow; /** * Force seeking to any (also non key) frames. * - encoding: unused * - decoding: Set by user via AVOptions (NO direct access) */ int seek2any; /** * Flush the I/O context after each packet. * - encoding: Set by user via AVOptions (NO direct access) * - decoding: unused */ int flush_packets; /** * format probing score. * The maximal score is AVPROBE_SCORE_MAX, its set when the demuxer probes * the format. * - encoding: unused * - decoding: set by avformat, read by user via av_format_get_probe_score() (NO direct access) */ int probe_score; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * This buffer is only needed when packets were already buffered but * not decoded, for example to get the codec parameters in MPEG * streams. */ struct AVPacketList *packet_buffer; struct AVPacketList *packet_buffer_end; /* av_seek_frame() support */ int64_t data_offset; /**< offset of the first packet */ /** * Raw packets from the demuxer, prior to parsing and decoding. * This buffer is used for buffering packets until the codec can * be identified, as parsing cannot be done without knowing the * codec. */ struct AVPacketList *raw_packet_buffer; struct AVPacketList *raw_packet_buffer_end; /** * Packets split by the parser get queued here. */ struct AVPacketList *parse_queue; struct AVPacketList *parse_queue_end; /** * Remaining size available for raw_packet_buffer, in bytes. */ #define RAW_PACKET_BUFFER_SIZE 2500000 int raw_packet_buffer_remaining_size; /** * Offset to remap timestamps to be non-negative. * Expressed in timebase units. * @see AVStream.mux_ts_offset */ int64_t offset; /** * Timebase for the timestamp offset. */ AVRational offset_timebase; /** * An opaque field for libavformat internal usage. * Must not be accessed in any way by callers. */ AVFormatInternal *internal; /** * IO repositioned flag. * This is set by avformat when the underlaying IO context read pointer * is repositioned, for example when doing byte based seeking. * Demuxers can use the flag to detect such changes. */ int io_repositioned; /** * Forced video codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user via av_format_set_video_codec (NO direct access). */ AVCodec *video_codec; /** * Forced audio codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user via av_format_set_audio_codec (NO direct access). */ AVCodec *audio_codec; /** * Forced subtitle codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user via av_format_set_subtitle_codec (NO direct access). */ AVCodec *subtitle_codec; /** * Number of bytes to be written as padding in a metadata header. * Demuxing: Unused. * Muxing: Set by user via av_format_set_metadata_header_padding. */ int metadata_header_padding; /** * User data. * This is a place for some private data of the user. * Mostly usable with control_message_cb or any future callbacks in device's context. */ void *opaque; /** * Callback used by devices to communicate with application. */ av_format_control_message control_message_cb; /** * Output timestamp offset, in microseconds. * Muxing: set by user via AVOptions (NO direct access) */ int64_t output_ts_offset; } AVFormatContext; int av_format_get_probe_score(const AVFormatContext *s); AVCodec * av_format_get_video_codec(const AVFormatContext *s); void av_format_set_video_codec(AVFormatContext *s, AVCodec *c); AVCodec * av_format_get_audio_codec(const AVFormatContext *s); void av_format_set_audio_codec(AVFormatContext *s, AVCodec *c); AVCodec * av_format_get_subtitle_codec(const AVFormatContext *s); void av_format_set_subtitle_codec(AVFormatContext *s, AVCodec *c); int av_format_get_metadata_header_padding(const AVFormatContext *s); void av_format_set_metadata_header_padding(AVFormatContext *s, int c); void * av_format_get_opaque(const AVFormatContext *s); void av_format_set_opaque(AVFormatContext *s, void *opaque); av_format_control_message av_format_get_control_message_cb(const AVFormatContext *s); void av_format_set_control_message_cb(AVFormatContext *s, av_format_control_message callback); /** * Returns the method used to set ctx->duration. * * @return AVFMT_DURATION_FROM_PTS, AVFMT_DURATION_FROM_STREAM, or AVFMT_DURATION_FROM_BITRATE. */ enum AVDurationEstimationMethod av_fmt_ctx_get_duration_estimation_method(const AVFormatContext* ctx); typedef struct AVPacketList { AVPacket pkt; struct AVPacketList *next; } AVPacketList; /** * @defgroup lavf_core Core functions * @ingroup libavf * * Functions for querying libavformat capabilities, allocating core structures, * etc. * @{ */ /** * Return the LIBAVFORMAT_VERSION_INT constant. */ unsigned avformat_version(void); /** * Return the libavformat build-time configuration. */ const char *avformat_configuration(void); /** * Return the libavformat license. */ const char *avformat_license(void); /** * Initialize libavformat and register all the muxers, demuxers and * protocols. If you do not call this function, then you can select * exactly which formats you want to support. * * @see av_register_input_format() * @see av_register_output_format() */ void av_register_all(void); void av_register_input_format(AVInputFormat *format); void av_register_output_format(AVOutputFormat *format); /** * Do global initialization of network components. This is optional, * but recommended, since it avoids the overhead of implicitly * doing the setup for each session. * * Calling this function will become mandatory if using network * protocols at some major version bump. */ int avformat_network_init(void); /** * Undo the initialization done by avformat_network_init. */ int avformat_network_deinit(void); /** * If f is NULL, returns the first registered input format, * if f is non-NULL, returns the next registered input format after f * or NULL if f is the last one. */ AVInputFormat *av_iformat_next(AVInputFormat *f); /** * If f is NULL, returns the first registered output format, * if f is non-NULL, returns the next registered output format after f * or NULL if f is the last one. */ AVOutputFormat *av_oformat_next(AVOutputFormat *f); /** * Allocate an AVFormatContext. * avformat_free_context() can be used to free the context and everything * allocated by the framework within it. */ AVFormatContext *avformat_alloc_context(void); /** * Free an AVFormatContext and all its streams. * @param s context to free */ void avformat_free_context(AVFormatContext *s); /** * Get the AVClass for AVFormatContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avformat_get_class(void); /** * Add a new stream to a media file. * * When demuxing, it is called by the demuxer in read_header(). If the * flag AVFMTCTX_NOHEADER is set in s.ctx_flags, then it may also * be called in read_packet(). * * When muxing, should be called by the user before avformat_write_header(). * * User is required to call avcodec_close() and avformat_free_context() to * clean up the allocation by avformat_new_stream(). * * @param s media file handle * @param c If non-NULL, the AVCodecContext corresponding to the new stream * will be initialized to use this codec. This is needed for e.g. codec-specific * defaults to be set, so codec should be provided if it is known. * * @return newly created stream or NULL on error. */ AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c); AVProgram *av_new_program(AVFormatContext *s, int id); /** * @} */ #if FF_API_ALLOC_OUTPUT_CONTEXT /** * @deprecated deprecated in favor of avformat_alloc_output_context2() */ attribute_deprecated AVFormatContext *avformat_alloc_output_context(const char *format, AVOutputFormat *oformat, const char *filename); #endif /** * Allocate an AVFormatContext for an output format. * avformat_free_context() can be used to free the context and * everything allocated by the framework within it. * * @param *ctx is set to the created format context, or to NULL in * case of failure * @param oformat format to use for allocating the context, if NULL * format_name and filename are used instead * @param format_name the name of output format to use for allocating the * context, if NULL filename is used instead * @param filename the name of the filename to use for allocating the * context, may be NULL * @return >= 0 in case of success, a negative AVERROR code in case of * failure */ int avformat_alloc_output_context2(AVFormatContext **ctx, AVOutputFormat *oformat, const char *format_name, const char *filename); /** * @addtogroup lavf_decoding * @{ */ /** * Find AVInputFormat based on the short name of the input format. */ AVInputFormat *av_find_input_format(const char *short_name); /** * Guess the file format. * * @param pd data to be probed * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. */ AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened); /** * Guess the file format. * * @param pd data to be probed * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. * @param score_max A probe score larger that this is required to accept a * detection, the variable is set to the actual detection * score afterwards. * If the score is <= AVPROBE_SCORE_MAX / 4 it is recommended * to retry with a larger probe buffer. */ AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max); /** * Guess the file format. * * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. * @param score_ret The score of the best detection. */ AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret); /** * Probe a bytestream to determine the input format. Each time a probe returns * with a score that is too low, the probe buffer size is increased and another * attempt is made. When the maximum probe size is reached, the input format * with the highest score is returned. * * @param pb the bytestream to probe * @param fmt the input format is put here * @param filename the filename of the stream * @param logctx the log context * @param offset the offset within the bytestream to probe from * @param max_probe_size the maximum probe buffer size (zero for default) * @return the score in case of success, a negative value corresponding to an * the maximal score is AVPROBE_SCORE_MAX * AVERROR code otherwise */ int av_probe_input_buffer2(AVIOContext *pb, AVInputFormat **fmt, const char *filename, void *logctx, unsigned int offset, unsigned int max_probe_size); /** * Like av_probe_input_buffer2() but returns 0 on success */ int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt, const char *filename, void *logctx, unsigned int offset, unsigned int max_probe_size); /** * Open an input stream and read the header. The codecs are not opened. * The stream must be closed with avformat_close_input(). * * @param ps Pointer to user-supplied AVFormatContext (allocated by avformat_alloc_context). * May be a pointer to NULL, in which case an AVFormatContext is allocated by this * function and written into ps. * Note that a user-supplied AVFormatContext will be freed on failure. * @param filename Name of the stream to open. * @param fmt If non-NULL, this parameter forces a specific input format. * Otherwise the format is autodetected. * @param options A dictionary filled with AVFormatContext and demuxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return 0 on success, a negative AVERROR on failure. * * @note If you want to use custom IO, preallocate the format context and set its pb field. */ int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options); attribute_deprecated int av_demuxer_open(AVFormatContext *ic); #if FF_API_FORMAT_PARAMETERS /** * Read packets of a media file to get stream information. This * is useful for file formats with no headers such as MPEG. This * function also computes the real framerate in case of MPEG-2 repeat * frame mode. * The logical file position is not changed by this function; * examined packets may be buffered for later processing. * * @param ic media file handle * @return >=0 if OK, AVERROR_xxx on error * @todo Let the user decide somehow what information is needed so that * we do not waste time getting stuff the user does not need. * * @deprecated use avformat_find_stream_info. */ attribute_deprecated int av_find_stream_info(AVFormatContext *ic); #endif /** * Read packets of a media file to get stream information. This * is useful for file formats with no headers such as MPEG. This * function also computes the real framerate in case of MPEG-2 repeat * frame mode. * The logical file position is not changed by this function; * examined packets may be buffered for later processing. * * @param ic media file handle * @param options If non-NULL, an ic.nb_streams long array of pointers to * dictionaries, where i-th member contains options for * codec corresponding to i-th stream. * On return each dictionary will be filled with options that were not found. * @return >=0 if OK, AVERROR_xxx on error * * @note this function isn't guaranteed to open all the codecs, so * options being non-empty at return is a perfectly normal behavior. * * @todo Let the user decide somehow what information is needed so that * we do not waste time getting stuff the user does not need. */ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options); /** * Find the programs which belong to a given stream. * * @param ic media file handle * @param last the last found program, the search will start after this * program, or from the beginning if it is NULL * @param s stream index * @return the next program which belongs to s, NULL if no program is found or * the last program is not among the programs of ic. */ AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s); /** * Find the "best" stream in the file. * The best stream is determined according to various heuristics as the most * likely to be what the user expects. * If the decoder parameter is non-NULL, av_find_best_stream will find the * default decoder for the stream's codec; streams for which no decoder can * be found are ignored. * * @param ic media file handle * @param type stream type: video, audio, subtitles, etc. * @param wanted_stream_nb user-requested stream number, * or -1 for automatic selection * @param related_stream try to find a stream related (eg. in the same * program) to this one, or -1 if none * @param decoder_ret if non-NULL, returns the decoder for the * selected stream * @param flags flags; none are currently defined * @return the non-negative stream number in case of success, * AVERROR_STREAM_NOT_FOUND if no stream with the requested type * could be found, * AVERROR_DECODER_NOT_FOUND if streams were found but no decoder * @note If av_find_best_stream returns successfully and decoder_ret is not * NULL, then *decoder_ret is guaranteed to be set to a valid AVCodec. */ int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type, int wanted_stream_nb, int related_stream, AVCodec **decoder_ret, int flags); #if FF_API_READ_PACKET /** * @deprecated use AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE to read raw * unprocessed packets * * Read a transport packet from a media file. * * This function is obsolete and should never be used. * Use av_read_frame() instead. * * @param s media file handle * @param pkt is filled * @return 0 if OK, AVERROR_xxx on error */ attribute_deprecated int av_read_packet(AVFormatContext *s, AVPacket *pkt); #endif /** * Return the next frame of a stream. * This function returns what is stored in the file, and does not validate * that what is there are valid frames for the decoder. It will split what is * stored in the file into frames and return one for each call. It will not * omit invalid data between valid frames so as to give the decoder the maximum * information possible for decoding. * * If pkt->buf is NULL, then the packet is valid until the next * av_read_frame() or until avformat_close_input(). Otherwise the packet * is valid indefinitely. In both cases the packet must be freed with * av_free_packet when it is no longer needed. For video, the packet contains * exactly one frame. For audio, it contains an integer number of frames if each * frame has a known fixed size (e.g. PCM or ADPCM data). If the audio frames * have a variable size (e.g. MPEG audio), then it contains one frame. * * pkt->pts, pkt->dts and pkt->duration are always set to correct * values in AVStream.time_base units (and guessed if the format cannot * provide them). pkt->pts can be AV_NOPTS_VALUE if the video format * has B-frames, so it is better to rely on pkt->dts if you do not * decompress the payload. * * @return 0 if OK, < 0 on error or end of file */ int av_read_frame(AVFormatContext *s, AVPacket *pkt); /** * Seek to the keyframe at timestamp. * 'timestamp' in 'stream_index'. * * @param s media file handle * @param stream_index If stream_index is (-1), a default * stream is selected, and timestamp is automatically converted * from AV_TIME_BASE units to the stream specific time_base. * @param timestamp Timestamp in AVStream.time_base units * or, if no stream is specified, in AV_TIME_BASE units. * @param flags flags which select direction and seeking mode * @return >= 0 on success */ int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags); /** * Seek to timestamp ts. * Seeking will be done so that the point from which all active streams * can be presented successfully will be closest to ts and within min/max_ts. * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL. * * If flags contain AVSEEK_FLAG_BYTE, then all timestamps are in bytes and * are the file position (this may not be supported by all demuxers). * If flags contain AVSEEK_FLAG_FRAME, then all timestamps are in frames * in the stream with stream_index (this may not be supported by all demuxers). * Otherwise all timestamps are in units of the stream selected by stream_index * or if stream_index is -1, in AV_TIME_BASE units. * If flags contain AVSEEK_FLAG_ANY, then non-keyframes are treated as * keyframes (this may not be supported by all demuxers). * If flags contain AVSEEK_FLAG_BACKWARD, it is ignored. * * @param s media file handle * @param stream_index index of the stream which is used as time base reference * @param min_ts smallest acceptable timestamp * @param ts target timestamp * @param max_ts largest acceptable timestamp * @param flags flags * @return >=0 on success, error code otherwise * * @note This is part of the new seek API which is still under construction. * Thus do not use this yet. It may change at any time, do not expect * ABI compatibility yet! */ int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags); /** * Start playing a network-based stream (e.g. RTSP stream) at the * current position. */ int av_read_play(AVFormatContext *s); /** * Pause a network-based stream (e.g. RTSP stream). * * Use av_read_play() to resume it. */ int av_read_pause(AVFormatContext *s); #if FF_API_CLOSE_INPUT_FILE /** * @deprecated use avformat_close_input() * Close a media file (but not its codecs). * * @param s media file handle */ attribute_deprecated void av_close_input_file(AVFormatContext *s); #endif /** * Close an opened input AVFormatContext. Free it and all its contents * and set *s to NULL. */ void avformat_close_input(AVFormatContext **s); /** * @} */ #if FF_API_NEW_STREAM /** * Add a new stream to a media file. * * Can only be called in the read_header() function. If the flag * AVFMTCTX_NOHEADER is in the format context, then new streams * can be added in read_packet too. * * @param s media file handle * @param id file-format-dependent stream ID */ attribute_deprecated AVStream *av_new_stream(AVFormatContext *s, int id); #endif #if FF_API_SET_PTS_INFO /** * @deprecated this function is not supposed to be called outside of lavf */ attribute_deprecated void av_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den); #endif #define AVSEEK_FLAG_BACKWARD 1 ///< seek backward #define AVSEEK_FLAG_BYTE 2 ///< seeking based on position in bytes #define AVSEEK_FLAG_ANY 4 ///< seek to any frame, even non-keyframes #define AVSEEK_FLAG_FRAME 8 ///< seeking based on frame number /** * @addtogroup lavf_encoding * @{ */ /** * Allocate the stream private data and write the stream header to * an output media file. * * @param s Media file handle, must be allocated with avformat_alloc_context(). * Its oformat field must be set to the desired output format; * Its pb field must be set to an already opened AVIOContext. * @param options An AVDictionary filled with AVFormatContext and muxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return 0 on success, negative AVERROR on failure. * * @see av_opt_find, av_dict_set, avio_open, av_oformat_next. */ int avformat_write_header(AVFormatContext *s, AVDictionary **options); /** * Write a packet to an output media file. * * This function passes the packet directly to the muxer, without any buffering * or reordering. The caller is responsible for correctly interleaving the * packets if the format requires it. Callers that want libavformat to handle * the interleaving should call av_interleaved_write_frame() instead of this * function. * * @param s media file handle * @param pkt The packet containing the data to be written. Note that unlike * av_interleaved_write_frame(), this function does not take * ownership of the packet passed to it (though some muxers may make * an internal reference to the input packet). *
* This parameter can be NULL (at any time, not just at the end), in * order to immediately flush data buffered within the muxer, for * muxers that buffer up data internally before writing it to the * output. *
* Packet's @ref AVPacket.stream_index "stream_index" field must be * set to the index of the corresponding stream in @ref * AVFormatContext.streams "s->streams". It is very strongly * recommended that timing information (@ref AVPacket.pts "pts", @ref * AVPacket.dts "dts", @ref AVPacket.duration "duration") is set to * correct values. * @return < 0 on error, = 0 if OK, 1 if flushed and there is no more data to flush * * @see av_interleaved_write_frame() */ int av_write_frame(AVFormatContext *s, AVPacket *pkt); /** * Write a packet to an output media file ensuring correct interleaving. * * This function will buffer the packets internally as needed to make sure the * packets in the output file are properly interleaved in the order of * increasing dts. Callers doing their own interleaving should call * av_write_frame() instead of this function. * * @param s media file handle * @param pkt The packet containing the data to be written. *
* If the packet is reference-counted, this function will take * ownership of this reference and unreference it later when it sees * fit. * The caller must not access the data through this reference after * this function returns. If the packet is not reference-counted, * libavformat will make a copy. *
* This parameter can be NULL (at any time, not just at the end), to * flush the interleaving queues. *
* Packet's @ref AVPacket.stream_index "stream_index" field must be * set to the index of the corresponding stream in @ref * AVFormatContext.streams "s->streams". It is very strongly * recommended that timing information (@ref AVPacket.pts "pts", @ref * AVPacket.dts "dts", @ref AVPacket.duration "duration") is set to * correct values. * * @return 0 on success, a negative AVERROR on error. Libavformat will always * take care of freeing the packet, even if this function fails. * * @see av_write_frame(), AVFormatContext.max_interleave_delta */ int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt); /** * Write a uncoded frame to an output media file. * * The frame must be correctly interleaved according to the container * specification; if not, then av_interleaved_write_frame() must be used. * * See av_interleaved_write_frame() for details. */ int av_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame); /** * Write a uncoded frame to an output media file. * * If the muxer supports it, this function allows to write an AVFrame * structure directly, without encoding it into a packet. * It is mostly useful for devices and similar special muxers that use raw * video or PCM data and will not serialize it into a byte stream. * * To test whether it is possible to use it with a given muxer and stream, * use av_write_uncoded_frame_query(). * * The caller gives up ownership of the frame and must not access it * afterwards. * * @return >=0 for success, a negative code on error */ int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame); /** * Test whether a muxer supports uncoded frame. * * @return >=0 if an uncoded frame can be written to that muxer and stream, * <0 if not */ int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index); /** * Write the stream trailer to an output media file and free the * file private data. * * May only be called after a successful call to avformat_write_header. * * @param s media file handle * @return 0 if OK, AVERROR_xxx on error */ int av_write_trailer(AVFormatContext *s); /** * Return the output format in the list of registered output formats * which best matches the provided parameters, or return NULL if * there is no match. * * @param short_name if non-NULL checks if short_name matches with the * names of the registered formats * @param filename if non-NULL checks if filename terminates with the * extensions of the registered formats * @param mime_type if non-NULL checks if mime_type matches with the * MIME type of the registered formats */ AVOutputFormat *av_guess_format(const char *short_name, const char *filename, const char *mime_type); /** * Guess the codec ID based upon muxer and filename. */ enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name, const char *filename, const char *mime_type, enum AVMediaType type); /** * Get timing information for the data currently output. * The exact meaning of "currently output" depends on the format. * It is mostly relevant for devices that have an internal buffer and/or * work in real time. * @param s media file handle * @param stream stream in the media file * @param[out] dts DTS of the last packet output for the stream, in stream * time_base units * @param[out] wall absolute time when that packet whas output, * in microsecond * @return 0 if OK, AVERROR(ENOSYS) if the format does not support it * Note: some formats or devices may not allow to measure dts and wall * atomically. */ int av_get_output_timestamp(struct AVFormatContext *s, int stream, int64_t *dts, int64_t *wall); /** * @} */ /** * @defgroup lavf_misc Utility functions * @ingroup libavf * @{ * * Miscellaneous utility functions related to both muxing and demuxing * (or neither). */ /** * Send a nice hexadecimal dump of a buffer to the specified file stream. * * @param f The file stream pointer where the dump should be sent to. * @param buf buffer * @param size buffer size * * @see av_hex_dump_log, av_pkt_dump2, av_pkt_dump_log2 */ void av_hex_dump(FILE *f, const uint8_t *buf, int size); /** * Send a nice hexadecimal dump of a buffer to the log. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message, lower values signifying * higher importance. * @param buf buffer * @param size buffer size * * @see av_hex_dump, av_pkt_dump2, av_pkt_dump_log2 */ void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size); /** * Send a nice dump of a packet to the specified file stream. * * @param f The file stream pointer where the dump should be sent to. * @param pkt packet to dump * @param dump_payload True if the payload must be displayed, too. * @param st AVStream that the packet belongs to */ void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st); /** * Send a nice dump of a packet to the log. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message, lower values signifying * higher importance. * @param pkt packet to dump * @param dump_payload True if the payload must be displayed, too. * @param st AVStream that the packet belongs to */ void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload, AVStream *st); /** * Get the AVCodecID for the given codec tag tag. * If no codec id is found returns AV_CODEC_ID_NONE. * * @param tags list of supported codec_id-codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param tag codec tag to match to a codec ID */ enum AVCodecID av_codec_get_id(const struct AVCodecTag * const *tags, unsigned int tag); /** * Get the codec tag for the given codec id id. * If no codec tag is found returns 0. * * @param tags list of supported codec_id-codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param id codec ID to match to a codec tag */ unsigned int av_codec_get_tag(const struct AVCodecTag * const *tags, enum AVCodecID id); /** * Get the codec tag for the given codec id. * * @param tags list of supported codec_id - codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param id codec id that should be searched for in the list * @param tag A pointer to the found tag * @return 0 if id was not found in tags, > 0 if it was found */ int av_codec_get_tag2(const struct AVCodecTag * const *tags, enum AVCodecID id, unsigned int *tag); int av_find_default_stream_index(AVFormatContext *s); /** * Get the index for a specific timestamp. * * @param st stream that the timestamp belongs to * @param timestamp timestamp to retrieve the index for * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond * to the timestamp which is <= the requested one, if backward * is 0, then it will be >= * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise * @return < 0 if no such timestamp could be found */ int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags); /** * Add an index entry into a sorted list. Update the entry if the list * already contains it. * * @param timestamp timestamp in the time base of the given stream */ int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags); /** * Split a URL string into components. * * The pointers to buffers for storing individual components may be null, * in order to ignore that component. Buffers for components not found are * set to empty strings. If the port is not found, it is set to a negative * value. * * @param proto the buffer for the protocol * @param proto_size the size of the proto buffer * @param authorization the buffer for the authorization * @param authorization_size the size of the authorization buffer * @param hostname the buffer for the host name * @param hostname_size the size of the hostname buffer * @param port_ptr a pointer to store the port number in * @param path the buffer for the path * @param path_size the size of the path buffer * @param url the URL to split */ void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url); void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output); /** * Return in 'buf' the path with '%d' replaced by a number. * * Also handles the '%0nd' format where 'n' is the total number * of digits and '%%'. * * @param buf destination buffer * @param buf_size destination buffer size * @param path numbered sequence string * @param number frame number * @return 0 if OK, -1 on format error */ int av_get_frame_filename(char *buf, int buf_size, const char *path, int number); /** * Check whether filename actually is a numbered sequence generator. * * @param filename possible numbered sequence string * @return 1 if a valid numbered sequence string, 0 otherwise */ int av_filename_number_test(const char *filename); /** * Generate an SDP for an RTP session. * * Note, this overwrites the id values of AVStreams in the muxer contexts * for getting unique dynamic payload types. * * @param ac array of AVFormatContexts describing the RTP streams. If the * array is composed by only one context, such context can contain * multiple AVStreams (one AVStream per RTP stream). Otherwise, * all the contexts in the array (an AVCodecContext per RTP stream) * must contain only one AVStream. * @param n_files number of AVCodecContexts contained in ac * @param buf buffer where the SDP will be stored (must be allocated by * the caller) * @param size the size of the buffer * @return 0 if OK, AVERROR_xxx on error */ int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size); /** * Return a positive value if the given filename has one of the given * extensions, 0 otherwise. * * @param filename file name to check against the given extensions * @param extensions a comma-separated list of filename extensions */ int av_match_ext(const char *filename, const char *extensions); /** * Test if the given container can store a codec. * * @param ofmt container to check for compatibility * @param codec_id codec to potentially store in container * @param std_compliance standards compliance level, one of FF_COMPLIANCE_* * * @return 1 if codec with ID codec_id can be stored in ofmt, 0 if it cannot. * A negative number if this information is not available. */ int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance); /** * @defgroup riff_fourcc RIFF FourCCs * @{ * Get the tables mapping RIFF FourCCs to libavcodec AVCodecIDs. The tables are * meant to be passed to av_codec_get_id()/av_codec_get_tag() as in the * following code: * @code * uint32_t tag = MKTAG('H', '2', '6', '4'); * const struct AVCodecTag *table[] = { avformat_get_riff_video_tags(), 0 }; * enum AVCodecID id = av_codec_get_id(table, tag); * @endcode */ /** * @return the table mapping RIFF FourCCs for video to libavcodec AVCodecID. */ const struct AVCodecTag *avformat_get_riff_video_tags(void); /** * @return the table mapping RIFF FourCCs for audio to AVCodecID. */ const struct AVCodecTag *avformat_get_riff_audio_tags(void); /** * @return the table mapping MOV FourCCs for video to libavcodec AVCodecID. */ const struct AVCodecTag *avformat_get_mov_video_tags(void); /** * @return the table mapping MOV FourCCs for audio to AVCodecID. */ const struct AVCodecTag *avformat_get_mov_audio_tags(void); /** * @} */ /** * Guess the sample aspect ratio of a frame, based on both the stream and the * frame aspect ratio. * * Since the frame aspect ratio is set by the codec but the stream aspect ratio * is set by the demuxer, these two may not be equal. This function tries to * return the value that you should use if you would like to display the frame. * * Basic logic is to use the stream aspect ratio if it is set to something sane * otherwise use the frame aspect ratio. This way a container setting, which is * usually easy to modify can override the coded value in the frames. * * @param format the format context which the stream is part of * @param stream the stream which the frame is part of * @param frame the frame with the aspect ratio to be determined * @return the guessed (valid) sample_aspect_ratio, 0/1 if no idea */ AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame); /** * Guess the frame rate, based on both the container and codec information. * * @param ctx the format context which the stream is part of * @param stream the stream which the frame is part of * @param frame the frame for which the frame rate should be determined, may be NULL * @return the guessed (valid) frame rate, 0/1 if no idea */ AVRational av_guess_frame_rate(AVFormatContext *ctx, AVStream *stream, AVFrame *frame); /** * Check if the stream st contained in s is matched by the stream specifier * spec. * * See the "stream specifiers" chapter in the documentation for the syntax * of spec. * * @return >0 if st is matched by spec; * 0 if st is not matched by spec; * AVERROR code if spec is invalid * * @note A stream specifier can match several streams in the format. */ int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec); int avformat_queue_attached_pictures(AVFormatContext *s); /** * @} */ #endif /* AVFORMAT_AVFORMAT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavformat/avio.h ================================================ /* * copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_AVIO_H #define AVFORMAT_AVIO_H /** * @file * @ingroup lavf_io * Buffered I/O operations */ #include #include "libavutil/common.h" #include "libavutil/dict.h" #include "libavutil/log.h" #include "libavformat/version.h" #define AVIO_SEEKABLE_NORMAL 0x0001 /**< Seeking works like for a local file */ /** * Callback for checking whether to abort blocking functions. * AVERROR_EXIT is returned in this case by the interrupted * function. During blocking operations, callback is called with * opaque as parameter. If the callback returns 1, the * blocking operation will be aborted. * * No members can be added to this struct without a major bump, if * new elements have been added after this struct in AVFormatContext * or AVIOContext. */ typedef struct AVIOInterruptCB { int (*callback)(void*); void *opaque; } AVIOInterruptCB; /** * Bytestream IO Context. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVIOContext) must not be used outside libav*. * * @note None of the function pointers in AVIOContext should be called * directly, they should only be set by the client application * when implementing custom I/O. Normally these are set to the * function pointers specified in avio_alloc_context() */ typedef struct AVIOContext { /** * A class for private options. * * If this AVIOContext is created by avio_open2(), av_class is set and * passes the options down to protocols. * * If this AVIOContext is manually allocated, then av_class may be set by * the caller. * * warning -- this field can be NULL, be sure to not pass this AVIOContext * to any av_opt_* functions in that case. */ const AVClass *av_class; unsigned char *buffer; /**< Start of the buffer. */ int buffer_size; /**< Maximum buffer size */ unsigned char *buf_ptr; /**< Current position in the buffer */ unsigned char *buf_end; /**< End of the data, may be less than buffer+buffer_size if the read function returned less data than requested, e.g. for streams where no more data has been received yet. */ void *opaque; /**< A private pointer, passed to the read/write/seek/... functions. */ int (*read_packet)(void *opaque, uint8_t *buf, int buf_size); int (*write_packet)(void *opaque, uint8_t *buf, int buf_size); int64_t (*seek)(void *opaque, int64_t offset, int whence); int64_t pos; /**< position in the file of the current buffer */ int must_flush; /**< true if the next seek should flush */ int eof_reached; /**< true if eof reached */ int write_flag; /**< true if open for writing */ int max_packet_size; unsigned long checksum; unsigned char *checksum_ptr; unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size); int error; /**< contains the error code or 0 if no error happened */ /** * Pause or resume playback for network streaming protocols - e.g. MMS. */ int (*read_pause)(void *opaque, int pause); /** * Seek to a given timestamp in stream with the specified stream_index. * Needed for some network streaming protocols which don't support seeking * to byte position. */ int64_t (*read_seek)(void *opaque, int stream_index, int64_t timestamp, int flags); /** * A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable. */ int seekable; /** * max filesize, used to limit allocations * This field is internal to libavformat and access from outside is not allowed. */ int64_t maxsize; /** * avio_read and avio_write should if possible be satisfied directly * instead of going through a buffer, and avio_seek will always * call the underlying seek function directly. */ int direct; /** * Bytes read statistic * This field is internal to libavformat and access from outside is not allowed. */ int64_t bytes_read; /** * seek statistic * This field is internal to libavformat and access from outside is not allowed. */ int seek_count; /** * writeout statistic * This field is internal to libavformat and access from outside is not allowed. */ int writeout_count; } AVIOContext; /* unbuffered I/O */ /** * Return the name of the protocol that will handle the passed URL. * * NULL is returned if no protocol could be found for the given URL. * * @return Name of the protocol or NULL. */ const char *avio_find_protocol_name(const char *url); /** * Return AVIO_FLAG_* access flags corresponding to the access permissions * of the resource in url, or a negative value corresponding to an * AVERROR code in case of failure. The returned access flags are * masked by the value in flags. * * @note This function is intrinsically unsafe, in the sense that the * checked resource may change its existence or permission status from * one call to another. Thus you should not trust the returned value, * unless you are sure that no other processes are accessing the * checked resource. */ int avio_check(const char *url, int flags); /** * Allocate and initialize an AVIOContext for buffered I/O. It must be later * freed with av_free(). * * @param buffer Memory block for input/output operations via AVIOContext. * The buffer must be allocated with av_malloc() and friends. * @param buffer_size The buffer size is very important for performance. * For protocols with fixed blocksize it should be set to this blocksize. * For others a typical size is a cache page, e.g. 4kb. * @param write_flag Set to 1 if the buffer should be writable, 0 otherwise. * @param opaque An opaque pointer to user-specific data. * @param read_packet A function for refilling the buffer, may be NULL. * @param write_packet A function for writing the buffer contents, may be NULL. * The function may not change the input buffers content. * @param seek A function for seeking to specified byte position, may be NULL. * * @return Allocated AVIOContext or NULL on failure. */ AVIOContext *avio_alloc_context( unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int (*read_packet)(void *opaque, uint8_t *buf, int buf_size), int (*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t (*seek)(void *opaque, int64_t offset, int whence)); void avio_w8(AVIOContext *s, int b); void avio_write(AVIOContext *s, const unsigned char *buf, int size); void avio_wl64(AVIOContext *s, uint64_t val); void avio_wb64(AVIOContext *s, uint64_t val); void avio_wl32(AVIOContext *s, unsigned int val); void avio_wb32(AVIOContext *s, unsigned int val); void avio_wl24(AVIOContext *s, unsigned int val); void avio_wb24(AVIOContext *s, unsigned int val); void avio_wl16(AVIOContext *s, unsigned int val); void avio_wb16(AVIOContext *s, unsigned int val); /** * Write a NULL-terminated string. * @return number of bytes written. */ int avio_put_str(AVIOContext *s, const char *str); /** * Convert an UTF-8 string to UTF-16LE and write it. * @return number of bytes written. */ int avio_put_str16le(AVIOContext *s, const char *str); /** * Passing this as the "whence" parameter to a seek function causes it to * return the filesize without seeking anywhere. Supporting this is optional. * If it is not supported then the seek function will return <0. */ #define AVSEEK_SIZE 0x10000 /** * Oring this flag as into the "whence" parameter to a seek function causes it to * seek by any means (like reopening and linear reading) or other normally unreasonable * means that can be extremely slow. * This may be ignored by the seek code. */ #define AVSEEK_FORCE 0x20000 /** * fseek() equivalent for AVIOContext. * @return new position or AVERROR. */ int64_t avio_seek(AVIOContext *s, int64_t offset, int whence); /** * Skip given number of bytes forward * @return new position or AVERROR. */ int64_t avio_skip(AVIOContext *s, int64_t offset); /** * ftell() equivalent for AVIOContext. * @return position or AVERROR. */ static av_always_inline int64_t avio_tell(AVIOContext *s) { return avio_seek(s, 0, SEEK_CUR); } /** * Get the filesize. * @return filesize or AVERROR */ int64_t avio_size(AVIOContext *s); /** * feof() equivalent for AVIOContext. * @return non zero if and only if end of file */ int url_feof(AVIOContext *s); /** @warning currently size is limited */ int avio_printf(AVIOContext *s, const char *fmt, ...) av_printf_format(2, 3); /** * Force flushing of buffered data to the output s. * * Force the buffered data to be immediately written to the output, * without to wait to fill the internal buffer. */ void avio_flush(AVIOContext *s); /** * Read size bytes from AVIOContext into buf. * @return number of bytes read or AVERROR */ int avio_read(AVIOContext *s, unsigned char *buf, int size); /** * @name Functions for reading from AVIOContext * @{ * * @note return 0 if EOF, so you cannot use it if EOF handling is * necessary */ int avio_r8 (AVIOContext *s); unsigned int avio_rl16(AVIOContext *s); unsigned int avio_rl24(AVIOContext *s); unsigned int avio_rl32(AVIOContext *s); uint64_t avio_rl64(AVIOContext *s); unsigned int avio_rb16(AVIOContext *s); unsigned int avio_rb24(AVIOContext *s); unsigned int avio_rb32(AVIOContext *s); uint64_t avio_rb64(AVIOContext *s); /** * @} */ /** * Read a string from pb into buf. The reading will terminate when either * a NULL character was encountered, maxlen bytes have been read, or nothing * more can be read from pb. The result is guaranteed to be NULL-terminated, it * will be truncated if buf is too small. * Note that the string is not interpreted or validated in any way, it * might get truncated in the middle of a sequence for multi-byte encodings. * * @return number of bytes read (is always <= maxlen). * If reading ends on EOF or error, the return value will be one more than * bytes actually read. */ int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen); /** * Read a UTF-16 string from pb and convert it to UTF-8. * The reading will terminate when either a null or invalid character was * encountered or maxlen bytes have been read. * @return number of bytes read (is always <= maxlen) */ int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen); int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen); /** * @name URL open modes * The flags argument to avio_open must be one of the following * constants, optionally ORed with other flags. * @{ */ #define AVIO_FLAG_READ 1 /**< read-only */ #define AVIO_FLAG_WRITE 2 /**< write-only */ #define AVIO_FLAG_READ_WRITE (AVIO_FLAG_READ|AVIO_FLAG_WRITE) /**< read-write pseudo flag */ /** * @} */ /** * Use non-blocking mode. * If this flag is set, operations on the context will return * AVERROR(EAGAIN) if they can not be performed immediately. * If this flag is not set, operations on the context will never return * AVERROR(EAGAIN). * Note that this flag does not affect the opening/connecting of the * context. Connecting a protocol will always block if necessary (e.g. on * network protocols) but never hang (e.g. on busy devices). * Warning: non-blocking protocols is work-in-progress; this flag may be * silently ignored. */ #define AVIO_FLAG_NONBLOCK 8 /** * Use direct mode. * avio_read and avio_write should if possible be satisfied directly * instead of going through a buffer, and avio_seek will always * call the underlying seek function directly. */ #define AVIO_FLAG_DIRECT 0x8000 /** * Create and initialize a AVIOContext for accessing the * resource indicated by url. * @note When the resource indicated by url has been opened in * read+write mode, the AVIOContext can be used only for writing. * * @param s Used to return the pointer to the created AVIOContext. * In case of failure the pointed to value is set to NULL. * @param url resource to access * @param flags flags which control how the resource indicated by url * is to be opened * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code in case of failure */ int avio_open(AVIOContext **s, const char *url, int flags); /** * Create and initialize a AVIOContext for accessing the * resource indicated by url. * @note When the resource indicated by url has been opened in * read+write mode, the AVIOContext can be used only for writing. * * @param s Used to return the pointer to the created AVIOContext. * In case of failure the pointed to value is set to NULL. * @param url resource to access * @param flags flags which control how the resource indicated by url * is to be opened * @param int_cb an interrupt callback to be used at the protocols level * @param options A dictionary filled with protocol-private options. On return * this parameter will be destroyed and replaced with a dict containing options * that were not found. May be NULL. * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code in case of failure */ int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options); /** * Close the resource accessed by the AVIOContext s and free it. * This function can only be used if s was opened by avio_open(). * * The internal buffer is automatically flushed before closing the * resource. * * @return 0 on success, an AVERROR < 0 on error. * @see avio_closep */ int avio_close(AVIOContext *s); /** * Close the resource accessed by the AVIOContext *s, free it * and set the pointer pointing to it to NULL. * This function can only be used if s was opened by avio_open(). * * The internal buffer is automatically flushed before closing the * resource. * * @return 0 on success, an AVERROR < 0 on error. * @see avio_close */ int avio_closep(AVIOContext **s); /** * Open a write only memory stream. * * @param s new IO context * @return zero if no error. */ int avio_open_dyn_buf(AVIOContext **s); /** * Return the written size and a pointer to the buffer. The buffer * must be freed with av_free(). * Padding of FF_INPUT_BUFFER_PADDING_SIZE is added to the buffer. * * @param s IO context * @param pbuffer pointer to a byte buffer * @return the length of the byte buffer */ int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer); /** * Iterate through names of available protocols. * * @param opaque A private pointer representing current protocol. * It must be a pointer to NULL on first iteration and will * be updated by successive calls to avio_enum_protocols. * @param output If set to 1, iterate over output protocols, * otherwise over input protocols. * * @return A static string containing the name of current protocol or NULL */ const char *avio_enum_protocols(void **opaque, int output); /** * Pause and resume playing - only meaningful if using a network streaming * protocol (e.g. MMS). * * @param h IO context from which to call the read_pause function pointer * @param pause 1 for pause, 0 for resume */ int avio_pause(AVIOContext *h, int pause); /** * Seek to a given timestamp relative to some component stream. * Only meaningful if using a network streaming protocol (e.g. MMS.). * * @param h IO context from which to call the seek function pointers * @param stream_index The stream index that the timestamp is relative to. * If stream_index is (-1) the timestamp should be in AV_TIME_BASE * units from the beginning of the presentation. * If a stream_index >= 0 is used and the protocol does not support * seeking based on component streams, the call will fail. * @param timestamp timestamp in AVStream.time_base units * or if there is no stream specified then in AV_TIME_BASE units. * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE * and AVSEEK_FLAG_ANY. The protocol may silently ignore * AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will * fail if used and not supported. * @return >= 0 on success * @see AVInputFormat::read_seek */ int64_t avio_seek_time(AVIOContext *h, int stream_index, int64_t timestamp, int flags); #endif /* AVFORMAT_AVIO_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavformat/version.h ================================================ /* * Version macros. * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_VERSION_H #define AVFORMAT_VERSION_H /** * @file * @ingroup libavf * Libavformat version macros */ #include "libavutil/version.h" #define LIBAVFORMAT_VERSION_MAJOR 55 #define LIBAVFORMAT_VERSION_MINOR 33 #define LIBAVFORMAT_VERSION_MICRO 100 #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \ LIBAVFORMAT_VERSION_MINOR, \ LIBAVFORMAT_VERSION_MICRO) #define LIBAVFORMAT_VERSION AV_VERSION(LIBAVFORMAT_VERSION_MAJOR, \ LIBAVFORMAT_VERSION_MINOR, \ LIBAVFORMAT_VERSION_MICRO) #define LIBAVFORMAT_BUILD LIBAVFORMAT_VERSION_INT #define LIBAVFORMAT_IDENT "Lavf" AV_STRINGIFY(LIBAVFORMAT_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #ifndef FF_API_REFERENCE_DTS #define FF_API_REFERENCE_DTS (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_ALLOC_OUTPUT_CONTEXT #define FF_API_ALLOC_OUTPUT_CONTEXT (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_FORMAT_PARAMETERS #define FF_API_FORMAT_PARAMETERS (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_NEW_STREAM #define FF_API_NEW_STREAM (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_SET_PTS_INFO #define FF_API_SET_PTS_INFO (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_CLOSE_INPUT_FILE #define FF_API_CLOSE_INPUT_FILE (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_READ_PACKET #define FF_API_READ_PACKET (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_ASS_SSA #define FF_API_ASS_SSA (LIBAVFORMAT_VERSION_MAJOR < 56) #endif #ifndef FF_API_R_FRAME_RATE #define FF_API_R_FRAME_RATE 1 #endif #endif /* AVFORMAT_VERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/adler32.h ================================================ /* * copyright (c) 2006 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_ADLER32_H #define AVUTIL_ADLER32_H #include #include "attributes.h" /** * @file * Public header for libavutil Adler32 hasher * * @defgroup lavu_adler32 Adler32 * @ingroup lavu_crypto * @{ */ /** * Calculate the Adler32 checksum of a buffer. * * Passing the return value to a subsequent av_adler32_update() call * allows the checksum of multiple buffers to be calculated as though * they were concatenated. * * @param adler initial checksum value * @param buf pointer to input buffer * @param len size of input buffer * @return updated checksum */ unsigned long av_adler32_update(unsigned long adler, const uint8_t *buf, unsigned int len) av_pure; /** * @} */ #endif /* AVUTIL_ADLER32_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/aes.h ================================================ /* * copyright (c) 2007 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AES_H #define AVUTIL_AES_H #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_aes AES * @ingroup lavu_crypto * @{ */ extern const int av_aes_size; struct AVAES; /** * Allocate an AVAES context. */ struct AVAES *av_aes_alloc(void); /** * Initialize an AVAES context. * @param key_bits 128, 192 or 256 * @param decrypt 0 for encryption, 1 for decryption */ int av_aes_init(struct AVAES *a, const uint8_t *key, int key_bits, int decrypt); /** * Encrypt or decrypt a buffer using a previously initialized context. * @param count number of 16 byte blocks * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param iv initialization vector for CBC mode, if NULL then ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_aes_crypt(struct AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_AES_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/attributes.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Macro definitions for various function/variable attributes */ #ifndef AVUTIL_ATTRIBUTES_H #define AVUTIL_ATTRIBUTES_H #ifdef __GNUC__ # define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > x || __GNUC__ == x && __GNUC_MINOR__ >= y) #else # define AV_GCC_VERSION_AT_LEAST(x,y) 0 #endif #ifndef av_always_inline #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_always_inline __attribute__((always_inline)) inline #elif defined(_MSC_VER) # define av_always_inline __forceinline #else # define av_always_inline inline #endif #endif #ifndef av_extern_inline #if defined(__ICL) && __ICL >= 1210 || defined(__GNUC_STDC_INLINE__) # define av_extern_inline extern inline #else # define av_extern_inline inline #endif #endif #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_noinline __attribute__((noinline)) #elif defined(_MSC_VER) # define av_noinline __declspec(noinline) #else # define av_noinline #endif #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_pure __attribute__((pure)) #else # define av_pure #endif #if AV_GCC_VERSION_AT_LEAST(2,6) # define av_const __attribute__((const)) #else # define av_const #endif #if AV_GCC_VERSION_AT_LEAST(4,3) # define av_cold __attribute__((cold)) #else # define av_cold #endif #if AV_GCC_VERSION_AT_LEAST(4,1) && !defined(__llvm__) # define av_flatten __attribute__((flatten)) #else # define av_flatten #endif #if AV_GCC_VERSION_AT_LEAST(3,1) # define attribute_deprecated __attribute__((deprecated)) #elif defined(_MSC_VER) # define attribute_deprecated __declspec(deprecated) #else # define attribute_deprecated #endif /** * Disable warnings about deprecated features * This is useful for sections of code kept for backward compatibility and * scheduled for removal. */ #ifndef AV_NOWARN_DEPRECATED #if AV_GCC_VERSION_AT_LEAST(4,6) # define AV_NOWARN_DEPRECATED(code) \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \ code \ _Pragma("GCC diagnostic pop") #elif defined(_MSC_VER) # define AV_NOWARN_DEPRECATED(code) \ __pragma(warning(push)) \ __pragma(warning(disable : 4996)) \ code; \ __pragma(warning(pop)) #else # define AV_NOWARN_DEPRECATED(code) code #endif #endif #if defined(__GNUC__) # define av_unused __attribute__((unused)) #else # define av_unused #endif /** * Mark a variable as used and prevent the compiler from optimizing it * away. This is useful for variables accessed only from inline * assembler without the compiler being aware. */ #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_used __attribute__((used)) #else # define av_used #endif #if AV_GCC_VERSION_AT_LEAST(3,3) # define av_alias __attribute__((may_alias)) #else # define av_alias #endif #if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !defined(__clang__) # define av_uninit(x) x=x #else # define av_uninit(x) x #endif #ifdef __GNUC__ # define av_builtin_constant_p __builtin_constant_p # define av_printf_format(fmtpos, attrpos) __attribute__((__format__(__printf__, fmtpos, attrpos))) #else # define av_builtin_constant_p(x) 0 # define av_printf_format(fmtpos, attrpos) #endif #if AV_GCC_VERSION_AT_LEAST(2,5) # define av_noreturn __attribute__((noreturn)) #else # define av_noreturn #endif #endif /* AVUTIL_ATTRIBUTES_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/audio_fifo.h ================================================ /* * Audio FIFO * Copyright (c) 2012 Justin Ruggles * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Audio FIFO Buffer */ #ifndef AVUTIL_AUDIO_FIFO_H #define AVUTIL_AUDIO_FIFO_H #include "avutil.h" #include "fifo.h" #include "samplefmt.h" /** * @addtogroup lavu_audio * @{ */ /** * Context for an Audio FIFO Buffer. * * - Operates at the sample level rather than the byte level. * - Supports multiple channels with either planar or packed sample format. * - Automatic reallocation when writing to a full buffer. */ typedef struct AVAudioFifo AVAudioFifo; /** * Free an AVAudioFifo. * * @param af AVAudioFifo to free */ void av_audio_fifo_free(AVAudioFifo *af); /** * Allocate an AVAudioFifo. * * @param sample_fmt sample format * @param channels number of channels * @param nb_samples initial allocation size, in samples * @return newly allocated AVAudioFifo, or NULL on error */ AVAudioFifo *av_audio_fifo_alloc(enum AVSampleFormat sample_fmt, int channels, int nb_samples); /** * Reallocate an AVAudioFifo. * * @param af AVAudioFifo to reallocate * @param nb_samples new allocation size, in samples * @return 0 if OK, or negative AVERROR code on failure */ int av_audio_fifo_realloc(AVAudioFifo *af, int nb_samples); /** * Write data to an AVAudioFifo. * * The AVAudioFifo will be reallocated automatically if the available space * is less than nb_samples. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param af AVAudioFifo to write to * @param data audio data plane pointers * @param nb_samples number of samples to write * @return number of samples actually written, or negative AVERROR * code on failure. If successful, the number of samples * actually written will always be nb_samples. */ int av_audio_fifo_write(AVAudioFifo *af, void **data, int nb_samples); /** * Read data from an AVAudioFifo. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param af AVAudioFifo to read from * @param data audio data plane pointers * @param nb_samples number of samples to read * @return number of samples actually read, or negative AVERROR code * on failure. The number of samples actually read will not * be greater than nb_samples, and will only be less than * nb_samples if av_audio_fifo_size is less than nb_samples. */ int av_audio_fifo_read(AVAudioFifo *af, void **data, int nb_samples); /** * Drain data from an AVAudioFifo. * * Removes the data without reading it. * * @param af AVAudioFifo to drain * @param nb_samples number of samples to drain * @return 0 if OK, or negative AVERROR code on failure */ int av_audio_fifo_drain(AVAudioFifo *af, int nb_samples); /** * Reset the AVAudioFifo buffer. * * This empties all data in the buffer. * * @param af AVAudioFifo to reset */ void av_audio_fifo_reset(AVAudioFifo *af); /** * Get the current number of samples in the AVAudioFifo available for reading. * * @param af the AVAudioFifo to query * @return number of samples available for reading */ int av_audio_fifo_size(AVAudioFifo *af); /** * Get the current number of samples in the AVAudioFifo available for writing. * * @param af the AVAudioFifo to query * @return number of samples available for writing */ int av_audio_fifo_space(AVAudioFifo *af); /** * @} */ #endif /* AVUTIL_AUDIO_FIFO_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/audioconvert.h ================================================ #include "version.h" #if FF_API_AUDIOCONVERT #include "channel_layout.h" #endif ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/avassert.h ================================================ /* * copyright (c) 2010 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * simple assert() macros that are a bit more flexible than ISO C assert(). * @author Michael Niedermayer */ #ifndef AVUTIL_AVASSERT_H #define AVUTIL_AVASSERT_H #include #include "avutil.h" #include "log.h" /** * assert() equivalent, that is always enabled. */ #define av_assert0(cond) do { \ if (!(cond)) { \ av_log(NULL, AV_LOG_PANIC, "Assertion %s failed at %s:%d\n", \ AV_STRINGIFY(cond), __FILE__, __LINE__); \ abort(); \ } \ } while (0) /** * assert() equivalent, that does not lie in speed critical code. * These asserts() thus can be enabled without fearing speedloss. */ #if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 0 #define av_assert1(cond) av_assert0(cond) #else #define av_assert1(cond) ((void)0) #endif /** * assert() equivalent, that does lie in speed critical code. */ #if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 1 #define av_assert2(cond) av_assert0(cond) #else #define av_assert2(cond) ((void)0) #endif #endif /* AVUTIL_AVASSERT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/avconfig.h ================================================ /* Generated by ffconf */ #ifndef AVUTIL_AVCONFIG_H #define AVUTIL_AVCONFIG_H #define AV_HAVE_BIGENDIAN 0 #define AV_HAVE_FAST_UNALIGNED 1 #define AV_HAVE_INCOMPATIBLE_LIBAV_ABI 0 #define AV_HAVE_INCOMPATIBLE_FORK_ABI 0 #endif /* AVUTIL_AVCONFIG_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/avstring.h ================================================ /* * Copyright (c) 2007 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVSTRING_H #define AVUTIL_AVSTRING_H #include #include #include "attributes.h" /** * @addtogroup lavu_string * @{ */ /** * Return non-zero if pfx is a prefix of str. If it is, *ptr is set to * the address of the first character in str after the prefix. * * @param str input string * @param pfx prefix to test * @param ptr updated if the prefix is matched inside str * @return non-zero if the prefix matches, zero otherwise */ int av_strstart(const char *str, const char *pfx, const char **ptr); /** * Return non-zero if pfx is a prefix of str independent of case. If * it is, *ptr is set to the address of the first character in str * after the prefix. * * @param str input string * @param pfx prefix to test * @param ptr updated if the prefix is matched inside str * @return non-zero if the prefix matches, zero otherwise */ int av_stristart(const char *str, const char *pfx, const char **ptr); /** * Locate the first case-independent occurrence in the string haystack * of the string needle. A zero-length string needle is considered to * match at the start of haystack. * * This function is a case-insensitive version of the standard strstr(). * * @param haystack string to search in * @param needle string to search for * @return pointer to the located match within haystack * or a null pointer if no match */ char *av_stristr(const char *haystack, const char *needle); /** * Locate the first occurrence of the string needle in the string haystack * where not more than hay_length characters are searched. A zero-length * string needle is considered to match at the start of haystack. * * This function is a length-limited version of the standard strstr(). * * @param haystack string to search in * @param needle string to search for * @param hay_length length of string to search in * @return pointer to the located match within haystack * or a null pointer if no match */ char *av_strnstr(const char *haystack, const char *needle, size_t hay_length); /** * Copy the string src to dst, but no more than size - 1 bytes, and * null-terminate dst. * * This function is the same as BSD strlcpy(). * * @param dst destination buffer * @param src source string * @param size size of destination buffer * @return the length of src * * @warning since the return value is the length of src, src absolutely * _must_ be a properly 0-terminated string, otherwise this will read beyond * the end of the buffer and possibly crash. */ size_t av_strlcpy(char *dst, const char *src, size_t size); /** * Append the string src to the string dst, but to a total length of * no more than size - 1 bytes, and null-terminate dst. * * This function is similar to BSD strlcat(), but differs when * size <= strlen(dst). * * @param dst destination buffer * @param src source string * @param size size of destination buffer * @return the total length of src and dst * * @warning since the return value use the length of src and dst, these * absolutely _must_ be a properly 0-terminated strings, otherwise this * will read beyond the end of the buffer and possibly crash. */ size_t av_strlcat(char *dst, const char *src, size_t size); /** * Append output to a string, according to a format. Never write out of * the destination buffer, and always put a terminating 0 within * the buffer. * @param dst destination buffer (string to which the output is * appended) * @param size total size of the destination buffer * @param fmt printf-compatible format string, specifying how the * following parameters are used * @return the length of the string that would have been generated * if enough space had been available */ size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...) av_printf_format(3, 4); /** * Get the count of continuous non zero chars starting from the beginning. * * @param len maximum number of characters to check in the string, that * is the maximum value which is returned by the function */ static inline size_t av_strnlen(const char *s, size_t len) { size_t i; for (i = 0; i < len && s[i]; i++) ; return i; } /** * Print arguments following specified format into a large enough auto * allocated buffer. It is similar to GNU asprintf(). * @param fmt printf-compatible format string, specifying how the * following parameters are used. * @return the allocated string * @note You have to free the string yourself with av_free(). */ char *av_asprintf(const char *fmt, ...) av_printf_format(1, 2); /** * Convert a number to a av_malloced string. */ char *av_d2str(double d); /** * Unescape the given string until a non escaped terminating char, * and return the token corresponding to the unescaped string. * * The normal \ and ' escaping is supported. Leading and trailing * whitespaces are removed, unless they are escaped with '\' or are * enclosed between ''. * * @param buf the buffer to parse, buf will be updated to point to the * terminating char * @param term a 0-terminated list of terminating chars * @return the malloced unescaped string, which must be av_freed by * the user, NULL in case of allocation failure */ char *av_get_token(const char **buf, const char *term); /** * Split the string into several tokens which can be accessed by * successive calls to av_strtok(). * * A token is defined as a sequence of characters not belonging to the * set specified in delim. * * On the first call to av_strtok(), s should point to the string to * parse, and the value of saveptr is ignored. In subsequent calls, s * should be NULL, and saveptr should be unchanged since the previous * call. * * This function is similar to strtok_r() defined in POSIX.1. * * @param s the string to parse, may be NULL * @param delim 0-terminated list of token delimiters, must be non-NULL * @param saveptr user-provided pointer which points to stored * information necessary for av_strtok() to continue scanning the same * string. saveptr is updated to point to the next character after the * first delimiter found, or to NULL if the string was terminated * @return the found token, or NULL when no token is found */ char *av_strtok(char *s, const char *delim, char **saveptr); /** * Locale-independent conversion of ASCII isdigit. */ int av_isdigit(int c); /** * Locale-independent conversion of ASCII isgraph. */ int av_isgraph(int c); /** * Locale-independent conversion of ASCII isspace. */ int av_isspace(int c); /** * Locale-independent conversion of ASCII characters to uppercase. */ static inline int av_toupper(int c) { if (c >= 'a' && c <= 'z') c ^= 0x20; return c; } /** * Locale-independent conversion of ASCII characters to lowercase. */ static inline int av_tolower(int c) { if (c >= 'A' && c <= 'Z') c ^= 0x20; return c; } /** * Locale-independent conversion of ASCII isxdigit. */ int av_isxdigit(int c); /** * Locale-independent case-insensitive compare. * @note This means only ASCII-range characters are case-insensitive */ int av_strcasecmp(const char *a, const char *b); /** * Locale-independent case-insensitive compare. * @note This means only ASCII-range characters are case-insensitive */ int av_strncasecmp(const char *a, const char *b, size_t n); /** * Thread safe basename. * @param path the path, on DOS both \ and / are considered separators. * @return pointer to the basename substring. */ const char *av_basename(const char *path); /** * Thread safe dirname. * @param path the path, on DOS both \ and / are considered separators. * @return the path with the separator replaced by the string terminator or ".". * @note the function may change the input string. */ const char *av_dirname(char *path); enum AVEscapeMode { AV_ESCAPE_MODE_AUTO, ///< Use auto-selected escaping mode. AV_ESCAPE_MODE_BACKSLASH, ///< Use backslash escaping. AV_ESCAPE_MODE_QUOTE, ///< Use single-quote escaping. }; /** * Consider spaces special and escape them even in the middle of the * string. * * This is equivalent to adding the whitespace characters to the special * characters lists, except it is guaranteed to use the exact same list * of whitespace characters as the rest of libavutil. */ #define AV_ESCAPE_FLAG_WHITESPACE 0x01 /** * Escape only specified special characters. * Without this flag, escape also any characters that may be considered * special by av_get_token(), such as the single quote. */ #define AV_ESCAPE_FLAG_STRICT 0x02 /** * Escape string in src, and put the escaped string in an allocated * string in *dst, which must be freed with av_free(). * * @param dst pointer where an allocated string is put * @param src string to escape, must be non-NULL * @param special_chars string containing the special characters which * need to be escaped, can be NULL * @param mode escape mode to employ, see AV_ESCAPE_MODE_* macros. * Any unknown value for mode will be considered equivalent to * AV_ESCAPE_MODE_BACKSLASH, but this behaviour can change without * notice. * @param flags flags which control how to escape, see AV_ESCAPE_FLAG_ macros * @return the length of the allocated string, or a negative error code in case of error * @see av_bprint_escape() */ int av_escape(char **dst, const char *src, const char *special_chars, enum AVEscapeMode mode, int flags); #define AV_UTF8_FLAG_ACCEPT_INVALID_BIG_CODES 1 ///< accept codepoints over 0x10FFFF #define AV_UTF8_FLAG_ACCEPT_NON_CHARACTERS 2 ///< accept non-characters - 0xFFFE and 0xFFFF #define AV_UTF8_FLAG_ACCEPT_SURROGATES 4 ///< accept UTF-16 surrogates codes #define AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES 8 ///< exclude control codes not accepted by XML #define AV_UTF8_FLAG_ACCEPT_ALL \ AV_UTF8_FLAG_ACCEPT_INVALID_BIG_CODES|AV_UTF8_FLAG_ACCEPT_NON_CHARACTERS|AV_UTF8_FLAG_ACCEPT_SURROGATES /** * Read and decode a single UTF-8 code point (character) from the * buffer in *buf, and update *buf to point to the next byte to * decode. * * In case of an invalid byte sequence, the pointer will be updated to * the next byte after the invalid sequence and the function will * return an error code. * * Depending on the specified flags, the function will also fail in * case the decoded code point does not belong to a valid range. * * @note For speed-relevant code a carefully implemented use of * GET_UTF8() may be preferred. * * @param codep pointer used to return the parsed code in case of success. * The value in *codep is set even in case the range check fails. * @param bufp pointer to the address the first byte of the sequence * to decode, updated by the function to point to the * byte next after the decoded sequence * @param buf_end pointer to the end of the buffer, points to the next * byte past the last in the buffer. This is used to * avoid buffer overreads (in case of an unfinished * UTF-8 sequence towards the end of the buffer). * @param flags a collection of AV_UTF8_FLAG_* flags * @return >= 0 in case a sequence was successfully read, a negative * value in case of invalid sequence */ int av_utf8_decode(int32_t *codep, const uint8_t **bufp, const uint8_t *buf_end, unsigned int flags); /** * @} */ #endif /* AVUTIL_AVSTRING_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/avutil.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVUTIL_H #define AVUTIL_AVUTIL_H /** * @file * external API header */ /** * @mainpage * * @section ffmpeg_intro Introduction * * This document describes the usage of the different libraries * provided by FFmpeg. * * @li @ref libavc "libavcodec" encoding/decoding library * @li @ref lavfi "libavfilter" graph-based frame editing library * @li @ref libavf "libavformat" I/O and muxing/demuxing library * @li @ref lavd "libavdevice" special devices muxing/demuxing library * @li @ref lavu "libavutil" common utility library * @li @ref lswr "libswresample" audio resampling, format conversion and mixing * @li @ref lpp "libpostproc" post processing library * @li @ref libsws "libswscale" color conversion and scaling library * * @section ffmpeg_versioning Versioning and compatibility * * Each of the FFmpeg libraries contains a version.h header, which defines a * major, minor and micro version number with the * LIBRARYNAME_VERSION_{MAJOR,MINOR,MICRO} macros. The major version * number is incremented with backward incompatible changes - e.g. removing * parts of the public API, reordering public struct members, etc. The minor * version number is incremented for backward compatible API changes or major * new features - e.g. adding a new public function or a new decoder. The micro * version number is incremented for smaller changes that a calling program * might still want to check for - e.g. changing behavior in a previously * unspecified situation. * * FFmpeg guarantees backward API and ABI compatibility for each library as long * as its major version number is unchanged. This means that no public symbols * will be removed or renamed. Types and names of the public struct members and * values of public macros and enums will remain the same (unless they were * explicitly declared as not part of the public API). Documented behavior will * not change. * * In other words, any correct program that works with a given FFmpeg snapshot * should work just as well without any changes with any later snapshot with the * same major versions. This applies to both rebuilding the program against new * FFmpeg versions or to replacing the dynamic FFmpeg libraries that a program * links against. * * However, new public symbols may be added and new members may be appended to * public structs whose size is not part of public ABI (most public structs in * FFmpeg). New macros and enum values may be added. Behavior in undocumented * situations may change slightly (and be documented). All those are accompanied * by an entry in doc/APIchanges and incrementing either the minor or micro * version number. */ /** * @defgroup lavu Common utility functions * * @brief * libavutil contains the code shared across all the other FFmpeg * libraries * * @note In order to use the functions provided by avutil you must include * the specific header. * * @{ * * @defgroup lavu_crypto Crypto and Hashing * * @{ * @} * * @defgroup lavu_math Maths * @{ * * @} * * @defgroup lavu_string String Manipulation * * @{ * * @} * * @defgroup lavu_mem Memory Management * * @{ * * @} * * @defgroup lavu_data Data Structures * @{ * * @} * * @defgroup lavu_audio Audio related * * @{ * * @} * * @defgroup lavu_error Error Codes * * @{ * * @} * * @defgroup lavu_log Logging Facility * * @{ * * @} * * @defgroup lavu_misc Other * * @{ * * @defgroup lavu_internal Internal * * Not exported functions, for internal usage only * * @{ * * @} * * @defgroup preproc_misc Preprocessor String Macros * * @{ * * @} */ /** * @addtogroup lavu_ver * @{ */ /** * Return the LIBAVUTIL_VERSION_INT constant. */ unsigned avutil_version(void); /** * Return the libavutil build-time configuration. */ const char *avutil_configuration(void); /** * Return the libavutil license. */ const char *avutil_license(void); /** * @} */ /** * @addtogroup lavu_media Media Type * @brief Media Type */ enum AVMediaType { AVMEDIA_TYPE_UNKNOWN = -1, ///< Usually treated as AVMEDIA_TYPE_DATA AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA, ///< Opaque data information usually continuous AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_ATTACHMENT, ///< Opaque data information usually sparse AVMEDIA_TYPE_NB }; /** * Return a string describing the media_type enum, NULL if media_type * is unknown. */ const char *av_get_media_type_string(enum AVMediaType media_type); /** * @defgroup lavu_const Constants * @{ * * @defgroup lavu_enc Encoding specific * * @note those definition should move to avcodec * @{ */ #define FF_LAMBDA_SHIFT 7 #define FF_LAMBDA_SCALE (1< /** * @defgroup lavu_base64 Base64 * @ingroup lavu_crypto * @{ */ /** * Decode a base64-encoded string. * * @param out buffer for decoded data * @param in null-terminated input string * @param out_size size in bytes of the out buffer, must be at * least 3/4 of the length of in * @return number of bytes written, or a negative value in case of * invalid input */ int av_base64_decode(uint8_t *out, const char *in, int out_size); /** * Encode data to base64 and null-terminate. * * @param out buffer for encoded data * @param out_size size in bytes of the out buffer (including the * null terminator), must be at least AV_BASE64_SIZE(in_size) * @param in input buffer containing the data to encode * @param in_size size in bytes of the in buffer * @return out or NULL in case of error */ char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size); /** * Calculate the output size needed to base64-encode x bytes to a * null-terminated string. */ #define AV_BASE64_SIZE(x) (((x)+2) / 3 * 4 + 1) /** * @} */ #endif /* AVUTIL_BASE64_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/blowfish.h ================================================ /* * Blowfish algorithm * Copyright (c) 2012 Samuel Pitoiset * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_BLOWFISH_H #define AVUTIL_BLOWFISH_H #include /** * @defgroup lavu_blowfish Blowfish * @ingroup lavu_crypto * @{ */ #define AV_BF_ROUNDS 16 typedef struct AVBlowfish { uint32_t p[AV_BF_ROUNDS + 2]; uint32_t s[4][256]; } AVBlowfish; /** * Initialize an AVBlowfish context. * * @param ctx an AVBlowfish context * @param key a key * @param key_len length of the key */ void av_blowfish_init(struct AVBlowfish *ctx, const uint8_t *key, int key_len); /** * Encrypt or decrypt a buffer using a previously initialized context. * * @param ctx an AVBlowfish context * @param xl left four bytes halves of input to be encrypted * @param xr right four bytes halves of input to be encrypted * @param decrypt 0 for encryption, 1 for decryption */ void av_blowfish_crypt_ecb(struct AVBlowfish *ctx, uint32_t *xl, uint32_t *xr, int decrypt); /** * Encrypt or decrypt a buffer using a previously initialized context. * * @param ctx an AVBlowfish context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param iv initialization vector for CBC mode, if NULL ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_blowfish_crypt(struct AVBlowfish *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_BLOWFISH_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/bprint.h ================================================ /* * Copyright (c) 2012 Nicolas George * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_BPRINT_H #define AVUTIL_BPRINT_H #include #include "attributes.h" #include "avstring.h" /** * Define a structure with extra padding to a fixed size * This helps ensuring binary compatibility with future versions. */ #define FF_PAD_STRUCTURE(size, ...) \ __VA_ARGS__ \ char reserved_padding[size - sizeof(struct { __VA_ARGS__ })]; /** * Buffer to print data progressively * * The string buffer grows as necessary and is always 0-terminated. * The content of the string is never accessed, and thus is * encoding-agnostic and can even hold binary data. * * Small buffers are kept in the structure itself, and thus require no * memory allocation at all (unless the contents of the buffer is needed * after the structure goes out of scope). This is almost as lightweight as * declaring a local "char buf[512]". * * The length of the string can go beyond the allocated size: the buffer is * then truncated, but the functions still keep account of the actual total * length. * * In other words, buf->len can be greater than buf->size and records the * total length of what would have been to the buffer if there had been * enough memory. * * Append operations do not need to be tested for failure: if a memory * allocation fails, data stop being appended to the buffer, but the length * is still updated. This situation can be tested with * av_bprint_is_complete(). * * The size_max field determines several possible behaviours: * * size_max = -1 (= UINT_MAX) or any large value will let the buffer be * reallocated as necessary, with an amortized linear cost. * * size_max = 0 prevents writing anything to the buffer: only the total * length is computed. The write operations can then possibly be repeated in * a buffer with exactly the necessary size * (using size_init = size_max = len + 1). * * size_max = 1 is automatically replaced by the exact size available in the * structure itself, thus ensuring no dynamic memory allocation. The * internal buffer is large enough to hold a reasonable paragraph of text, * such as the current paragraph. */ typedef struct AVBPrint { FF_PAD_STRUCTURE(1024, char *str; /**< string so far */ unsigned len; /**< length so far */ unsigned size; /**< allocated memory */ unsigned size_max; /**< maximum allocated memory */ char reserved_internal_buffer[1]; ) } AVBPrint; /** * Convenience macros for special values for av_bprint_init() size_max * parameter. */ #define AV_BPRINT_SIZE_UNLIMITED ((unsigned)-1) #define AV_BPRINT_SIZE_AUTOMATIC 1 #define AV_BPRINT_SIZE_COUNT_ONLY 0 /** * Init a print buffer. * * @param buf buffer to init * @param size_init initial size (including the final 0) * @param size_max maximum size; * 0 means do not write anything, just count the length; * 1 is replaced by the maximum value for automatic storage; * any large value means that the internal buffer will be * reallocated as needed up to that limit; -1 is converted to * UINT_MAX, the largest limit possible. * Check also AV_BPRINT_SIZE_* macros. */ void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max); /** * Init a print buffer using a pre-existing buffer. * * The buffer will not be reallocated. * * @param buf buffer structure to init * @param buffer byte buffer to use for the string data * @param size size of buffer */ void av_bprint_init_for_buffer(AVBPrint *buf, char *buffer, unsigned size); /** * Append a formatted string to a print buffer. */ void av_bprintf(AVBPrint *buf, const char *fmt, ...) av_printf_format(2, 3); /** * Append a formatted string to a print buffer. */ void av_vbprintf(AVBPrint *buf, const char *fmt, va_list vl_arg); /** * Append char c n times to a print buffer. */ void av_bprint_chars(AVBPrint *buf, char c, unsigned n); /** * Append data to a print buffer. * * param buf bprint buffer to use * param data pointer to data * param size size of data */ void av_bprint_append_data(AVBPrint *buf, const char *data, unsigned size); struct tm; /** * Append a formatted date and time to a print buffer. * * param buf bprint buffer to use * param fmt date and time format string, see strftime() * param tm broken-down time structure to translate * * @note due to poor design of the standard strftime function, it may * produce poor results if the format string expands to a very long text and * the bprint buffer is near the limit stated by the size_max option. */ void av_bprint_strftime(AVBPrint *buf, const char *fmt, const struct tm *tm); /** * Allocate bytes in the buffer for external use. * * @param[in] buf buffer structure * @param[in] size required size * @param[out] mem pointer to the memory area * @param[out] actual_size size of the memory area after allocation; * can be larger or smaller than size */ void av_bprint_get_buffer(AVBPrint *buf, unsigned size, unsigned char **mem, unsigned *actual_size); /** * Reset the string to "" but keep internal allocated data. */ void av_bprint_clear(AVBPrint *buf); /** * Test if the print buffer is complete (not truncated). * * It may have been truncated due to a memory allocation failure * or the size_max limit (compare size and size_max if necessary). */ static inline int av_bprint_is_complete(AVBPrint *buf) { return buf->len < buf->size; } /** * Finalize a print buffer. * * The print buffer can no longer be used afterwards, * but the len and size fields are still valid. * * @arg[out] ret_str if not NULL, used to return a permanent copy of the * buffer contents, or NULL if memory allocation fails; * if NULL, the buffer is discarded and freed * @return 0 for success or error code (probably AVERROR(ENOMEM)) */ int av_bprint_finalize(AVBPrint *buf, char **ret_str); /** * Escape the content in src and append it to dstbuf. * * @param dstbuf already inited destination bprint buffer * @param src string containing the text to escape * @param special_chars string containing the special characters which * need to be escaped, can be NULL * @param mode escape mode to employ, see AV_ESCAPE_MODE_* macros. * Any unknown value for mode will be considered equivalent to * AV_ESCAPE_MODE_BACKSLASH, but this behaviour can change without * notice. * @param flags flags which control how to escape, see AV_ESCAPE_FLAG_* macros */ void av_bprint_escape(AVBPrint *dstbuf, const char *src, const char *special_chars, enum AVEscapeMode mode, int flags); #endif /* AVUTIL_BPRINT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/bswap.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * byte swapping routines */ #ifndef AVUTIL_BSWAP_H #define AVUTIL_BSWAP_H #include #include "libavutil/avconfig.h" #include "attributes.h" #ifdef HAVE_AV_CONFIG_H #include "config.h" #if ARCH_AARCH64 # include "aarch64/bswap.h" #elif ARCH_ARM # include "arm/bswap.h" #elif ARCH_AVR32 # include "avr32/bswap.h" #elif ARCH_BFIN # include "bfin/bswap.h" #elif ARCH_SH4 # include "sh4/bswap.h" #elif ARCH_X86 # include "x86/bswap.h" #endif #endif /* HAVE_AV_CONFIG_H */ #define AV_BSWAP16C(x) (((x) << 8 & 0xff00) | ((x) >> 8 & 0x00ff)) #define AV_BSWAP32C(x) (AV_BSWAP16C(x) << 16 | AV_BSWAP16C((x) >> 16)) #define AV_BSWAP64C(x) (AV_BSWAP32C(x) << 32 | AV_BSWAP32C((x) >> 32)) #define AV_BSWAPC(s, x) AV_BSWAP##s##C(x) #ifndef av_bswap16 static av_always_inline av_const uint16_t av_bswap16(uint16_t x) { x= (x>>8) | (x<<8); return x; } #endif #ifndef av_bswap32 static av_always_inline av_const uint32_t av_bswap32(uint32_t x) { return AV_BSWAP32C(x); } #endif #ifndef av_bswap64 static inline uint64_t av_const av_bswap64(uint64_t x) { return (uint64_t)av_bswap32(x) << 32 | av_bswap32(x >> 32); } #endif // be2ne ... big-endian to native-endian // le2ne ... little-endian to native-endian #if AV_HAVE_BIGENDIAN #define av_be2ne16(x) (x) #define av_be2ne32(x) (x) #define av_be2ne64(x) (x) #define av_le2ne16(x) av_bswap16(x) #define av_le2ne32(x) av_bswap32(x) #define av_le2ne64(x) av_bswap64(x) #define AV_BE2NEC(s, x) (x) #define AV_LE2NEC(s, x) AV_BSWAPC(s, x) #else #define av_be2ne16(x) av_bswap16(x) #define av_be2ne32(x) av_bswap32(x) #define av_be2ne64(x) av_bswap64(x) #define av_le2ne16(x) (x) #define av_le2ne32(x) (x) #define av_le2ne64(x) (x) #define AV_BE2NEC(s, x) AV_BSWAPC(s, x) #define AV_LE2NEC(s, x) (x) #endif #define AV_BE2NE16C(x) AV_BE2NEC(16, x) #define AV_BE2NE32C(x) AV_BE2NEC(32, x) #define AV_BE2NE64C(x) AV_BE2NEC(64, x) #define AV_LE2NE16C(x) AV_LE2NEC(16, x) #define AV_LE2NE32C(x) AV_LE2NEC(32, x) #define AV_LE2NE64C(x) AV_LE2NEC(64, x) #endif /* AVUTIL_BSWAP_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/buffer.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_buffer * refcounted data buffer API */ #ifndef AVUTIL_BUFFER_H #define AVUTIL_BUFFER_H #include /** * @defgroup lavu_buffer AVBuffer * @ingroup lavu_data * * @{ * AVBuffer is an API for reference-counted data buffers. * * There are two core objects in this API -- AVBuffer and AVBufferRef. AVBuffer * represents the data buffer itself; it is opaque and not meant to be accessed * by the caller directly, but only through AVBufferRef. However, the caller may * e.g. compare two AVBuffer pointers to check whether two different references * are describing the same data buffer. AVBufferRef represents a single * reference to an AVBuffer and it is the object that may be manipulated by the * caller directly. * * There are two functions provided for creating a new AVBuffer with a single * reference -- av_buffer_alloc() to just allocate a new buffer, and * av_buffer_create() to wrap an existing array in an AVBuffer. From an existing * reference, additional references may be created with av_buffer_ref(). * Use av_buffer_unref() to free a reference (this will automatically free the * data once all the references are freed). * * The convention throughout this API and the rest of FFmpeg is such that the * buffer is considered writable if there exists only one reference to it (and * it has not been marked as read-only). The av_buffer_is_writable() function is * provided to check whether this is true and av_buffer_make_writable() will * automatically create a new writable buffer when necessary. * Of course nothing prevents the calling code from violating this convention, * however that is safe only when all the existing references are under its * control. * * @note Referencing and unreferencing the buffers is thread-safe and thus * may be done from multiple threads simultaneously without any need for * additional locking. * * @note Two different references to the same buffer can point to different * parts of the buffer (i.e. their AVBufferRef.data will not be equal). */ /** * A reference counted buffer type. It is opaque and is meant to be used through * references (AVBufferRef). */ typedef struct AVBuffer AVBuffer; /** * A reference to a data buffer. * * The size of this struct is not a part of the public ABI and it is not meant * to be allocated directly. */ typedef struct AVBufferRef { AVBuffer *buffer; /** * The data buffer. It is considered writable if and only if * this is the only reference to the buffer, in which case * av_buffer_is_writable() returns 1. */ uint8_t *data; /** * Size of data in bytes. */ int size; } AVBufferRef; /** * Allocate an AVBuffer of the given size using av_malloc(). * * @return an AVBufferRef of given size or NULL when out of memory */ AVBufferRef *av_buffer_alloc(int size); /** * Same as av_buffer_alloc(), except the returned buffer will be initialized * to zero. */ AVBufferRef *av_buffer_allocz(int size); /** * Always treat the buffer as read-only, even when it has only one * reference. */ #define AV_BUFFER_FLAG_READONLY (1 << 0) /** * Create an AVBuffer from an existing array. * * If this function is successful, data is owned by the AVBuffer. The caller may * only access data through the returned AVBufferRef and references derived from * it. * If this function fails, data is left untouched. * @param data data array * @param size size of data in bytes * @param free a callback for freeing this buffer's data * @param opaque parameter to be got for processing or passed to free * @param flags a combination of AV_BUFFER_FLAG_* * * @return an AVBufferRef referring to data on success, NULL on failure. */ AVBufferRef *av_buffer_create(uint8_t *data, int size, void (*free)(void *opaque, uint8_t *data), void *opaque, int flags); /** * Default free callback, which calls av_free() on the buffer data. * This function is meant to be passed to av_buffer_create(), not called * directly. */ void av_buffer_default_free(void *opaque, uint8_t *data); /** * Create a new reference to an AVBuffer. * * @return a new AVBufferRef referring to the same AVBuffer as buf or NULL on * failure. */ AVBufferRef *av_buffer_ref(AVBufferRef *buf); /** * Free a given reference and automatically free the buffer if there are no more * references to it. * * @param buf the reference to be freed. The pointer is set to NULL on return. */ void av_buffer_unref(AVBufferRef **buf); /** * @return 1 if the caller may write to the data referred to by buf (which is * true if and only if buf is the only reference to the underlying AVBuffer). * Return 0 otherwise. * A positive answer is valid until av_buffer_ref() is called on buf. */ int av_buffer_is_writable(const AVBufferRef *buf); /** * @return the opaque parameter set by av_buffer_create. */ void *av_buffer_get_opaque(const AVBufferRef *buf); int av_buffer_get_ref_count(const AVBufferRef *buf); /** * Create a writable reference from a given buffer reference, avoiding data copy * if possible. * * @param buf buffer reference to make writable. On success, buf is either left * untouched, or it is unreferenced and a new writable AVBufferRef is * written in its place. On failure, buf is left untouched. * @return 0 on success, a negative AVERROR on failure. */ int av_buffer_make_writable(AVBufferRef **buf); /** * Reallocate a given buffer. * * @param buf a buffer reference to reallocate. On success, buf will be * unreferenced and a new reference with the required size will be * written in its place. On failure buf will be left untouched. *buf * may be NULL, then a new buffer is allocated. * @param size required new buffer size. * @return 0 on success, a negative AVERROR on failure. * * @note the buffer is actually reallocated with av_realloc() only if it was * initially allocated through av_buffer_realloc(NULL) and there is only one * reference to it (i.e. the one passed to this function). In all other cases * a new buffer is allocated and the data is copied. */ int av_buffer_realloc(AVBufferRef **buf, int size); /** * @} */ /** * @defgroup lavu_bufferpool AVBufferPool * @ingroup lavu_data * * @{ * AVBufferPool is an API for a lock-free thread-safe pool of AVBuffers. * * Frequently allocating and freeing large buffers may be slow. AVBufferPool is * meant to solve this in cases when the caller needs a set of buffers of the * same size (the most obvious use case being buffers for raw video or audio * frames). * * At the beginning, the user must call av_buffer_pool_init() to create the * buffer pool. Then whenever a buffer is needed, call av_buffer_pool_get() to * get a reference to a new buffer, similar to av_buffer_alloc(). This new * reference works in all aspects the same way as the one created by * av_buffer_alloc(). However, when the last reference to this buffer is * unreferenced, it is returned to the pool instead of being freed and will be * reused for subsequent av_buffer_pool_get() calls. * * When the caller is done with the pool and no longer needs to allocate any new * buffers, av_buffer_pool_uninit() must be called to mark the pool as freeable. * Once all the buffers are released, it will automatically be freed. * * Allocating and releasing buffers with this API is thread-safe as long as * either the default alloc callback is used, or the user-supplied one is * thread-safe. */ /** * The buffer pool. This structure is opaque and not meant to be accessed * directly. It is allocated with av_buffer_pool_init() and freed with * av_buffer_pool_uninit(). */ typedef struct AVBufferPool AVBufferPool; /** * Allocate and initialize a buffer pool. * * @param size size of each buffer in this pool * @param alloc a function that will be used to allocate new buffers when the * pool is empty. May be NULL, then the default allocator will be used * (av_buffer_alloc()). * @return newly created buffer pool on success, NULL on error. */ AVBufferPool *av_buffer_pool_init(int size, AVBufferRef* (*alloc)(int size)); /** * Mark the pool as being available for freeing. It will actually be freed only * once all the allocated buffers associated with the pool are released. Thus it * is safe to call this function while some of the allocated buffers are still * in use. * * @param pool pointer to the pool to be freed. It will be set to NULL. * @see av_buffer_pool_can_uninit() */ void av_buffer_pool_uninit(AVBufferPool **pool); /** * Allocate a new AVBuffer, reusing an old buffer from the pool when available. * This function may be called simultaneously from multiple threads. * * @return a reference to the new buffer on success, NULL on error. */ AVBufferRef *av_buffer_pool_get(AVBufferPool *pool); /** * @} */ #endif /* AVUTIL_BUFFER_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/channel_layout.h ================================================ /* * Copyright (c) 2006 Michael Niedermayer * Copyright (c) 2008 Peter Ross * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CHANNEL_LAYOUT_H #define AVUTIL_CHANNEL_LAYOUT_H #include /** * @file * audio channel layout utility functions */ /** * @addtogroup lavu_audio * @{ */ /** * @defgroup channel_masks Audio channel masks * * A channel layout is a 64-bits integer with a bit set for every channel. * The number of bits set must be equal to the number of channels. * The value 0 means that the channel layout is not known. * @note this data structure is not powerful enough to handle channels * combinations that have the same channel multiple times, such as * dual-mono. * * @{ */ #define AV_CH_FRONT_LEFT 0x00000001 #define AV_CH_FRONT_RIGHT 0x00000002 #define AV_CH_FRONT_CENTER 0x00000004 #define AV_CH_LOW_FREQUENCY 0x00000008 #define AV_CH_BACK_LEFT 0x00000010 #define AV_CH_BACK_RIGHT 0x00000020 #define AV_CH_FRONT_LEFT_OF_CENTER 0x00000040 #define AV_CH_FRONT_RIGHT_OF_CENTER 0x00000080 #define AV_CH_BACK_CENTER 0x00000100 #define AV_CH_SIDE_LEFT 0x00000200 #define AV_CH_SIDE_RIGHT 0x00000400 #define AV_CH_TOP_CENTER 0x00000800 #define AV_CH_TOP_FRONT_LEFT 0x00001000 #define AV_CH_TOP_FRONT_CENTER 0x00002000 #define AV_CH_TOP_FRONT_RIGHT 0x00004000 #define AV_CH_TOP_BACK_LEFT 0x00008000 #define AV_CH_TOP_BACK_CENTER 0x00010000 #define AV_CH_TOP_BACK_RIGHT 0x00020000 #define AV_CH_STEREO_LEFT 0x20000000 ///< Stereo downmix. #define AV_CH_STEREO_RIGHT 0x40000000 ///< See AV_CH_STEREO_LEFT. #define AV_CH_WIDE_LEFT 0x0000000080000000ULL #define AV_CH_WIDE_RIGHT 0x0000000100000000ULL #define AV_CH_SURROUND_DIRECT_LEFT 0x0000000200000000ULL #define AV_CH_SURROUND_DIRECT_RIGHT 0x0000000400000000ULL #define AV_CH_LOW_FREQUENCY_2 0x0000000800000000ULL /** Channel mask value used for AVCodecContext.request_channel_layout to indicate that the user requests the channel order of the decoder output to be the native codec channel order. */ #define AV_CH_LAYOUT_NATIVE 0x8000000000000000ULL /** * @} * @defgroup channel_mask_c Audio channel convenience macros * @{ * */ #define AV_CH_LAYOUT_MONO (AV_CH_FRONT_CENTER) #define AV_CH_LAYOUT_STEREO (AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT) #define AV_CH_LAYOUT_2POINT1 (AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_2_1 (AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_SURROUND (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) #define AV_CH_LAYOUT_3POINT1 (AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_4POINT0 (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_4POINT1 (AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_2_2 (AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT) #define AV_CH_LAYOUT_QUAD (AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_5POINT0 (AV_CH_LAYOUT_SURROUND|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT) #define AV_CH_LAYOUT_5POINT1 (AV_CH_LAYOUT_5POINT0|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_5POINT0_BACK (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_5POINT1_BACK (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_6POINT0 (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT0_FRONT (AV_CH_LAYOUT_2_2|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_HEXAGONAL (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT1 (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT1_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT1_FRONT (AV_CH_LAYOUT_6POINT0_FRONT|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_7POINT0 (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_7POINT0_FRONT (AV_CH_LAYOUT_5POINT0|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_7POINT1 (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_7POINT1_WIDE (AV_CH_LAYOUT_5POINT1|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_7POINT1_WIDE_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_OCTAGONAL (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_CENTER|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_STEREO_DOWNMIX (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT) enum AVMatrixEncoding { AV_MATRIX_ENCODING_NONE, AV_MATRIX_ENCODING_DOLBY, AV_MATRIX_ENCODING_DPLII, AV_MATRIX_ENCODING_DPLIIX, AV_MATRIX_ENCODING_DPLIIZ, AV_MATRIX_ENCODING_DOLBYEX, AV_MATRIX_ENCODING_DOLBYHEADPHONE, AV_MATRIX_ENCODING_NB }; /** * @} */ /** * Return a channel layout id that matches name, or 0 if no match is found. * * name can be one or several of the following notations, * separated by '+' or '|': * - the name of an usual channel layout (mono, stereo, 4.0, quad, 5.0, * 5.0(side), 5.1, 5.1(side), 7.1, 7.1(wide), downmix); * - the name of a single channel (FL, FR, FC, LFE, BL, BR, FLC, FRC, BC, * SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR); * - a number of channels, in decimal, optionally followed by 'c', yielding * the default channel layout for that number of channels (@see * av_get_default_channel_layout); * - a channel layout mask, in hexadecimal starting with "0x" (see the * AV_CH_* macros). * * @warning Starting from the next major bump the trailing character * 'c' to specify a number of channels will be required, while a * channel layout mask could also be specified as a decimal number * (if and only if not followed by "c"). * * Example: "stereo+FC" = "2c+FC" = "2c+1c" = "0x7" */ uint64_t av_get_channel_layout(const char *name); /** * Return a description of a channel layout. * If nb_channels is <= 0, it is guessed from the channel_layout. * * @param buf put here the string containing the channel layout * @param buf_size size in bytes of the buffer */ void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout); struct AVBPrint; /** * Append a description of a channel layout to a bprint buffer. */ void av_bprint_channel_layout(struct AVBPrint *bp, int nb_channels, uint64_t channel_layout); /** * Return the number of channels in the channel layout. */ int av_get_channel_layout_nb_channels(uint64_t channel_layout); /** * Return default channel layout for a given number of channels. */ int64_t av_get_default_channel_layout(int nb_channels); /** * Get the index of a channel in channel_layout. * * @param channel a channel layout describing exactly one channel which must be * present in channel_layout. * * @return index of channel in channel_layout on success, a negative AVERROR * on error. */ int av_get_channel_layout_channel_index(uint64_t channel_layout, uint64_t channel); /** * Get the channel with the given index in channel_layout. */ uint64_t av_channel_layout_extract_channel(uint64_t channel_layout, int index); /** * Get the name of a given channel. * * @return channel name on success, NULL on error. */ const char *av_get_channel_name(uint64_t channel); /** * Get the description of a given channel. * * @param channel a channel layout with a single channel * @return channel description on success, NULL on error */ const char *av_get_channel_description(uint64_t channel); /** * Get the value and name of a standard channel layout. * * @param[in] index index in an internal list, starting at 0 * @param[out] layout channel layout mask * @param[out] name name of the layout * @return 0 if the layout exists, * <0 if index is beyond the limits */ int av_get_standard_channel_layout(unsigned index, uint64_t *layout, const char **name); /** * @} */ #endif /* AVUTIL_CHANNEL_LAYOUT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/common.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * common internal and external API header */ #ifndef AVUTIL_COMMON_H #define AVUTIL_COMMON_H #if defined(__cplusplus) && !defined(__STDC_CONSTANT_MACROS) && !defined(UINT64_C) #error missing -D__STDC_CONSTANT_MACROS / #define __STDC_CONSTANT_MACROS #endif #include #include #include #include #include #include #include #include #include "attributes.h" #include "version.h" #include "libavutil/avconfig.h" #if AV_HAVE_BIGENDIAN # define AV_NE(be, le) (be) #else # define AV_NE(be, le) (le) #endif //rounded division & shift #define RSHIFT(a,b) ((a) > 0 ? ((a) + ((1<<(b))>>1))>>(b) : ((a) + ((1<<(b))>>1)-1)>>(b)) /* assume b>0 */ #define ROUNDED_DIV(a,b) (((a)>0 ? (a) + ((b)>>1) : (a) - ((b)>>1))/(b)) /* assume a>0 and b>0 */ #define FF_CEIL_RSHIFT(a,b) (!av_builtin_constant_p(b) ? -((-(a)) >> (b)) \ : ((a) + (1<<(b)) - 1) >> (b)) #define FFUDIV(a,b) (((a)>0 ?(a):(a)-(b)+1) / (b)) #define FFUMOD(a,b) ((a)-(b)*FFUDIV(a,b)) #define FFABS(a) ((a) >= 0 ? (a) : (-(a))) #define FFSIGN(a) ((a) > 0 ? 1 : -1) #define FFMAX(a,b) ((a) > (b) ? (a) : (b)) #define FFMAX3(a,b,c) FFMAX(FFMAX(a,b),c) #define FFMIN(a,b) ((a) > (b) ? (b) : (a)) #define FFMIN3(a,b,c) FFMIN(FFMIN(a,b),c) #define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0) #define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0])) #define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1)) /* misc math functions */ /** * Reverse the order of the bits of an 8-bits unsigned integer. */ #if FF_API_AV_REVERSE extern attribute_deprecated const uint8_t av_reverse[256]; #endif #ifdef HAVE_AV_CONFIG_H # include "config.h" # include "intmath.h" #endif /* Pull in unguarded fallback defines at the end of this file. */ #include "common.h" #ifndef av_log2 av_const int av_log2(unsigned v); #endif #ifndef av_log2_16bit av_const int av_log2_16bit(unsigned v); #endif /** * Clip a signed integer value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static av_always_inline av_const int av_clip_c(int a, int amin, int amax) { #if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** * Clip a signed 64bit integer value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static av_always_inline av_const int64_t av_clip64_c(int64_t a, int64_t amin, int64_t amax) { #if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** * Clip a signed integer value into the 0-255 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const uint8_t av_clip_uint8_c(int a) { if (a&(~0xFF)) return (-a)>>31; else return a; } /** * Clip a signed integer value into the -128,127 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const int8_t av_clip_int8_c(int a) { if ((a+0x80) & ~0xFF) return (a>>31) ^ 0x7F; else return a; } /** * Clip a signed integer value into the 0-65535 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const uint16_t av_clip_uint16_c(int a) { if (a&(~0xFFFF)) return (-a)>>31; else return a; } /** * Clip a signed integer value into the -32768,32767 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const int16_t av_clip_int16_c(int a) { if ((a+0x8000) & ~0xFFFF) return (a>>31) ^ 0x7FFF; else return a; } /** * Clip a signed 64-bit integer value into the -2147483648,2147483647 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const int32_t av_clipl_int32_c(int64_t a) { if ((a+0x80000000u) & ~UINT64_C(0xFFFFFFFF)) return (int32_t)((a>>63) ^ 0x7FFFFFFF); else return (int32_t)a; } /** * Clip a signed integer to an unsigned power of two range. * @param a value to clip * @param p bit position to clip at * @return clipped value */ static av_always_inline av_const unsigned av_clip_uintp2_c(int a, int p) { if (a & ~((1<> 31 & ((1<= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** * Clip a double value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static av_always_inline av_const double av_clipd_c(double a, double amin, double amax) { #if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** Compute ceil(log2(x)). * @param x value used to compute ceil(log2(x)) * @return computed ceiling of log2(x) */ static av_always_inline av_const int av_ceil_log2_c(int x) { return av_log2((x - 1) << 1); } /** * Count number of bits set to one in x * @param x value to count bits of * @return the number of bits set to one in x */ static av_always_inline av_const int av_popcount_c(uint32_t x) { x -= (x >> 1) & 0x55555555; x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x += x >> 8; return (x + (x >> 16)) & 0x3F; } /** * Count number of bits set to one in x * @param x value to count bits of * @return the number of bits set to one in x */ static av_always_inline av_const int av_popcount64_c(uint64_t x) { return av_popcount((uint32_t)x) + av_popcount((uint32_t)(x >> 32)); } #define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((unsigned)(d) << 24)) #define MKBETAG(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((unsigned)(a) << 24)) /** * Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form. * * @param val Output value, must be an lvalue of type uint32_t. * @param GET_BYTE Expression reading one byte from the input. * Evaluated up to 7 times (4 for the currently * assigned Unicode range). With a memory buffer * input, this could be *ptr++. * @param ERROR Expression to be evaluated on invalid input, * typically a goto statement. * * @warning ERROR should not contain a loop control statement which * could interact with the internal while loop, and should force an * exit from the macro code (e.g. through a goto or a return) in order * to prevent undefined results. */ #define GET_UTF8(val, GET_BYTE, ERROR)\ val= GET_BYTE;\ {\ uint32_t top = (val & 128) >> 1;\ if ((val & 0xc0) == 0x80 || val >= 0xFE)\ ERROR\ while (val & top) {\ int tmp= GET_BYTE - 128;\ if(tmp>>6)\ ERROR\ val= (val<<6) + tmp;\ top <<= 5;\ }\ val &= (top << 1) - 1;\ } /** * Convert a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form. * * @param val Output value, must be an lvalue of type uint32_t. * @param GET_16BIT Expression returning two bytes of UTF-16 data converted * to native byte order. Evaluated one or two times. * @param ERROR Expression to be evaluated on invalid input, * typically a goto statement. */ #define GET_UTF16(val, GET_16BIT, ERROR)\ val = GET_16BIT;\ {\ unsigned int hi = val - 0xD800;\ if (hi < 0x800) {\ val = GET_16BIT - 0xDC00;\ if (val > 0x3FFU || hi > 0x3FFU)\ ERROR\ val += (hi<<10) + 0x10000;\ }\ }\ /** * @def PUT_UTF8(val, tmp, PUT_BYTE) * Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long). * @param val is an input-only argument and should be of type uint32_t. It holds * a UCS-4 encoded Unicode character that is to be converted to UTF-8. If * val is given as a function it is executed only once. * @param tmp is a temporary variable and should be of type uint8_t. It * represents an intermediate value during conversion that is to be * output by PUT_BYTE. * @param PUT_BYTE writes the converted UTF-8 bytes to any proper destination. * It could be a function or a statement, and uses tmp as the input byte. * For example, PUT_BYTE could be "*output++ = tmp;" PUT_BYTE will be * executed up to 4 times for values in the valid UTF-8 range and up to * 7 times in the general case, depending on the length of the converted * Unicode character. */ #define PUT_UTF8(val, tmp, PUT_BYTE)\ {\ int bytes, shift;\ uint32_t in = val;\ if (in < 0x80) {\ tmp = in;\ PUT_BYTE\ } else {\ bytes = (av_log2(in) + 4) / 5;\ shift = (bytes - 1) * 6;\ tmp = (256 - (256 >> bytes)) | (in >> shift);\ PUT_BYTE\ while (shift >= 6) {\ shift -= 6;\ tmp = 0x80 | ((in >> shift) & 0x3f);\ PUT_BYTE\ }\ }\ } /** * @def PUT_UTF16(val, tmp, PUT_16BIT) * Convert a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes). * @param val is an input-only argument and should be of type uint32_t. It holds * a UCS-4 encoded Unicode character that is to be converted to UTF-16. If * val is given as a function it is executed only once. * @param tmp is a temporary variable and should be of type uint16_t. It * represents an intermediate value during conversion that is to be * output by PUT_16BIT. * @param PUT_16BIT writes the converted UTF-16 data to any proper destination * in desired endianness. It could be a function or a statement, and uses tmp * as the input byte. For example, PUT_BYTE could be "*output++ = tmp;" * PUT_BYTE will be executed 1 or 2 times depending on input character. */ #define PUT_UTF16(val, tmp, PUT_16BIT)\ {\ uint32_t in = val;\ if (in < 0x10000) {\ tmp = in;\ PUT_16BIT\ } else {\ tmp = 0xD800 | ((in - 0x10000) >> 10);\ PUT_16BIT\ tmp = 0xDC00 | ((in - 0x10000) & 0x3FF);\ PUT_16BIT\ }\ }\ #include "mem.h" #ifdef HAVE_AV_CONFIG_H # include "internal.h" #endif /* HAVE_AV_CONFIG_H */ #endif /* AVUTIL_COMMON_H */ /* * The following definitions are outside the multiple inclusion guard * to ensure they are immediately available in intmath.h. */ #ifndef av_ceil_log2 # define av_ceil_log2 av_ceil_log2_c #endif #ifndef av_clip # define av_clip av_clip_c #endif #ifndef av_clip64 # define av_clip64 av_clip64_c #endif #ifndef av_clip_uint8 # define av_clip_uint8 av_clip_uint8_c #endif #ifndef av_clip_int8 # define av_clip_int8 av_clip_int8_c #endif #ifndef av_clip_uint16 # define av_clip_uint16 av_clip_uint16_c #endif #ifndef av_clip_int16 # define av_clip_int16 av_clip_int16_c #endif #ifndef av_clipl_int32 # define av_clipl_int32 av_clipl_int32_c #endif #ifndef av_clip_uintp2 # define av_clip_uintp2 av_clip_uintp2_c #endif #ifndef av_sat_add32 # define av_sat_add32 av_sat_add32_c #endif #ifndef av_sat_dadd32 # define av_sat_dadd32 av_sat_dadd32_c #endif #ifndef av_clipf # define av_clipf av_clipf_c #endif #ifndef av_clipd # define av_clipd av_clipd_c #endif #ifndef av_popcount # define av_popcount av_popcount_c #endif #ifndef av_popcount64 # define av_popcount64 av_popcount64_c #endif ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/cpu.h ================================================ /* * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CPU_H #define AVUTIL_CPU_H #include "attributes.h" #define AV_CPU_FLAG_FORCE 0x80000000 /* force usage of selected flags (OR) */ /* lower 16 bits - CPU features */ #define AV_CPU_FLAG_MMX 0x0001 ///< standard MMX #define AV_CPU_FLAG_MMXEXT 0x0002 ///< SSE integer functions or AMD MMX ext #define AV_CPU_FLAG_MMX2 0x0002 ///< SSE integer functions or AMD MMX ext #define AV_CPU_FLAG_3DNOW 0x0004 ///< AMD 3DNOW #define AV_CPU_FLAG_SSE 0x0008 ///< SSE functions #define AV_CPU_FLAG_SSE2 0x0010 ///< PIV SSE2 functions #define AV_CPU_FLAG_SSE2SLOW 0x40000000 ///< SSE2 supported, but usually not faster ///< than regular MMX/SSE (e.g. Core1) #define AV_CPU_FLAG_3DNOWEXT 0x0020 ///< AMD 3DNowExt #define AV_CPU_FLAG_SSE3 0x0040 ///< Prescott SSE3 functions #define AV_CPU_FLAG_SSE3SLOW 0x20000000 ///< SSE3 supported, but usually not faster ///< than regular MMX/SSE (e.g. Core1) #define AV_CPU_FLAG_SSSE3 0x0080 ///< Conroe SSSE3 functions #define AV_CPU_FLAG_ATOM 0x10000000 ///< Atom processor, some SSSE3 instructions are slower #define AV_CPU_FLAG_SSE4 0x0100 ///< Penryn SSE4.1 functions #define AV_CPU_FLAG_SSE42 0x0200 ///< Nehalem SSE4.2 functions #define AV_CPU_FLAG_AVX 0x4000 ///< AVX functions: requires OS support even if YMM registers aren't used #define AV_CPU_FLAG_XOP 0x0400 ///< Bulldozer XOP functions #define AV_CPU_FLAG_FMA4 0x0800 ///< Bulldozer FMA4 functions // #if LIBAVUTIL_VERSION_MAJOR <52 #define AV_CPU_FLAG_CMOV 0x1001000 ///< supports cmov instruction // #else // #define AV_CPU_FLAG_CMOV 0x1000 ///< supports cmov instruction // #endif #define AV_CPU_FLAG_AVX2 0x8000 ///< AVX2 functions: requires OS support even if YMM registers aren't used #define AV_CPU_FLAG_FMA3 0x10000 ///< Haswell FMA3 functions #define AV_CPU_FLAG_BMI1 0x20000 ///< Bit Manipulation Instruction Set 1 #define AV_CPU_FLAG_BMI2 0x40000 ///< Bit Manipulation Instruction Set 2 #define AV_CPU_FLAG_ALTIVEC 0x0001 ///< standard #define AV_CPU_FLAG_ARMV5TE (1 << 0) #define AV_CPU_FLAG_ARMV6 (1 << 1) #define AV_CPU_FLAG_ARMV6T2 (1 << 2) #define AV_CPU_FLAG_VFP (1 << 3) #define AV_CPU_FLAG_VFPV3 (1 << 4) #define AV_CPU_FLAG_NEON (1 << 5) /** * Return the flags which specify extensions supported by the CPU. * The returned value is affected by av_force_cpu_flags() if that was used * before. So av_get_cpu_flags() can easily be used in a application to * detect the enabled cpu flags. */ int av_get_cpu_flags(void); /** * Disables cpu detection and forces the specified flags. * -1 is a special case that disables forcing of specific flags. */ void av_force_cpu_flags(int flags); /** * Set a mask on flags returned by av_get_cpu_flags(). * This function is mainly useful for testing. * Please use av_force_cpu_flags() and av_get_cpu_flags() instead which are more flexible * * @warning this function is not thread safe. */ attribute_deprecated void av_set_cpu_flags_mask(int mask); /** * Parse CPU flags from a string. * * The returned flags contain the specified flags as well as related unspecified flags. * * This function exists only for compatibility with libav. * Please use av_parse_cpu_caps() when possible. * @return a combination of AV_CPU_* flags, negative on error. */ attribute_deprecated int av_parse_cpu_flags(const char *s); /** * Parse CPU caps from a string and update the given AV_CPU_* flags based on that. * * @return negative on error. */ int av_parse_cpu_caps(unsigned *flags, const char *s); /** * @return the number of logical CPU cores present. */ int av_cpu_count(void); #endif /* AVUTIL_CPU_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/crc.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CRC_H #define AVUTIL_CRC_H #include #include #include "attributes.h" /** * @defgroup lavu_crc32 CRC32 * @ingroup lavu_crypto * @{ */ typedef uint32_t AVCRC; typedef enum { AV_CRC_8_ATM, AV_CRC_16_ANSI, AV_CRC_16_CCITT, AV_CRC_32_IEEE, AV_CRC_32_IEEE_LE, /*< reversed bitorder version of AV_CRC_32_IEEE */ AV_CRC_24_IEEE = 12, AV_CRC_MAX, /*< Not part of public API! Do not use outside libavutil. */ }AVCRCId; /** * Initialize a CRC table. * @param ctx must be an array of size sizeof(AVCRC)*257 or sizeof(AVCRC)*1024 * @param le If 1, the lowest bit represents the coefficient for the highest * exponent of the corresponding polynomial (both for poly and * actual CRC). * If 0, you must swap the CRC parameter and the result of av_crc * if you need the standard representation (can be simplified in * most cases to e.g. bswap16): * av_bswap32(crc << (32-bits)) * @param bits number of bits for the CRC * @param poly generator polynomial without the x**bits coefficient, in the * representation as specified by le * @param ctx_size size of ctx in bytes * @return <0 on failure */ int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size); /** * Get an initialized standard CRC table. * @param crc_id ID of a standard CRC * @return a pointer to the CRC table or NULL on failure */ const AVCRC *av_crc_get_table(AVCRCId crc_id); /** * Calculate the CRC of a block. * @param crc CRC of previous blocks if any or initial value for CRC * @return CRC updated with the data from the given block * * @see av_crc_init() "le" parameter */ uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length) av_pure; /** * @} */ #endif /* AVUTIL_CRC_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/dict.h ================================================ /* * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Public dictionary API. * @deprecated * AVDictionary is provided for compatibility with libav. It is both in * implementation as well as API inefficient. It does not scale and is * extremely slow with large dictionaries. * It is recommended that new code uses our tree container from tree.c/h * where applicable, which uses AVL trees to achieve O(log n) performance. */ #ifndef AVUTIL_DICT_H #define AVUTIL_DICT_H /** * @addtogroup lavu_dict AVDictionary * @ingroup lavu_data * * @brief Simple key:value store * * @{ * Dictionaries are used for storing key:value pairs. To create * an AVDictionary, simply pass an address of a NULL pointer to * av_dict_set(). NULL can be used as an empty dictionary wherever * a pointer to an AVDictionary is required. * Use av_dict_get() to retrieve an entry or iterate over all * entries and finally av_dict_free() to free the dictionary * and all its contents. * @code AVDictionary *d = NULL; // "create" an empty dictionary AVDictionaryEntry *t = NULL; av_dict_set(&d, "foo", "bar", 0); // add an entry char *k = av_strdup("key"); // if your strings are already allocated, char *v = av_strdup("value"); // you can avoid copying them like this av_dict_set(&d, k, v, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL); while (t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX)) { <....> // iterate over all entries in d } av_dict_free(&d); @endcode * */ #define AV_DICT_MATCH_CASE 1 /**< Only get an entry with exact-case key match. Only relevant in av_dict_get(). */ #define AV_DICT_IGNORE_SUFFIX 2 /**< Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string. Only relevant in av_dict_get(). */ #define AV_DICT_DONT_STRDUP_KEY 4 /**< Take ownership of a key that's been allocated with av_malloc() or another memory allocation function. */ #define AV_DICT_DONT_STRDUP_VAL 8 /**< Take ownership of a value that's been allocated with av_malloc() or another memory allocation function. */ #define AV_DICT_DONT_OVERWRITE 16 ///< Don't overwrite existing entries. #define AV_DICT_APPEND 32 /**< If the entry already exists, append to it. Note that no delimiter is added, the strings are simply concatenated. */ typedef struct AVDictionaryEntry { char *key; char *value; } AVDictionaryEntry; typedef struct AVDictionary AVDictionary; /** * Get a dictionary entry with matching key. * * The returned entry key or value must not be changed, or it will * cause undefined behavior. * * To iterate through all the dictionary entries, you can set the matching key * to the null string "" and set the AV_DICT_IGNORE_SUFFIX flag. * * @param prev Set to the previous matching element to find the next. * If set to NULL the first matching element is returned. * @param key matching key * @param flags a collection of AV_DICT_* flags controlling how the entry is retrieved * @return found entry or NULL in case no matching entry was found in the dictionary */ AVDictionaryEntry * av_dict_get(AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags); /** * Get number of entries in dictionary. * * @param m dictionary * @return number of entries in dictionary */ int av_dict_count(const AVDictionary *m); /** * Set the given entry in *pm, overwriting an existing entry. * * @param pm pointer to a pointer to a dictionary struct. If *pm is NULL * a dictionary struct is allocated and put in *pm. * @param key entry key to add to *pm (will be av_strduped depending on flags) * @param value entry value to add to *pm (will be av_strduped depending on flags). * Passing a NULL value will cause an existing entry to be deleted. * @return >= 0 on success otherwise an error code <0 */ int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags); /** * Parse the key/value pairs list and add the parsed entries to a dictionary. * * In case of failure, all the successfully set entries are stored in * *pm. You may need to manually free the created dictionary. * * @param key_val_sep a 0-terminated list of characters used to separate * key from value * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other * @param flags flags to use when adding to dictionary. * AV_DICT_DONT_STRDUP_KEY and AV_DICT_DONT_STRDUP_VAL * are ignored since the key/value tokens will always * be duplicated. * @return 0 on success, negative AVERROR code on failure */ int av_dict_parse_string(AVDictionary **pm, const char *str, const char *key_val_sep, const char *pairs_sep, int flags); /** * Copy entries from one AVDictionary struct into another. * @param dst pointer to a pointer to a AVDictionary struct. If *dst is NULL, * this function will allocate a struct for you and put it in *dst * @param src pointer to source AVDictionary struct * @param flags flags to use when setting entries in *dst * @note metadata is read using the AV_DICT_IGNORE_SUFFIX flag */ void av_dict_copy(AVDictionary **dst, AVDictionary *src, int flags); /** * Free all the memory allocated for an AVDictionary struct * and all keys and values. */ void av_dict_free(AVDictionary **m); /** * @} */ #endif /* AVUTIL_DICT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/downmix_info.h ================================================ /* * Copyright (c) 2014 Tim Walker * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_DOWNMIX_INFO_H #define AVUTIL_DOWNMIX_INFO_H #include "frame.h" /** * @file * audio downmix medatata */ /** * @addtogroup lavu_audio * @{ */ /** * @defgroup downmix_info Audio downmix metadata * @{ */ /** * Possible downmix types. */ enum AVDownmixType { AV_DOWNMIX_TYPE_UNKNOWN, /**< Not indicated. */ AV_DOWNMIX_TYPE_LORO, /**< Lo/Ro 2-channel downmix (Stereo). */ AV_DOWNMIX_TYPE_LTRT, /**< Lt/Rt 2-channel downmix, Dolby Surround compatible. */ AV_DOWNMIX_TYPE_DPLII, /**< Lt/Rt 2-channel downmix, Dolby Pro Logic II compatible. */ AV_DOWNMIX_TYPE_NB /**< Number of downmix types. Not part of ABI. */ }; /** * This structure describes optional metadata relevant to a downmix procedure. * * All fields are set by the decoder to the value indicated in the audio * bitstream (if present), or to a "sane" default otherwise. */ typedef struct AVDownmixInfo { /** * Type of downmix preferred by the mastering engineer. */ enum AVDownmixType preferred_downmix_type; /** * Absolute scale factor representing the nominal level of the center * channel during a regular downmix. */ double center_mix_level; /** * Absolute scale factor representing the nominal level of the center * channel during an Lt/Rt compatible downmix. */ double center_mix_level_ltrt; /** * Absolute scale factor representing the nominal level of the surround * channels during a regular downmix. */ double surround_mix_level; /** * Absolute scale factor representing the nominal level of the surround * channels during an Lt/Rt compatible downmix. */ double surround_mix_level_ltrt; /** * Absolute scale factor representing the level at which the LFE data is * mixed into L/R channels during downmixing. */ double lfe_mix_level; } AVDownmixInfo; /** * Get a frame's AV_FRAME_DATA_DOWNMIX_INFO side data for editing. * * The side data is created and added to the frame if it's absent. * * @param frame the frame for which the side data is to be obtained. * * @return the AVDownmixInfo structure to be edited by the caller. */ AVDownmixInfo *av_downmix_info_update_side_data(AVFrame *frame); /** * @} */ /** * @} */ #endif /* AVUTIL_DOWNMIX_INFO_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/error.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * error code definitions */ #ifndef AVUTIL_ERROR_H #define AVUTIL_ERROR_H #include #include /** * @addtogroup lavu_error * * @{ */ /* error handling */ #if EDOM > 0 #define AVERROR(e) (-(e)) ///< Returns a negative error code from a POSIX error code, to return from library functions. #define AVUNERROR(e) (-(e)) ///< Returns a POSIX error code from a library function error return value. #else /* Some platforms have E* and errno already negated. */ #define AVERROR(e) (e) #define AVUNERROR(e) (e) #endif #define FFERRTAG(a, b, c, d) (-(int)MKTAG(a, b, c, d)) #define AVERROR_BSF_NOT_FOUND FFERRTAG(0xF8,'B','S','F') ///< Bitstream filter not found #define AVERROR_BUG FFERRTAG( 'B','U','G','!') ///< Internal bug, also see AVERROR_BUG2 #define AVERROR_BUFFER_TOO_SMALL FFERRTAG( 'B','U','F','S') ///< Buffer too small #define AVERROR_DECODER_NOT_FOUND FFERRTAG(0xF8,'D','E','C') ///< Decoder not found #define AVERROR_DEMUXER_NOT_FOUND FFERRTAG(0xF8,'D','E','M') ///< Demuxer not found #define AVERROR_ENCODER_NOT_FOUND FFERRTAG(0xF8,'E','N','C') ///< Encoder not found #define AVERROR_EOF FFERRTAG( 'E','O','F',' ') ///< End of file #define AVERROR_EXIT FFERRTAG( 'E','X','I','T') ///< Immediate exit was requested; the called function should not be restarted #define AVERROR_EXTERNAL FFERRTAG( 'E','X','T',' ') ///< Generic error in an external library #define AVERROR_FILTER_NOT_FOUND FFERRTAG(0xF8,'F','I','L') ///< Filter not found #define AVERROR_INVALIDDATA FFERRTAG( 'I','N','D','A') ///< Invalid data found when processing input #define AVERROR_MUXER_NOT_FOUND FFERRTAG(0xF8,'M','U','X') ///< Muxer not found #define AVERROR_OPTION_NOT_FOUND FFERRTAG(0xF8,'O','P','T') ///< Option not found #define AVERROR_PATCHWELCOME FFERRTAG( 'P','A','W','E') ///< Not yet implemented in FFmpeg, patches welcome #define AVERROR_PROTOCOL_NOT_FOUND FFERRTAG(0xF8,'P','R','O') ///< Protocol not found #define AVERROR_STREAM_NOT_FOUND FFERRTAG(0xF8,'S','T','R') ///< Stream not found /** * This is semantically identical to AVERROR_BUG * it has been introduced in Libav after our AVERROR_BUG and with a modified value. */ #define AVERROR_BUG2 FFERRTAG( 'B','U','G',' ') #define AVERROR_UNKNOWN FFERRTAG( 'U','N','K','N') ///< Unknown error, typically from an external library #define AVERROR_EXPERIMENTAL (-0x2bb2afa8) ///< Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it. #define AV_ERROR_MAX_STRING_SIZE 64 /** * Put a description of the AVERROR code errnum in errbuf. * In case of failure the global variable errno is set to indicate the * error. Even in case of failure av_strerror() will print a generic * error message indicating the errnum provided to errbuf. * * @param errnum error code to describe * @param errbuf buffer to which description is written * @param errbuf_size the size in bytes of errbuf * @return 0 on success, a negative value if a description for errnum * cannot be found */ int av_strerror(int errnum, char *errbuf, size_t errbuf_size); /** * Fill the provided buffer with a string containing an error string * corresponding to the AVERROR code errnum. * * @param errbuf a buffer * @param errbuf_size size in bytes of errbuf * @param errnum error code to describe * @return the buffer in input, filled with the error description * @see av_strerror() */ static inline char *av_make_error_string(char *errbuf, size_t errbuf_size, int errnum) { av_strerror(errnum, errbuf, errbuf_size); return errbuf; } /** * Convenience macro, the return value should be used only directly in * function arguments but never stand-alone. */ #define av_err2str(errnum) \ av_make_error_string((char[AV_ERROR_MAX_STRING_SIZE]){0}, AV_ERROR_MAX_STRING_SIZE, errnum) /** * @} */ #endif /* AVUTIL_ERROR_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/eval.h ================================================ /* * Copyright (c) 2002 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * simple arithmetic expression evaluator */ #ifndef AVUTIL_EVAL_H #define AVUTIL_EVAL_H #include "avutil.h" typedef struct AVExpr AVExpr; /** * Parse and evaluate an expression. * Note, this is significantly slower than av_expr_eval(). * * @param res a pointer to a double where is put the result value of * the expression, or NAN in case of error * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)" * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0} * @param const_values a zero terminated array of values for the identifiers from const_names * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2 * @param log_ctx parent logging context * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code otherwise */ int av_expr_parse_and_eval(double *res, const char *s, const char * const *const_names, const double *const_values, const char * const *func1_names, double (* const *funcs1)(void *, double), const char * const *func2_names, double (* const *funcs2)(void *, double, double), void *opaque, int log_offset, void *log_ctx); /** * Parse an expression. * * @param expr a pointer where is put an AVExpr containing the parsed * value in case of successful parsing, or NULL otherwise. * The pointed to AVExpr must be freed with av_expr_free() by the user * when it is not needed anymore. * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)" * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0} * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments * @param log_ctx parent logging context * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code otherwise */ int av_expr_parse(AVExpr **expr, const char *s, const char * const *const_names, const char * const *func1_names, double (* const *funcs1)(void *, double), const char * const *func2_names, double (* const *funcs2)(void *, double, double), int log_offset, void *log_ctx); /** * Evaluate a previously parsed expression. * * @param const_values a zero terminated array of values for the identifiers from av_expr_parse() const_names * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2 * @return the value of the expression */ double av_expr_eval(AVExpr *e, const double *const_values, void *opaque); /** * Free a parsed expression previously created with av_expr_parse(). */ void av_expr_free(AVExpr *e); /** * Parse the string in numstr and return its value as a double. If * the string is empty, contains only whitespaces, or does not contain * an initial substring that has the expected syntax for a * floating-point number, no conversion is performed. In this case, * returns a value of zero and the value returned in tail is the value * of numstr. * * @param numstr a string representing a number, may contain one of * the International System number postfixes, for example 'K', 'M', * 'G'. If 'i' is appended after the postfix, powers of 2 are used * instead of powers of 10. The 'B' postfix multiplies the value for * 8, and can be appended after another postfix or used alone. This * allows using for example 'KB', 'MiB', 'G' and 'B' as postfix. * @param tail if non-NULL puts here the pointer to the char next * after the last parsed character */ double av_strtod(const char *numstr, char **tail); #endif /* AVUTIL_EVAL_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/ffversion.h ================================================ #ifndef AVUTIL_FFVERSION_H #define AVUTIL_FFVERSION_H #define FFMPEG_VERSION "2.2.3" #endif /* AVUTIL_FFVERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/fifo.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * a very simple circular buffer FIFO implementation */ #ifndef AVUTIL_FIFO_H #define AVUTIL_FIFO_H #include #include "avutil.h" #include "attributes.h" typedef struct AVFifoBuffer { uint8_t *buffer; uint8_t *rptr, *wptr, *end; uint32_t rndx, wndx; } AVFifoBuffer; /** * Initialize an AVFifoBuffer. * @param size of FIFO * @return AVFifoBuffer or NULL in case of memory allocation failure */ AVFifoBuffer *av_fifo_alloc(unsigned int size); /** * Free an AVFifoBuffer. * @param f AVFifoBuffer to free */ void av_fifo_free(AVFifoBuffer *f); /** * Reset the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied. * @param f AVFifoBuffer to reset */ void av_fifo_reset(AVFifoBuffer *f); /** * Return the amount of data in bytes in the AVFifoBuffer, that is the * amount of data you can read from it. * @param f AVFifoBuffer to read from * @return size */ int av_fifo_size(AVFifoBuffer *f); /** * Return the amount of space in bytes in the AVFifoBuffer, that is the * amount of data you can write into it. * @param f AVFifoBuffer to write into * @return size */ int av_fifo_space(AVFifoBuffer *f); /** * Feed data from an AVFifoBuffer to a user-supplied callback. * @param f AVFifoBuffer to read from * @param buf_size number of bytes to read * @param func generic read function * @param dest data destination */ int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int)); /** * Feed data from a user-supplied callback to an AVFifoBuffer. * @param f AVFifoBuffer to write to * @param src data source; non-const since it may be used as a * modifiable context by the function defined in func * @param size number of bytes to write * @param func generic write function; the first parameter is src, * the second is dest_buf, the third is dest_buf_size. * func must return the number of bytes written to dest_buf, or <= 0 to * indicate no more data available to write. * If func is NULL, src is interpreted as a simple byte array for source data. * @return the number of bytes written to the FIFO */ int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void*, void*, int)); /** * Resize an AVFifoBuffer. * In case of reallocation failure, the old FIFO is kept unchanged. * * @param f AVFifoBuffer to resize * @param size new AVFifoBuffer size in bytes * @return <0 for failure, >=0 otherwise */ int av_fifo_realloc2(AVFifoBuffer *f, unsigned int size); /** * Enlarge an AVFifoBuffer. * In case of reallocation failure, the old FIFO is kept unchanged. * The new fifo size may be larger than the requested size. * * @param f AVFifoBuffer to resize * @param additional_space the amount of space in bytes to allocate in addition to av_fifo_size() * @return <0 for failure, >=0 otherwise */ int av_fifo_grow(AVFifoBuffer *f, unsigned int additional_space); /** * Read and discard the specified amount of data from an AVFifoBuffer. * @param f AVFifoBuffer to read from * @param size amount of data to read in bytes */ void av_fifo_drain(AVFifoBuffer *f, int size); /** * Return a pointer to the data stored in a FIFO buffer at a certain offset. * The FIFO buffer is not modified. * * @param f AVFifoBuffer to peek at, f must be non-NULL * @param offs an offset in bytes, its absolute value must be less * than the used buffer size or the returned pointer will * point outside to the buffer data. * The used buffer size can be checked with av_fifo_size(). */ static inline uint8_t *av_fifo_peek2(const AVFifoBuffer *f, int offs) { uint8_t *ptr = f->rptr + offs; if (ptr >= f->end) ptr = f->buffer + (ptr - f->end); else if (ptr < f->buffer) ptr = f->end - (f->buffer - ptr); return ptr; } #endif /* AVUTIL_FIFO_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/file.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_FILE_H #define AVUTIL_FILE_H #include #include "avutil.h" /** * @file * Misc file utilities. */ /** * Read the file with name filename, and put its content in a newly * allocated buffer or map it with mmap() when available. * In case of success set *bufptr to the read or mmapped buffer, and * *size to the size in bytes of the buffer in *bufptr. * The returned buffer must be released with av_file_unmap(). * * @param log_offset loglevel offset used for logging * @param log_ctx context used for logging * @return a non negative number in case of success, a negative value * corresponding to an AVERROR error code in case of failure */ int av_file_map(const char *filename, uint8_t **bufptr, size_t *size, int log_offset, void *log_ctx); /** * Unmap or free the buffer bufptr created by av_file_map(). * * @param size size in bytes of bufptr, must be the same as returned * by av_file_map() */ void av_file_unmap(uint8_t *bufptr, size_t size); /** * Wrapper to work around the lack of mkstemp() on mingw. * Also, tries to create file in /tmp first, if possible. * *prefix can be a character constant; *filename will be allocated internally. * @return file descriptor of opened file (or -1 on error) * and opened file name in **filename. * @note On very old libcs it is necessary to set a secure umask before * calling this, av_tempfile() can't call umask itself as it is used in * libraries and could interfere with the calling application. */ int av_tempfile(const char *prefix, char **filename, int log_offset, void *log_ctx); #endif /* AVUTIL_FILE_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/frame.h ================================================ /* * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_frame * reference-counted frame API */ #ifndef AVUTIL_FRAME_H #define AVUTIL_FRAME_H #include #include "avutil.h" #include "buffer.h" #include "dict.h" #include "rational.h" #include "samplefmt.h" #include "version.h" enum AVColorSpace{ AVCOL_SPC_RGB = 0, AVCOL_SPC_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B AVCOL_SPC_UNSPECIFIED = 2, AVCOL_SPC_FCC = 4, AVCOL_SPC_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601 AVCOL_SPC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above AVCOL_SPC_SMPTE240M = 7, AVCOL_SPC_YCOCG = 8, ///< Used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16 AVCOL_SPC_BT2020_NCL = 9, ///< ITU-R BT2020 non-constant luminance system AVCOL_SPC_BT2020_CL = 10, ///< ITU-R BT2020 constant luminance system AVCOL_SPC_NB , ///< Not part of ABI }; #define AVCOL_SPC_YCGCO AVCOL_SPC_YCOCG enum AVColorRange{ AVCOL_RANGE_UNSPECIFIED = 0, AVCOL_RANGE_MPEG = 1, ///< the normal 219*2^(n-8) "MPEG" YUV ranges AVCOL_RANGE_JPEG = 2, ///< the normal 2^n-1 "JPEG" YUV ranges AVCOL_RANGE_NB , ///< Not part of ABI }; /** * @defgroup lavu_frame AVFrame * @ingroup lavu_data * * @{ * AVFrame is an abstraction for reference-counted raw multimedia data. */ enum AVFrameSideDataType { /** * The data is the AVPanScan struct defined in libavcodec. */ AV_FRAME_DATA_PANSCAN, /** * ATSC A53 Part 4 Closed Captions. * A53 CC bitstream is stored as uint8_t in AVFrameSideData.data. * The number of bytes of CC data is AVFrameSideData.size. */ AV_FRAME_DATA_A53_CC, /** * Stereoscopic 3d metadata. * The data is the AVStereo3D struct defined in libavutil/stereo3d.h. */ AV_FRAME_DATA_STEREO3D, /** * The data is the AVMatrixEncoding enum defined in libavutil/channel_layout.h. */ AV_FRAME_DATA_MATRIXENCODING, /** * Metadata relevant to a downmix procedure. * The data is the AVDownmixInfo struct defined in libavutil/downmix_info.h. */ AV_FRAME_DATA_DOWNMIX_INFO, }; typedef struct AVFrameSideData { enum AVFrameSideDataType type; uint8_t *data; int size; AVDictionary *metadata; } AVFrameSideData; /** * This structure describes decoded (raw) audio or video data. * * AVFrame must be allocated using av_frame_alloc(). Note that this only * allocates the AVFrame itself, the buffers for the data must be managed * through other means (see below). * AVFrame must be freed with av_frame_free(). * * AVFrame is typically allocated once and then reused multiple times to hold * different data (e.g. a single AVFrame to hold frames received from a * decoder). In such a case, av_frame_unref() will free any references held by * the frame and reset it to its original clean state before it * is reused again. * * The data described by an AVFrame is usually reference counted through the * AVBuffer API. The underlying buffer references are stored in AVFrame.buf / * AVFrame.extended_buf. An AVFrame is considered to be reference counted if at * least one reference is set, i.e. if AVFrame.buf[0] != NULL. In such a case, * every single data plane must be contained in one of the buffers in * AVFrame.buf or AVFrame.extended_buf. * There may be a single buffer for all the data, or one separate buffer for * each plane, or anything in between. * * sizeof(AVFrame) is not a part of the public ABI, so new fields may be added * to the end with a minor bump. * Similarly fields that are marked as to be only accessed by * av_opt_ptr() can be reordered. This allows 2 forks to add fields * without breaking compatibility with each other. */ typedef struct AVFrame { #define AV_NUM_DATA_POINTERS 8 /** * pointer to the picture/channel planes. * This might be different from the first allocated byte * * Some decoders access areas outside 0,0 - width,height, please * see avcodec_align_dimensions2(). Some filters and swscale can read * up to 16 bytes beyond the planes, if these filters are to be used, * then 16 extra bytes must be allocated. */ uint8_t *data[AV_NUM_DATA_POINTERS]; /** * For video, size in bytes of each picture line. * For audio, size in bytes of each plane. * * For audio, only linesize[0] may be set. For planar audio, each channel * plane must be the same size. * * For video the linesizes should be multiplies of the CPUs alignment * preference, this is 16 or 32 for modern desktop CPUs. * Some code requires such alignment other code can be slower without * correct alignment, for yet other it makes no difference. * * @note The linesize may be larger than the size of usable data -- there * may be extra padding present for performance reasons. */ int linesize[AV_NUM_DATA_POINTERS]; /** * pointers to the data planes/channels. * * For video, this should simply point to data[]. * * For planar audio, each channel has a separate data pointer, and * linesize[0] contains the size of each channel buffer. * For packed audio, there is just one data pointer, and linesize[0] * contains the total size of the buffer for all channels. * * Note: Both data and extended_data should always be set in a valid frame, * but for planar audio with more channels that can fit in data, * extended_data must be used in order to access all channels. */ uint8_t **extended_data; /** * width and height of the video frame */ int width, height; /** * number of audio samples (per channel) described by this frame */ int nb_samples; /** * format of the frame, -1 if unknown or unset * Values correspond to enum AVPixelFormat for video frames, * enum AVSampleFormat for audio) */ int format; /** * 1 -> keyframe, 0-> not */ int key_frame; /** * Picture type of the frame. */ enum AVPictureType pict_type; #if FF_API_AVFRAME_LAVC attribute_deprecated uint8_t *base[AV_NUM_DATA_POINTERS]; #endif /** * Sample aspect ratio for the video frame, 0/1 if unknown/unspecified. */ AVRational sample_aspect_ratio; /** * Presentation timestamp in time_base units (time when frame should be shown to user). */ int64_t pts; /** * PTS copied from the AVPacket that was decoded to produce this frame. */ int64_t pkt_pts; /** * DTS copied from the AVPacket that triggered returning this frame. (if frame threading isnt used) * This is also the Presentation time of this AVFrame calculated from * only AVPacket.dts values without pts values. */ int64_t pkt_dts; /** * picture number in bitstream order */ int coded_picture_number; /** * picture number in display order */ int display_picture_number; /** * quality (between 1 (good) and FF_LAMBDA_MAX (bad)) */ int quality; #if FF_API_AVFRAME_LAVC attribute_deprecated int reference; /** * QP table */ attribute_deprecated int8_t *qscale_table; /** * QP store stride */ attribute_deprecated int qstride; attribute_deprecated int qscale_type; /** * mbskip_table[mb]>=1 if MB didn't change * stride= mb_width = (width+15)>>4 */ attribute_deprecated uint8_t *mbskip_table; /** * motion vector table * @code * example: * int mv_sample_log2= 4 - motion_subsample_log2; * int mb_width= (width+15)>>4; * int mv_stride= (mb_width << mv_sample_log2) + 1; * motion_val[direction][x + y*mv_stride][0->mv_x, 1->mv_y]; * @endcode */ attribute_deprecated int16_t (*motion_val[2])[2]; /** * macroblock type table * mb_type_base + mb_width + 2 */ attribute_deprecated uint32_t *mb_type; /** * DCT coefficients */ attribute_deprecated short *dct_coeff; /** * motion reference frame index * the order in which these are stored can depend on the codec. */ attribute_deprecated int8_t *ref_index[2]; #endif /** * for some private data of the user */ void *opaque; /** * error */ uint64_t error[AV_NUM_DATA_POINTERS]; #if FF_API_AVFRAME_LAVC attribute_deprecated int type; #endif /** * When decoding, this signals how much the picture must be delayed. * extra_delay = repeat_pict / (2*fps) */ int repeat_pict; /** * The content of the picture is interlaced. */ int interlaced_frame; /** * If the content is interlaced, is top field displayed first. */ int top_field_first; /** * Tell user application that palette has changed from previous frame. */ int palette_has_changed; #if FF_API_AVFRAME_LAVC attribute_deprecated int buffer_hints; /** * Pan scan. */ attribute_deprecated struct AVPanScan *pan_scan; #endif /** * reordered opaque 64bit (generally an integer or a double precision float * PTS but can be anything). * The user sets AVCodecContext.reordered_opaque to represent the input at * that time, * the decoder reorders values as needed and sets AVFrame.reordered_opaque * to exactly one of the values provided by the user through AVCodecContext.reordered_opaque * @deprecated in favor of pkt_pts */ int64_t reordered_opaque; #if FF_API_AVFRAME_LAVC /** * @deprecated this field is unused */ attribute_deprecated void *hwaccel_picture_private; attribute_deprecated struct AVCodecContext *owner; attribute_deprecated void *thread_opaque; /** * log2 of the size of the block which a single vector in motion_val represents: * (4->16x16, 3->8x8, 2-> 4x4, 1-> 2x2) */ attribute_deprecated uint8_t motion_subsample_log2; #endif /** * Sample rate of the audio data. */ int sample_rate; /** * Channel layout of the audio data. */ uint64_t channel_layout; /** * AVBuffer references backing the data for this frame. If all elements of * this array are NULL, then this frame is not reference counted. * * There may be at most one AVBuffer per data plane, so for video this array * always contains all the references. For planar audio with more than * AV_NUM_DATA_POINTERS channels, there may be more buffers than can fit in * this array. Then the extra AVBufferRef pointers are stored in the * extended_buf array. */ AVBufferRef *buf[AV_NUM_DATA_POINTERS]; /** * For planar audio which requires more than AV_NUM_DATA_POINTERS * AVBufferRef pointers, this array will hold all the references which * cannot fit into AVFrame.buf. * * Note that this is different from AVFrame.extended_data, which always * contains all the pointers. This array only contains the extra pointers, * which cannot fit into AVFrame.buf. * * This array is always allocated using av_malloc() by whoever constructs * the frame. It is freed in av_frame_unref(). */ AVBufferRef **extended_buf; /** * Number of elements in extended_buf. */ int nb_extended_buf; AVFrameSideData **side_data; int nb_side_data; /** * @defgroup lavu_frame_flags AV_FRAME_FLAGS * Flags describing additional frame properties. * * @{ */ /** * The frame data may be corrupted, e.g. due to decoding errors. */ #define AV_FRAME_FLAG_CORRUPT (1 << 0) /** * @} */ /** * Frame flags, a combination of @ref lavu_frame_flags */ int flags; /** * frame timestamp estimated using various heuristics, in stream time base * Code outside libavcodec should access this field using: * av_frame_get_best_effort_timestamp(frame) * - encoding: unused * - decoding: set by libavcodec, read by user. */ int64_t best_effort_timestamp; /** * reordered pos from the last AVPacket that has been input into the decoder * Code outside libavcodec should access this field using: * av_frame_get_pkt_pos(frame) * - encoding: unused * - decoding: Read by user. */ int64_t pkt_pos; /** * duration of the corresponding packet, expressed in * AVStream->time_base units, 0 if unknown. * Code outside libavcodec should access this field using: * av_frame_get_pkt_duration(frame) * - encoding: unused * - decoding: Read by user. */ int64_t pkt_duration; /** * metadata. * Code outside libavcodec should access this field using: * av_frame_get_metadata(frame) * - encoding: Set by user. * - decoding: Set by libavcodec. */ AVDictionary *metadata; /** * decode error flags of the frame, set to a combination of * FF_DECODE_ERROR_xxx flags if the decoder produced a frame, but there * were errors during the decoding. * Code outside libavcodec should access this field using: * av_frame_get_decode_error_flags(frame) * - encoding: unused * - decoding: set by libavcodec, read by user. */ int decode_error_flags; #define FF_DECODE_ERROR_INVALID_BITSTREAM 1 #define FF_DECODE_ERROR_MISSING_REFERENCE 2 /** * number of audio channels, only used for audio. * Code outside libavcodec should access this field using: * av_frame_get_channels(frame) * - encoding: unused * - decoding: Read by user. */ int channels; /** * size of the corresponding packet containing the compressed * frame. It must be accessed using av_frame_get_pkt_size() and * av_frame_set_pkt_size(). * It is set to a negative value if unknown. * - encoding: unused * - decoding: set by libavcodec, read by user. */ int pkt_size; /** * YUV colorspace type. * It must be accessed using av_frame_get_colorspace() and * av_frame_set_colorspace(). * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorSpace colorspace; /** * MPEG vs JPEG YUV range. * It must be accessed using av_frame_get_color_range() and * av_frame_set_color_range(). * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorRange color_range; /** * Not to be accessed directly from outside libavutil */ AVBufferRef *qp_table_buf; } AVFrame; /** * Accessors for some AVFrame fields. * The position of these field in the structure is not part of the ABI, * they should not be accessed directly outside libavcodec. */ int64_t av_frame_get_best_effort_timestamp(const AVFrame *frame); void av_frame_set_best_effort_timestamp(AVFrame *frame, int64_t val); int64_t av_frame_get_pkt_duration (const AVFrame *frame); void av_frame_set_pkt_duration (AVFrame *frame, int64_t val); int64_t av_frame_get_pkt_pos (const AVFrame *frame); void av_frame_set_pkt_pos (AVFrame *frame, int64_t val); int64_t av_frame_get_channel_layout (const AVFrame *frame); void av_frame_set_channel_layout (AVFrame *frame, int64_t val); int av_frame_get_channels (const AVFrame *frame); void av_frame_set_channels (AVFrame *frame, int val); int av_frame_get_sample_rate (const AVFrame *frame); void av_frame_set_sample_rate (AVFrame *frame, int val); AVDictionary *av_frame_get_metadata (const AVFrame *frame); void av_frame_set_metadata (AVFrame *frame, AVDictionary *val); int av_frame_get_decode_error_flags (const AVFrame *frame); void av_frame_set_decode_error_flags (AVFrame *frame, int val); int av_frame_get_pkt_size(const AVFrame *frame); void av_frame_set_pkt_size(AVFrame *frame, int val); AVDictionary **avpriv_frame_get_metadatap(AVFrame *frame); int8_t *av_frame_get_qp_table(AVFrame *f, int *stride, int *type); int av_frame_set_qp_table(AVFrame *f, AVBufferRef *buf, int stride, int type); enum AVColorSpace av_frame_get_colorspace(const AVFrame *frame); void av_frame_set_colorspace(AVFrame *frame, enum AVColorSpace val); enum AVColorRange av_frame_get_color_range(const AVFrame *frame); void av_frame_set_color_range(AVFrame *frame, enum AVColorRange val); /** * Get the name of a colorspace. * @return a static string identifying the colorspace; can be NULL. */ const char *av_get_colorspace_name(enum AVColorSpace val); /** * Allocate an AVFrame and set its fields to default values. The resulting * struct must be freed using av_frame_free(). * * @return An AVFrame filled with default values or NULL on failure. * * @note this only allocates the AVFrame itself, not the data buffers. Those * must be allocated through other means, e.g. with av_frame_get_buffer() or * manually. */ AVFrame *av_frame_alloc(void); /** * Free the frame and any dynamically allocated objects in it, * e.g. extended_data. If the frame is reference counted, it will be * unreferenced first. * * @param frame frame to be freed. The pointer will be set to NULL. */ void av_frame_free(AVFrame **frame); /** * Set up a new reference to the data described by the source frame. * * Copy frame properties from src to dst and create a new reference for each * AVBufferRef from src. * * If src is not reference counted, new buffers are allocated and the data is * copied. * * @return 0 on success, a negative AVERROR on error */ int av_frame_ref(AVFrame *dst, const AVFrame *src); /** * Create a new frame that references the same data as src. * * This is a shortcut for av_frame_alloc()+av_frame_ref(). * * @return newly created AVFrame on success, NULL on error. */ AVFrame *av_frame_clone(const AVFrame *src); /** * Unreference all the buffers referenced by frame and reset the frame fields. */ void av_frame_unref(AVFrame *frame); /** * Move everythnig contained in src to dst and reset src. */ void av_frame_move_ref(AVFrame *dst, AVFrame *src); /** * Allocate new buffer(s) for audio or video data. * * The following fields must be set on frame before calling this function: * - format (pixel format for video, sample format for audio) * - width and height for video * - nb_samples and channel_layout for audio * * This function will fill AVFrame.data and AVFrame.buf arrays and, if * necessary, allocate and fill AVFrame.extended_data and AVFrame.extended_buf. * For planar formats, one buffer will be allocated for each plane. * * @param frame frame in which to store the new buffers. * @param align required buffer size alignment * * @return 0 on success, a negative AVERROR on error. */ int av_frame_get_buffer(AVFrame *frame, int align); /** * Check if the frame data is writable. * * @return A positive value if the frame data is writable (which is true if and * only if each of the underlying buffers has only one reference, namely the one * stored in this frame). Return 0 otherwise. * * If 1 is returned the answer is valid until av_buffer_ref() is called on any * of the underlying AVBufferRefs (e.g. through av_frame_ref() or directly). * * @see av_frame_make_writable(), av_buffer_is_writable() */ int av_frame_is_writable(AVFrame *frame); /** * Ensure that the frame data is writable, avoiding data copy if possible. * * Do nothing if the frame is writable, allocate new buffers and copy the data * if it is not. * * @return 0 on success, a negative AVERROR on error. * * @see av_frame_is_writable(), av_buffer_is_writable(), * av_buffer_make_writable() */ int av_frame_make_writable(AVFrame *frame); /** * Copy the frame data from src to dst. * * This function does not allocate anything, dst must be already initialized and * allocated with the same parameters as src. * * This function only copies the frame data (i.e. the contents of the data / * extended data arrays), not any other properties. * * @return >= 0 on success, a negative AVERROR on error. */ int av_frame_copy(AVFrame *dst, const AVFrame *src); /** * Copy only "metadata" fields from src to dst. * * Metadata for the purpose of this function are those fields that do not affect * the data layout in the buffers. E.g. pts, sample rate (for audio) or sample * aspect ratio (for video), but not width/height or channel layout. * Side data is also copied. */ int av_frame_copy_props(AVFrame *dst, const AVFrame *src); /** * Get the buffer reference a given data plane is stored in. * * @param plane index of the data plane of interest in frame->extended_data. * * @return the buffer reference that contains the plane or NULL if the input * frame is not valid. */ AVBufferRef *av_frame_get_plane_buffer(AVFrame *frame, int plane); /** * Add a new side data to a frame. * * @param frame a frame to which the side data should be added * @param type type of the added side data * @param size size of the side data * * @return newly added side data on success, NULL on error */ AVFrameSideData *av_frame_new_side_data(AVFrame *frame, enum AVFrameSideDataType type, int size); /** * @return a pointer to the side data of a given type on success, NULL if there * is no side data with such type in this frame. */ AVFrameSideData *av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type); /** * @} */ #endif /* AVUTIL_FRAME_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/hmac.h ================================================ /* * Copyright (C) 2012 Martin Storsjo * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HMAC_H #define AVUTIL_HMAC_H #include /** * @defgroup lavu_hmac HMAC * @ingroup lavu_crypto * @{ */ enum AVHMACType { AV_HMAC_MD5, AV_HMAC_SHA1, AV_HMAC_SHA224 = 10, AV_HMAC_SHA256, AV_HMAC_SHA384, AV_HMAC_SHA512, }; typedef struct AVHMAC AVHMAC; /** * Allocate an AVHMAC context. * @param type The hash function used for the HMAC. */ AVHMAC *av_hmac_alloc(enum AVHMACType type); /** * Free an AVHMAC context. * @param ctx The context to free, may be NULL */ void av_hmac_free(AVHMAC *ctx); /** * Initialize an AVHMAC context with an authentication key. * @param ctx The HMAC context * @param key The authentication key * @param keylen The length of the key, in bytes */ void av_hmac_init(AVHMAC *ctx, const uint8_t *key, unsigned int keylen); /** * Hash data with the HMAC. * @param ctx The HMAC context * @param data The data to hash * @param len The length of the data, in bytes */ void av_hmac_update(AVHMAC *ctx, const uint8_t *data, unsigned int len); /** * Finish hashing and output the HMAC digest. * @param ctx The HMAC context * @param out The output buffer to write the digest into * @param outlen The length of the out buffer, in bytes * @return The number of bytes written to out, or a negative error code. */ int av_hmac_final(AVHMAC *ctx, uint8_t *out, unsigned int outlen); /** * Hash an array of data with a key. * @param ctx The HMAC context * @param data The data to hash * @param len The length of the data, in bytes * @param key The authentication key * @param keylen The length of the key, in bytes * @param out The output buffer to write the digest into * @param outlen The length of the out buffer, in bytes * @return The number of bytes written to out, or a negative error code. */ int av_hmac_calc(AVHMAC *ctx, const uint8_t *data, unsigned int len, const uint8_t *key, unsigned int keylen, uint8_t *out, unsigned int outlen); /** * @} */ #endif /* AVUTIL_HMAC_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/imgutils.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_IMGUTILS_H #define AVUTIL_IMGUTILS_H /** * @file * misc image utilities * * @addtogroup lavu_picture * @{ */ #include "avutil.h" #include "pixdesc.h" /** * Compute the max pixel step for each plane of an image with a * format described by pixdesc. * * The pixel step is the distance in bytes between the first byte of * the group of bytes which describe a pixel component and the first * byte of the successive group in the same plane for the same * component. * * @param max_pixsteps an array which is filled with the max pixel step * for each plane. Since a plane may contain different pixel * components, the computed max_pixsteps[plane] is relative to the * component in the plane with the max pixel step. * @param max_pixstep_comps an array which is filled with the component * for each plane which has the max pixel step. May be NULL. */ void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4], const AVPixFmtDescriptor *pixdesc); /** * Compute the size of an image line with format pix_fmt and width * width for the plane plane. * * @return the computed size in bytes */ int av_image_get_linesize(enum AVPixelFormat pix_fmt, int width, int plane); /** * Fill plane linesizes for an image with pixel format pix_fmt and * width width. * * @param linesizes array to be filled with the linesize for each plane * @return >= 0 in case of success, a negative error code otherwise */ int av_image_fill_linesizes(int linesizes[4], enum AVPixelFormat pix_fmt, int width); /** * Fill plane data pointers for an image with pixel format pix_fmt and * height height. * * @param data pointers array to be filled with the pointer for each image plane * @param ptr the pointer to a buffer which will contain the image * @param linesizes the array containing the linesize for each * plane, should be filled by av_image_fill_linesizes() * @return the size in bytes required for the image buffer, a negative * error code in case of failure */ int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height, uint8_t *ptr, const int linesizes[4]); /** * Allocate an image with size w and h and pixel format pix_fmt, and * fill pointers and linesizes accordingly. * The allocated image buffer has to be freed by using * av_freep(&pointers[0]). * * @param align the value to use for buffer size alignment * @return the size in bytes required for the image buffer, a negative * error code in case of failure */ int av_image_alloc(uint8_t *pointers[4], int linesizes[4], int w, int h, enum AVPixelFormat pix_fmt, int align); /** * Copy image plane from src to dst. * That is, copy "height" number of lines of "bytewidth" bytes each. * The first byte of each successive line is separated by *_linesize * bytes. * * bytewidth must be contained by both absolute values of dst_linesize * and src_linesize, otherwise the function behavior is undefined. * * @param dst_linesize linesize for the image plane in dst * @param src_linesize linesize for the image plane in src */ void av_image_copy_plane(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int bytewidth, int height); /** * Copy image in src_data to dst_data. * * @param dst_linesizes linesizes for the image in dst_data * @param src_linesizes linesizes for the image in src_data */ void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height); /** * Setup the data pointers and linesizes based on the specified image * parameters and the provided array. * * The fields of the given image are filled in by using the src * address which points to the image data buffer. Depending on the * specified pixel format, one or multiple image data pointers and * line sizes will be set. If a planar format is specified, several * pointers will be set pointing to the different picture planes and * the line sizes of the different planes will be stored in the * lines_sizes array. Call with src == NULL to get the required * size for the src buffer. * * To allocate the buffer and fill in the dst_data and dst_linesize in * one call, use av_image_alloc(). * * @param dst_data data pointers to be filled in * @param dst_linesizes linesizes for the image in dst_data to be filled in * @param src buffer which will contain or contains the actual image data, can be NULL * @param pix_fmt the pixel format of the image * @param width the width of the image in pixels * @param height the height of the image in pixels * @param align the value used in src for linesize alignment * @return the size in bytes required for src, a negative error code * in case of failure */ int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4], const uint8_t *src, enum AVPixelFormat pix_fmt, int width, int height, int align); /** * Return the size in bytes of the amount of data required to store an * image with the given parameters. * * @param[in] align the assumed linesize alignment */ int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align); /** * Copy image data from an image into a buffer. * * av_image_get_buffer_size() can be used to compute the required size * for the buffer to fill. * * @param dst a buffer into which picture data will be copied * @param dst_size the size in bytes of dst * @param src_data pointers containing the source image data * @param src_linesizes linesizes for the image in src_data * @param pix_fmt the pixel format of the source image * @param width the width of the source image in pixels * @param height the height of the source image in pixels * @param align the assumed linesize alignment for dst * @return the number of bytes written to dst, or a negative value * (error code) on error */ int av_image_copy_to_buffer(uint8_t *dst, int dst_size, const uint8_t * const src_data[4], const int src_linesize[4], enum AVPixelFormat pix_fmt, int width, int height, int align); /** * Check if the given dimension of an image is valid, meaning that all * bytes of the image can be addressed with a signed int. * * @param w the width of the picture * @param h the height of the picture * @param log_offset the offset to sum to the log level for logging with log_ctx * @param log_ctx the parent logging context, it may be NULL * @return >= 0 if valid, a negative error code otherwise */ int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx); int avpriv_set_systematic_pal2(uint32_t pal[256], enum AVPixelFormat pix_fmt); /** * @} */ #endif /* AVUTIL_IMGUTILS_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/intfloat.h ================================================ /* * Copyright (c) 2011 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_INTFLOAT_H #define AVUTIL_INTFLOAT_H #include #include "attributes.h" union av_intfloat32 { uint32_t i; float f; }; union av_intfloat64 { uint64_t i; double f; }; /** * Reinterpret a 32-bit integer as a float. */ static av_always_inline float av_int2float(uint32_t i) { union av_intfloat32 v; v.i = i; return v.f; } /** * Reinterpret a float as a 32-bit integer. */ static av_always_inline uint32_t av_float2int(float f) { union av_intfloat32 v; v.f = f; return v.i; } /** * Reinterpret a 64-bit integer as a double. */ static av_always_inline double av_int2double(uint64_t i) { union av_intfloat64 v; v.i = i; return v.f; } /** * Reinterpret a double as a 64-bit integer. */ static av_always_inline uint64_t av_double2int(double f) { union av_intfloat64 v; v.f = f; return v.i; } #endif /* AVUTIL_INTFLOAT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/intfloat_readwrite.h ================================================ /* * copyright (c) 2005 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_INTFLOAT_READWRITE_H #define AVUTIL_INTFLOAT_READWRITE_H #include #include "attributes.h" #include "version.h" #if FF_API_INTFLOAT /* IEEE 80 bits extended float */ typedef struct AVExtFloat { uint8_t exponent[2]; uint8_t mantissa[8]; } AVExtFloat; attribute_deprecated double av_int2dbl(int64_t v) av_const; attribute_deprecated float av_int2flt(int32_t v) av_const; attribute_deprecated double av_ext2dbl(const AVExtFloat ext) av_const; attribute_deprecated int64_t av_dbl2int(double d) av_const; attribute_deprecated int32_t av_flt2int(float d) av_const; attribute_deprecated AVExtFloat av_dbl2ext(double d) av_const; #endif /* FF_API_INTFLOAT */ #endif /* AVUTIL_INTFLOAT_READWRITE_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/intreadwrite.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_INTREADWRITE_H #define AVUTIL_INTREADWRITE_H #include #include "libavutil/avconfig.h" #include "attributes.h" #include "bswap.h" typedef union { uint64_t u64; uint32_t u32[2]; uint16_t u16[4]; uint8_t u8 [8]; double f64; float f32[2]; } av_alias av_alias64; typedef union { uint32_t u32; uint16_t u16[2]; uint8_t u8 [4]; float f32; } av_alias av_alias32; typedef union { uint16_t u16; uint8_t u8 [2]; } av_alias av_alias16; /* * Arch-specific headers can provide any combination of * AV_[RW][BLN](16|24|32|48|64) and AV_(COPY|SWAP|ZERO)(64|128) macros. * Preprocessor symbols must be defined, even if these are implemented * as inline functions. */ #ifdef HAVE_AV_CONFIG_H #include "config.h" #if ARCH_ARM # include "arm/intreadwrite.h" #elif ARCH_AVR32 # include "avr32/intreadwrite.h" #elif ARCH_MIPS # include "mips/intreadwrite.h" #elif ARCH_PPC # include "ppc/intreadwrite.h" #elif ARCH_TOMI # include "tomi/intreadwrite.h" #elif ARCH_X86 # include "x86/intreadwrite.h" #endif #endif /* HAVE_AV_CONFIG_H */ /* * Map AV_RNXX <-> AV_R[BL]XX for all variants provided by per-arch headers. */ #if AV_HAVE_BIGENDIAN # if defined(AV_RN16) && !defined(AV_RB16) # define AV_RB16(p) AV_RN16(p) # elif !defined(AV_RN16) && defined(AV_RB16) # define AV_RN16(p) AV_RB16(p) # endif # if defined(AV_WN16) && !defined(AV_WB16) # define AV_WB16(p, v) AV_WN16(p, v) # elif !defined(AV_WN16) && defined(AV_WB16) # define AV_WN16(p, v) AV_WB16(p, v) # endif # if defined(AV_RN24) && !defined(AV_RB24) # define AV_RB24(p) AV_RN24(p) # elif !defined(AV_RN24) && defined(AV_RB24) # define AV_RN24(p) AV_RB24(p) # endif # if defined(AV_WN24) && !defined(AV_WB24) # define AV_WB24(p, v) AV_WN24(p, v) # elif !defined(AV_WN24) && defined(AV_WB24) # define AV_WN24(p, v) AV_WB24(p, v) # endif # if defined(AV_RN32) && !defined(AV_RB32) # define AV_RB32(p) AV_RN32(p) # elif !defined(AV_RN32) && defined(AV_RB32) # define AV_RN32(p) AV_RB32(p) # endif # if defined(AV_WN32) && !defined(AV_WB32) # define AV_WB32(p, v) AV_WN32(p, v) # elif !defined(AV_WN32) && defined(AV_WB32) # define AV_WN32(p, v) AV_WB32(p, v) # endif # if defined(AV_RN48) && !defined(AV_RB48) # define AV_RB48(p) AV_RN48(p) # elif !defined(AV_RN48) && defined(AV_RB48) # define AV_RN48(p) AV_RB48(p) # endif # if defined(AV_WN48) && !defined(AV_WB48) # define AV_WB48(p, v) AV_WN48(p, v) # elif !defined(AV_WN48) && defined(AV_WB48) # define AV_WN48(p, v) AV_WB48(p, v) # endif # if defined(AV_RN64) && !defined(AV_RB64) # define AV_RB64(p) AV_RN64(p) # elif !defined(AV_RN64) && defined(AV_RB64) # define AV_RN64(p) AV_RB64(p) # endif # if defined(AV_WN64) && !defined(AV_WB64) # define AV_WB64(p, v) AV_WN64(p, v) # elif !defined(AV_WN64) && defined(AV_WB64) # define AV_WN64(p, v) AV_WB64(p, v) # endif #else /* AV_HAVE_BIGENDIAN */ # if defined(AV_RN16) && !defined(AV_RL16) # define AV_RL16(p) AV_RN16(p) # elif !defined(AV_RN16) && defined(AV_RL16) # define AV_RN16(p) AV_RL16(p) # endif # if defined(AV_WN16) && !defined(AV_WL16) # define AV_WL16(p, v) AV_WN16(p, v) # elif !defined(AV_WN16) && defined(AV_WL16) # define AV_WN16(p, v) AV_WL16(p, v) # endif # if defined(AV_RN24) && !defined(AV_RL24) # define AV_RL24(p) AV_RN24(p) # elif !defined(AV_RN24) && defined(AV_RL24) # define AV_RN24(p) AV_RL24(p) # endif # if defined(AV_WN24) && !defined(AV_WL24) # define AV_WL24(p, v) AV_WN24(p, v) # elif !defined(AV_WN24) && defined(AV_WL24) # define AV_WN24(p, v) AV_WL24(p, v) # endif # if defined(AV_RN32) && !defined(AV_RL32) # define AV_RL32(p) AV_RN32(p) # elif !defined(AV_RN32) && defined(AV_RL32) # define AV_RN32(p) AV_RL32(p) # endif # if defined(AV_WN32) && !defined(AV_WL32) # define AV_WL32(p, v) AV_WN32(p, v) # elif !defined(AV_WN32) && defined(AV_WL32) # define AV_WN32(p, v) AV_WL32(p, v) # endif # if defined(AV_RN48) && !defined(AV_RL48) # define AV_RL48(p) AV_RN48(p) # elif !defined(AV_RN48) && defined(AV_RL48) # define AV_RN48(p) AV_RL48(p) # endif # if defined(AV_WN48) && !defined(AV_WL48) # define AV_WL48(p, v) AV_WN48(p, v) # elif !defined(AV_WN48) && defined(AV_WL48) # define AV_WN48(p, v) AV_WL48(p, v) # endif # if defined(AV_RN64) && !defined(AV_RL64) # define AV_RL64(p) AV_RN64(p) # elif !defined(AV_RN64) && defined(AV_RL64) # define AV_RN64(p) AV_RL64(p) # endif # if defined(AV_WN64) && !defined(AV_WL64) # define AV_WL64(p, v) AV_WN64(p, v) # elif !defined(AV_WN64) && defined(AV_WL64) # define AV_WN64(p, v) AV_WL64(p, v) # endif #endif /* !AV_HAVE_BIGENDIAN */ /* * Define AV_[RW]N helper macros to simplify definitions not provided * by per-arch headers. */ #if defined(__GNUC__) && !defined(__TI_COMPILER_VERSION__) union unaligned_64 { uint64_t l; } __attribute__((packed)) av_alias; union unaligned_32 { uint32_t l; } __attribute__((packed)) av_alias; union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias; # define AV_RN(s, p) (((const union unaligned_##s *) (p))->l) # define AV_WN(s, p, v) ((((union unaligned_##s *) (p))->l) = (v)) #elif defined(__DECC) # define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p))) # define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v)) #elif AV_HAVE_FAST_UNALIGNED # define AV_RN(s, p) (((const av_alias##s*)(p))->u##s) # define AV_WN(s, p, v) (((av_alias##s*)(p))->u##s = (v)) #else #ifndef AV_RB16 # define AV_RB16(x) \ ((((const uint8_t*)(x))[0] << 8) | \ ((const uint8_t*)(x))[1]) #endif #ifndef AV_WB16 # define AV_WB16(p, darg) do { \ unsigned d = (darg); \ ((uint8_t*)(p))[1] = (d); \ ((uint8_t*)(p))[0] = (d)>>8; \ } while(0) #endif #ifndef AV_RL16 # define AV_RL16(x) \ ((((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[0]) #endif #ifndef AV_WL16 # define AV_WL16(p, darg) do { \ unsigned d = (darg); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ } while(0) #endif #ifndef AV_RB32 # define AV_RB32(x) \ (((uint32_t)((const uint8_t*)(x))[0] << 24) | \ (((const uint8_t*)(x))[1] << 16) | \ (((const uint8_t*)(x))[2] << 8) | \ ((const uint8_t*)(x))[3]) #endif #ifndef AV_WB32 # define AV_WB32(p, darg) do { \ unsigned d = (darg); \ ((uint8_t*)(p))[3] = (d); \ ((uint8_t*)(p))[2] = (d)>>8; \ ((uint8_t*)(p))[1] = (d)>>16; \ ((uint8_t*)(p))[0] = (d)>>24; \ } while(0) #endif #ifndef AV_RL32 # define AV_RL32(x) \ (((uint32_t)((const uint8_t*)(x))[3] << 24) | \ (((const uint8_t*)(x))[2] << 16) | \ (((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[0]) #endif #ifndef AV_WL32 # define AV_WL32(p, darg) do { \ unsigned d = (darg); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ ((uint8_t*)(p))[3] = (d)>>24; \ } while(0) #endif #ifndef AV_RB64 # define AV_RB64(x) \ (((uint64_t)((const uint8_t*)(x))[0] << 56) | \ ((uint64_t)((const uint8_t*)(x))[1] << 48) | \ ((uint64_t)((const uint8_t*)(x))[2] << 40) | \ ((uint64_t)((const uint8_t*)(x))[3] << 32) | \ ((uint64_t)((const uint8_t*)(x))[4] << 24) | \ ((uint64_t)((const uint8_t*)(x))[5] << 16) | \ ((uint64_t)((const uint8_t*)(x))[6] << 8) | \ (uint64_t)((const uint8_t*)(x))[7]) #endif #ifndef AV_WB64 # define AV_WB64(p, darg) do { \ uint64_t d = (darg); \ ((uint8_t*)(p))[7] = (d); \ ((uint8_t*)(p))[6] = (d)>>8; \ ((uint8_t*)(p))[5] = (d)>>16; \ ((uint8_t*)(p))[4] = (d)>>24; \ ((uint8_t*)(p))[3] = (d)>>32; \ ((uint8_t*)(p))[2] = (d)>>40; \ ((uint8_t*)(p))[1] = (d)>>48; \ ((uint8_t*)(p))[0] = (d)>>56; \ } while(0) #endif #ifndef AV_RL64 # define AV_RL64(x) \ (((uint64_t)((const uint8_t*)(x))[7] << 56) | \ ((uint64_t)((const uint8_t*)(x))[6] << 48) | \ ((uint64_t)((const uint8_t*)(x))[5] << 40) | \ ((uint64_t)((const uint8_t*)(x))[4] << 32) | \ ((uint64_t)((const uint8_t*)(x))[3] << 24) | \ ((uint64_t)((const uint8_t*)(x))[2] << 16) | \ ((uint64_t)((const uint8_t*)(x))[1] << 8) | \ (uint64_t)((const uint8_t*)(x))[0]) #endif #ifndef AV_WL64 # define AV_WL64(p, darg) do { \ uint64_t d = (darg); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ ((uint8_t*)(p))[3] = (d)>>24; \ ((uint8_t*)(p))[4] = (d)>>32; \ ((uint8_t*)(p))[5] = (d)>>40; \ ((uint8_t*)(p))[6] = (d)>>48; \ ((uint8_t*)(p))[7] = (d)>>56; \ } while(0) #endif #if AV_HAVE_BIGENDIAN # define AV_RN(s, p) AV_RB##s(p) # define AV_WN(s, p, v) AV_WB##s(p, v) #else # define AV_RN(s, p) AV_RL##s(p) # define AV_WN(s, p, v) AV_WL##s(p, v) #endif #endif /* HAVE_FAST_UNALIGNED */ #ifndef AV_RN16 # define AV_RN16(p) AV_RN(16, p) #endif #ifndef AV_RN32 # define AV_RN32(p) AV_RN(32, p) #endif #ifndef AV_RN64 # define AV_RN64(p) AV_RN(64, p) #endif #ifndef AV_WN16 # define AV_WN16(p, v) AV_WN(16, p, v) #endif #ifndef AV_WN32 # define AV_WN32(p, v) AV_WN(32, p, v) #endif #ifndef AV_WN64 # define AV_WN64(p, v) AV_WN(64, p, v) #endif #if AV_HAVE_BIGENDIAN # define AV_RB(s, p) AV_RN##s(p) # define AV_WB(s, p, v) AV_WN##s(p, v) # define AV_RL(s, p) av_bswap##s(AV_RN##s(p)) # define AV_WL(s, p, v) AV_WN##s(p, av_bswap##s(v)) #else # define AV_RB(s, p) av_bswap##s(AV_RN##s(p)) # define AV_WB(s, p, v) AV_WN##s(p, av_bswap##s(v)) # define AV_RL(s, p) AV_RN##s(p) # define AV_WL(s, p, v) AV_WN##s(p, v) #endif #define AV_RB8(x) (((const uint8_t*)(x))[0]) #define AV_WB8(p, d) do { ((uint8_t*)(p))[0] = (d); } while(0) #define AV_RL8(x) AV_RB8(x) #define AV_WL8(p, d) AV_WB8(p, d) #ifndef AV_RB16 # define AV_RB16(p) AV_RB(16, p) #endif #ifndef AV_WB16 # define AV_WB16(p, v) AV_WB(16, p, v) #endif #ifndef AV_RL16 # define AV_RL16(p) AV_RL(16, p) #endif #ifndef AV_WL16 # define AV_WL16(p, v) AV_WL(16, p, v) #endif #ifndef AV_RB32 # define AV_RB32(p) AV_RB(32, p) #endif #ifndef AV_WB32 # define AV_WB32(p, v) AV_WB(32, p, v) #endif #ifndef AV_RL32 # define AV_RL32(p) AV_RL(32, p) #endif #ifndef AV_WL32 # define AV_WL32(p, v) AV_WL(32, p, v) #endif #ifndef AV_RB64 # define AV_RB64(p) AV_RB(64, p) #endif #ifndef AV_WB64 # define AV_WB64(p, v) AV_WB(64, p, v) #endif #ifndef AV_RL64 # define AV_RL64(p) AV_RL(64, p) #endif #ifndef AV_WL64 # define AV_WL64(p, v) AV_WL(64, p, v) #endif #ifndef AV_RB24 # define AV_RB24(x) \ ((((const uint8_t*)(x))[0] << 16) | \ (((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[2]) #endif #ifndef AV_WB24 # define AV_WB24(p, d) do { \ ((uint8_t*)(p))[2] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[0] = (d)>>16; \ } while(0) #endif #ifndef AV_RL24 # define AV_RL24(x) \ ((((const uint8_t*)(x))[2] << 16) | \ (((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[0]) #endif #ifndef AV_WL24 # define AV_WL24(p, d) do { \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ } while(0) #endif #ifndef AV_RB48 # define AV_RB48(x) \ (((uint64_t)((const uint8_t*)(x))[0] << 40) | \ ((uint64_t)((const uint8_t*)(x))[1] << 32) | \ ((uint64_t)((const uint8_t*)(x))[2] << 24) | \ ((uint64_t)((const uint8_t*)(x))[3] << 16) | \ ((uint64_t)((const uint8_t*)(x))[4] << 8) | \ (uint64_t)((const uint8_t*)(x))[5]) #endif #ifndef AV_WB48 # define AV_WB48(p, darg) do { \ uint64_t d = (darg); \ ((uint8_t*)(p))[5] = (d); \ ((uint8_t*)(p))[4] = (d)>>8; \ ((uint8_t*)(p))[3] = (d)>>16; \ ((uint8_t*)(p))[2] = (d)>>24; \ ((uint8_t*)(p))[1] = (d)>>32; \ ((uint8_t*)(p))[0] = (d)>>40; \ } while(0) #endif #ifndef AV_RL48 # define AV_RL48(x) \ (((uint64_t)((const uint8_t*)(x))[5] << 40) | \ ((uint64_t)((const uint8_t*)(x))[4] << 32) | \ ((uint64_t)((const uint8_t*)(x))[3] << 24) | \ ((uint64_t)((const uint8_t*)(x))[2] << 16) | \ ((uint64_t)((const uint8_t*)(x))[1] << 8) | \ (uint64_t)((const uint8_t*)(x))[0]) #endif #ifndef AV_WL48 # define AV_WL48(p, darg) do { \ uint64_t d = (darg); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ ((uint8_t*)(p))[3] = (d)>>24; \ ((uint8_t*)(p))[4] = (d)>>32; \ ((uint8_t*)(p))[5] = (d)>>40; \ } while(0) #endif /* * The AV_[RW]NA macros access naturally aligned data * in a type-safe way. */ #define AV_RNA(s, p) (((const av_alias##s*)(p))->u##s) #define AV_WNA(s, p, v) (((av_alias##s*)(p))->u##s = (v)) #ifndef AV_RN16A # define AV_RN16A(p) AV_RNA(16, p) #endif #ifndef AV_RN32A # define AV_RN32A(p) AV_RNA(32, p) #endif #ifndef AV_RN64A # define AV_RN64A(p) AV_RNA(64, p) #endif #ifndef AV_WN16A # define AV_WN16A(p, v) AV_WNA(16, p, v) #endif #ifndef AV_WN32A # define AV_WN32A(p, v) AV_WNA(32, p, v) #endif #ifndef AV_WN64A # define AV_WN64A(p, v) AV_WNA(64, p, v) #endif /* * The AV_COPYxxU macros are suitable for copying data to/from unaligned * memory locations. */ #define AV_COPYU(n, d, s) AV_WN##n(d, AV_RN##n(s)); #ifndef AV_COPY16U # define AV_COPY16U(d, s) AV_COPYU(16, d, s) #endif #ifndef AV_COPY32U # define AV_COPY32U(d, s) AV_COPYU(32, d, s) #endif #ifndef AV_COPY64U # define AV_COPY64U(d, s) AV_COPYU(64, d, s) #endif #ifndef AV_COPY128U # define AV_COPY128U(d, s) \ do { \ AV_COPY64U(d, s); \ AV_COPY64U((char *)(d) + 8, (const char *)(s) + 8); \ } while(0) #endif /* Parameters for AV_COPY*, AV_SWAP*, AV_ZERO* must be * naturally aligned. They may be implemented using MMX, * so emms_c() must be called before using any float code * afterwards. */ #define AV_COPY(n, d, s) \ (((av_alias##n*)(d))->u##n = ((const av_alias##n*)(s))->u##n) #ifndef AV_COPY16 # define AV_COPY16(d, s) AV_COPY(16, d, s) #endif #ifndef AV_COPY32 # define AV_COPY32(d, s) AV_COPY(32, d, s) #endif #ifndef AV_COPY64 # define AV_COPY64(d, s) AV_COPY(64, d, s) #endif #ifndef AV_COPY128 # define AV_COPY128(d, s) \ do { \ AV_COPY64(d, s); \ AV_COPY64((char*)(d)+8, (char*)(s)+8); \ } while(0) #endif #define AV_SWAP(n, a, b) FFSWAP(av_alias##n, *(av_alias##n*)(a), *(av_alias##n*)(b)) #ifndef AV_SWAP64 # define AV_SWAP64(a, b) AV_SWAP(64, a, b) #endif #define AV_ZERO(n, d) (((av_alias##n*)(d))->u##n = 0) #ifndef AV_ZERO16 # define AV_ZERO16(d) AV_ZERO(16, d) #endif #ifndef AV_ZERO32 # define AV_ZERO32(d) AV_ZERO(32, d) #endif #ifndef AV_ZERO64 # define AV_ZERO64(d) AV_ZERO(64, d) #endif #ifndef AV_ZERO128 # define AV_ZERO128(d) \ do { \ AV_ZERO64(d); \ AV_ZERO64((char*)(d)+8); \ } while(0) #endif #endif /* AVUTIL_INTREADWRITE_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/lfg.h ================================================ /* * Lagged Fibonacci PRNG * Copyright (c) 2008 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LFG_H #define AVUTIL_LFG_H typedef struct AVLFG { unsigned int state[64]; int index; } AVLFG; void av_lfg_init(AVLFG *c, unsigned int seed); /** * Get the next random unsigned 32-bit number using an ALFG. * * Please also consider a simple LCG like state= state*1664525+1013904223, * it may be good enough and faster for your specific use case. */ static inline unsigned int av_lfg_get(AVLFG *c){ c->state[c->index & 63] = c->state[(c->index-24) & 63] + c->state[(c->index-55) & 63]; return c->state[c->index++ & 63]; } /** * Get the next random unsigned 32-bit number using a MLFG. * * Please also consider av_lfg_get() above, it is faster. */ static inline unsigned int av_mlfg_get(AVLFG *c){ unsigned int a= c->state[(c->index-55) & 63]; unsigned int b= c->state[(c->index-24) & 63]; return c->state[c->index++ & 63] = 2*a*b+a+b; } /** * Get the next two numbers generated by a Box-Muller Gaussian * generator using the random numbers issued by lfg. * * @param out array where the two generated numbers are placed */ void av_bmg_get(AVLFG *lfg, double out[2]); #endif /* AVUTIL_LFG_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/log.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LOG_H #define AVUTIL_LOG_H #include #include "avutil.h" #include "attributes.h" typedef enum { AV_CLASS_CATEGORY_NA = 0, AV_CLASS_CATEGORY_INPUT, AV_CLASS_CATEGORY_OUTPUT, AV_CLASS_CATEGORY_MUXER, AV_CLASS_CATEGORY_DEMUXER, AV_CLASS_CATEGORY_ENCODER, AV_CLASS_CATEGORY_DECODER, AV_CLASS_CATEGORY_FILTER, AV_CLASS_CATEGORY_BITSTREAM_FILTER, AV_CLASS_CATEGORY_SWSCALER, AV_CLASS_CATEGORY_SWRESAMPLER, AV_CLASS_CATEGORY_NB, ///< not part of ABI/API }AVClassCategory; struct AVOptionRanges; /** * Describe the class of an AVClass context structure. That is an * arbitrary struct of which the first field is a pointer to an * AVClass struct (e.g. AVCodecContext, AVFormatContext etc.). */ typedef struct AVClass { /** * The name of the class; usually it is the same name as the * context structure type to which the AVClass is associated. */ const char* class_name; /** * A pointer to a function which returns the name of a context * instance ctx associated with the class. */ const char* (*item_name)(void* ctx); /** * a pointer to the first option specified in the class if any or NULL * * @see av_set_default_options() */ const struct AVOption *option; /** * LIBAVUTIL_VERSION with which this structure was created. * This is used to allow fields to be added without requiring major * version bumps everywhere. */ int version; /** * Offset in the structure where log_level_offset is stored. * 0 means there is no such variable */ int log_level_offset_offset; /** * Offset in the structure where a pointer to the parent context for * logging is stored. For example a decoder could pass its AVCodecContext * to eval as such a parent context, which an av_log() implementation * could then leverage to display the parent context. * The offset can be NULL. */ int parent_log_context_offset; /** * Return next AVOptions-enabled child or NULL */ void* (*child_next)(void *obj, void *prev); /** * Return an AVClass corresponding to the next potential * AVOptions-enabled child. * * The difference between child_next and this is that * child_next iterates over _already existing_ objects, while * child_class_next iterates over _all possible_ children. */ const struct AVClass* (*child_class_next)(const struct AVClass *prev); /** * Category used for visualization (like color) * This is only set if the category is equal for all objects using this class. * available since version (51 << 16 | 56 << 8 | 100) */ AVClassCategory category; /** * Callback to return the category. * available since version (51 << 16 | 59 << 8 | 100) */ AVClassCategory (*get_category)(void* ctx); /** * Callback to return the supported/allowed ranges. * available since version (52.12) */ int (*query_ranges)(struct AVOptionRanges **, void *obj, const char *key, int flags); } AVClass; /** * @addtogroup lavu_log * * @{ * * @defgroup lavu_log_constants Logging Constants * * @{ */ /** * Print no output. */ #define AV_LOG_QUIET -8 /** * Something went really wrong and we will crash now. */ #define AV_LOG_PANIC 0 /** * Something went wrong and recovery is not possible. * For example, no header was found for a format which depends * on headers or an illegal combination of parameters is used. */ #define AV_LOG_FATAL 8 /** * Something went wrong and cannot losslessly be recovered. * However, not all future data is affected. */ #define AV_LOG_ERROR 16 /** * Something somehow does not look correct. This may or may not * lead to problems. An example would be the use of '-vstrict -2'. */ #define AV_LOG_WARNING 24 /** * Standard information. */ #define AV_LOG_INFO 32 /** * Detailed information. */ #define AV_LOG_VERBOSE 40 /** * Stuff which is only useful for libav* developers. */ #define AV_LOG_DEBUG 48 #define AV_LOG_MAX_OFFSET (AV_LOG_DEBUG - AV_LOG_QUIET) /** * @} */ /** * Send the specified message to the log if the level is less than or equal * to the current av_log_level. By default, all logging messages are sent to * stderr. This behavior can be altered by setting a different logging callback * function. * @see av_log_set_callback * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message expressed using a @ref * lavu_log_constants "Logging Constant". * @param fmt The format string (printf-compatible) that specifies how * subsequent arguments are converted to output. */ void av_log(void *avcl, int level, const char *fmt, ...) av_printf_format(3, 4); /** * Send the specified message to the log if the level is less than or equal * to the current av_log_level. By default, all logging messages are sent to * stderr. This behavior can be altered by setting a different logging callback * function. * @see av_log_set_callback * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message expressed using a @ref * lavu_log_constants "Logging Constant". * @param fmt The format string (printf-compatible) that specifies how * subsequent arguments are converted to output. * @param vl The arguments referenced by the format string. */ void av_vlog(void *avcl, int level, const char *fmt, va_list vl); /** * Get the current log level * * @see lavu_log_constants * * @return Current log level */ int av_log_get_level(void); /** * Set the log level * * @see lavu_log_constants * * @param level Logging level */ void av_log_set_level(int level); /** * Set the logging callback * * @note The callback must be thread safe, even if the application does not use * threads itself as some codecs are multithreaded. * * @see av_log_default_callback * * @param callback A logging function with a compatible signature. */ void av_log_set_callback(void (*callback)(void*, int, const char*, va_list)); /** * Default logging callback * * It prints the message to stderr, optionally colorizing it. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message expressed using a @ref * lavu_log_constants "Logging Constant". * @param fmt The format string (printf-compatible) that specifies how * subsequent arguments are converted to output. * @param vl The arguments referenced by the format string. */ void av_log_default_callback(void *avcl, int level, const char *fmt, va_list vl); /** * Return the context name * * @param ctx The AVClass context * * @return The AVClass class_name */ const char* av_default_item_name(void* ctx); AVClassCategory av_default_get_category(void *ptr); /** * Format a line of log the same way as the default callback. * @param line buffer to receive the formated line * @param line_size size of the buffer * @param print_prefix used to store whether the prefix must be printed; * must point to a persistent integer initially set to 1 */ void av_log_format_line(void *ptr, int level, const char *fmt, va_list vl, char *line, int line_size, int *print_prefix); /** * av_dlog macros * Useful to print debug messages that shouldn't get compiled in normally. */ #ifdef DEBUG # define av_dlog(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__) #else # define av_dlog(pctx, ...) do { if (0) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__); } while (0) #endif /** * Skip repeated messages, this requires the user app to use av_log() instead of * (f)printf as the 2 would otherwise interfere and lead to * "Last message repeated x times" messages below (f)printf messages with some * bad luck. * Also to receive the last, "last repeated" line if any, the user app must * call av_log(NULL, AV_LOG_QUIET, "%s", ""); at the end */ #define AV_LOG_SKIP_REPEATED 1 void av_log_set_flags(int arg); /** * @} */ #endif /* AVUTIL_LOG_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/lzo.h ================================================ /* * LZO 1x decompression * copyright (c) 2006 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LZO_H #define AVUTIL_LZO_H /** * @defgroup lavu_lzo LZO * @ingroup lavu_crypto * * @{ */ #include /** @name Error flags returned by av_lzo1x_decode * @{ */ /// end of the input buffer reached before decoding finished #define AV_LZO_INPUT_DEPLETED 1 /// decoded data did not fit into output buffer #define AV_LZO_OUTPUT_FULL 2 /// a reference to previously decoded data was wrong #define AV_LZO_INVALID_BACKPTR 4 /// a non-specific error in the compressed bitstream #define AV_LZO_ERROR 8 /** @} */ #define AV_LZO_INPUT_PADDING 8 #define AV_LZO_OUTPUT_PADDING 12 /** * @brief Decodes LZO 1x compressed data. * @param out output buffer * @param outlen size of output buffer, number of bytes left are returned here * @param in input buffer * @param inlen size of input buffer, number of bytes left are returned here * @return 0 on success, otherwise a combination of the error flags above * * Make sure all buffers are appropriately padded, in must provide * AV_LZO_INPUT_PADDING, out must provide AV_LZO_OUTPUT_PADDING additional bytes. */ int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen); /** * @} */ #endif /* AVUTIL_LZO_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/macros.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu * Utility Preprocessor macros */ #ifndef AVUTIL_MACROS_H #define AVUTIL_MACROS_H /** * @addtogroup preproc_misc Preprocessor String Macros * * String manipulation macros * * @{ */ #define AV_STRINGIFY(s) AV_TOSTRING(s) #define AV_TOSTRING(s) #s #define AV_GLUE(a, b) a ## b #define AV_JOIN(a, b) AV_GLUE(a, b) /** * @} */ #define AV_PRAGMA(s) _Pragma(#s) #endif /* AVUTIL_MACROS_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/mathematics.h ================================================ /* * copyright (c) 2005-2012 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_MATHEMATICS_H #define AVUTIL_MATHEMATICS_H #include #include #include "attributes.h" #include "rational.h" #include "intfloat.h" #ifndef M_E #define M_E 2.7182818284590452354 /* e */ #endif #ifndef M_LN2 #define M_LN2 0.69314718055994530942 /* log_e 2 */ #endif #ifndef M_LN10 #define M_LN10 2.30258509299404568402 /* log_e 10 */ #endif #ifndef M_LOG2_10 #define M_LOG2_10 3.32192809488736234787 /* log_2 10 */ #endif #ifndef M_PHI #define M_PHI 1.61803398874989484820 /* phi / golden ratio */ #endif #ifndef M_PI #define M_PI 3.14159265358979323846 /* pi */ #endif #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 /* pi/2 */ #endif #ifndef M_SQRT1_2 #define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */ #endif #ifndef M_SQRT2 #define M_SQRT2 1.41421356237309504880 /* sqrt(2) */ #endif #ifndef NAN #define NAN av_int2float(0x7fc00000) #endif #ifndef INFINITY #define INFINITY av_int2float(0x7f800000) #endif /** * @addtogroup lavu_math * @{ */ enum AVRounding { AV_ROUND_ZERO = 0, ///< Round toward zero. AV_ROUND_INF = 1, ///< Round away from zero. AV_ROUND_DOWN = 2, ///< Round toward -infinity. AV_ROUND_UP = 3, ///< Round toward +infinity. AV_ROUND_NEAR_INF = 5, ///< Round to nearest and halfway cases away from zero. AV_ROUND_PASS_MINMAX = 8192, ///< Flag to pass INT64_MIN/MAX through instead of rescaling, this avoids special cases for AV_NOPTS_VALUE }; /** * Return the greatest common divisor of a and b. * If both a and b are 0 or either or both are <0 then behavior is * undefined. */ int64_t av_const av_gcd(int64_t a, int64_t b); /** * Rescale a 64-bit integer with rounding to nearest. * A simple a*b/c isn't possible as it can overflow. */ int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const; /** * Rescale a 64-bit integer with specified rounding. * A simple a*b/c isn't possible as it can overflow. * * @return rescaled value a, or if AV_ROUND_PASS_MINMAX is set and a is * INT64_MIN or INT64_MAX then a is passed through unchanged. */ int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding) av_const; /** * Rescale a 64-bit integer by 2 rational numbers. */ int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const; /** * Rescale a 64-bit integer by 2 rational numbers with specified rounding. * * @return rescaled value a, or if AV_ROUND_PASS_MINMAX is set and a is * INT64_MIN or INT64_MAX then a is passed through unchanged. */ int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding) av_const; /** * Compare 2 timestamps each in its own timebases. * The result of the function is undefined if one of the timestamps * is outside the int64_t range when represented in the others timebase. * @return -1 if ts_a is before ts_b, 1 if ts_a is after ts_b or 0 if they represent the same position */ int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b); /** * Compare 2 integers modulo mod. * That is we compare integers a and b for which only the least * significant log2(mod) bits are known. * * @param mod must be a power of 2 * @return a negative value if a is smaller than b * a positive value if a is greater than b * 0 if a equals b */ int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod); /** * Rescale a timestamp while preserving known durations. * * @param in_ts Input timestamp * @param in_tb Input timebase * @param fs_tb Duration and *last timebase * @param duration duration till the next call * @param out_tb Output timebase */ int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb); /** * Add a value to a timestamp. * * This function gurantees that when the same value is repeatly added that * no accumulation of rounding errors occurs. * * @param ts Input timestamp * @param ts_tb Input timestamp timebase * @param inc value to add to ts * @param inc_tb inc timebase */ int64_t av_add_stable(AVRational ts_tb, int64_t ts, AVRational inc_tb, int64_t inc); /** * @} */ #endif /* AVUTIL_MATHEMATICS_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/md5.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_MD5_H #define AVUTIL_MD5_H #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_md5 MD5 * @ingroup lavu_crypto * @{ */ extern const int av_md5_size; struct AVMD5; /** * Allocate an AVMD5 context. */ struct AVMD5 *av_md5_alloc(void); /** * Initialize MD5 hashing. * * @param ctx pointer to the function context (of size av_md5_size) */ void av_md5_init(struct AVMD5 *ctx); /** * Update hash value. * * @param ctx hash function context * @param src input data to update hash with * @param len input data length */ void av_md5_update(struct AVMD5 *ctx, const uint8_t *src, int len); /** * Finish hashing and output digest value. * * @param ctx hash function context * @param dst buffer where output digest value is stored */ void av_md5_final(struct AVMD5 *ctx, uint8_t *dst); /** * Hash an array of data. * * @param dst The output buffer to write the digest into * @param src The data to hash * @param len The length of the data, in bytes */ void av_md5_sum(uint8_t *dst, const uint8_t *src, const int len); /** * @} */ #endif /* AVUTIL_MD5_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/mem.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * memory handling functions */ #ifndef AVUTIL_MEM_H #define AVUTIL_MEM_H #include #include #include "attributes.h" #include "error.h" #include "avutil.h" /** * @addtogroup lavu_mem * @{ */ #if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1110 || defined(__SUNPRO_C) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) const t __attribute__ ((aligned (n))) v #elif defined(__TI_COMPILER_VERSION__) #define DECLARE_ALIGNED(n,t,v) \ AV_PRAGMA(DATA_ALIGN(v,n)) \ t __attribute__((aligned(n))) v #define DECLARE_ASM_CONST(n,t,v) \ AV_PRAGMA(DATA_ALIGN(v,n)) \ static const t __attribute__((aligned(n))) v #elif defined(__GNUC__) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (n))) v #elif defined(_MSC_VER) #define DECLARE_ALIGNED(n,t,v) __declspec(align(n)) t v #define DECLARE_ASM_CONST(n,t,v) __declspec(align(n)) static const t v #else #define DECLARE_ALIGNED(n,t,v) t v #define DECLARE_ASM_CONST(n,t,v) static const t v #endif #if AV_GCC_VERSION_AT_LEAST(3,1) #define av_malloc_attrib __attribute__((__malloc__)) #else #define av_malloc_attrib #endif #if AV_GCC_VERSION_AT_LEAST(4,3) #define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__))) #else #define av_alloc_size(...) #endif /** * Allocate a block of size bytes with alignment suitable for all * memory accesses (including vectors if available on the CPU). * @param size Size in bytes for the memory block to be allocated. * @return Pointer to the allocated block, NULL if the block cannot * be allocated. * @see av_mallocz() */ void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1); /** * Allocate a block of size * nmemb bytes with av_malloc(). * @param nmemb Number of elements * @param size Size of the single element * @return Pointer to the allocated block, NULL if the block cannot * be allocated. * @see av_malloc() */ av_alloc_size(1, 2) static inline void *av_malloc_array(size_t nmemb, size_t size) { if (!size || nmemb >= INT_MAX / size) return NULL; return av_malloc(nmemb * size); } /** * Allocate or reallocate a block of memory. * If ptr is NULL and size > 0, allocate a new block. If * size is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a memory block already allocated with * av_realloc() or NULL. * @param size Size in bytes of the memory block to be allocated or * reallocated. * @return Pointer to a newly-reallocated block or NULL if the block * cannot be reallocated or the function is used to free the memory block. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_realloc(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. * @see av_fast_realloc() */ void *av_realloc(void *ptr, size_t size) av_alloc_size(2); /** * Allocate or reallocate a block of memory. * This function does the same thing as av_realloc, except: * - It takes two arguments and checks the result of the multiplication for * integer overflow. * - It frees the input block in case of failure, thus avoiding the memory * leak with the classic "buf = realloc(buf); if (!buf) return -1;". */ void *av_realloc_f(void *ptr, size_t nelem, size_t elsize); /** * Allocate or reallocate a block of memory. * If *ptr is NULL and size > 0, allocate a new block. If * size is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a pointer to a memory block already allocated * with av_realloc(), or pointer to a pointer to NULL. * The pointer is updated on success, or freed on failure. * @param size Size in bytes for the memory block to be allocated or * reallocated * @return Zero on success, an AVERROR error code on failure. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_reallocp(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. */ int av_reallocp(void *ptr, size_t size); /** * Allocate or reallocate an array. * If ptr is NULL and nmemb > 0, allocate a new block. If * nmemb is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a memory block already allocated with * av_realloc() or NULL. * @param nmemb Number of elements * @param size Size of the single element * @return Pointer to a newly-reallocated block or NULL if the block * cannot be reallocated or the function is used to free the memory block. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_realloc(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. */ av_alloc_size(2, 3) void *av_realloc_array(void *ptr, size_t nmemb, size_t size); /** * Allocate or reallocate an array through a pointer to a pointer. * If *ptr is NULL and nmemb > 0, allocate a new block. If * nmemb is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a pointer to a memory block already allocated * with av_realloc(), or pointer to a pointer to NULL. * The pointer is updated on success, or freed on failure. * @param nmemb Number of elements * @param size Size of the single element * @return Zero on success, an AVERROR error code on failure. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_realloc(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. */ av_alloc_size(2, 3) int av_reallocp_array(void *ptr, size_t nmemb, size_t size); /** * Free a memory block which has been allocated with av_malloc(z)() or * av_realloc(). * @param ptr Pointer to the memory block which should be freed. * @note ptr = NULL is explicitly allowed. * @note It is recommended that you use av_freep() instead. * @see av_freep() */ void av_free(void *ptr); /** * Allocate a block of size bytes with alignment suitable for all * memory accesses (including vectors if available on the CPU) and * zero all the bytes of the block. * @param size Size in bytes for the memory block to be allocated. * @return Pointer to the allocated block, NULL if it cannot be allocated. * @see av_malloc() */ void *av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1); /** * Allocate a block of nmemb * size bytes with alignment suitable for all * memory accesses (including vectors if available on the CPU) and * zero all the bytes of the block. * The allocation will fail if nmemb * size is greater than or equal * to INT_MAX. * @param nmemb * @param size * @return Pointer to the allocated block, NULL if it cannot be allocated. */ void *av_calloc(size_t nmemb, size_t size) av_malloc_attrib; /** * Allocate a block of size * nmemb bytes with av_mallocz(). * @param nmemb Number of elements * @param size Size of the single element * @return Pointer to the allocated block, NULL if the block cannot * be allocated. * @see av_mallocz() * @see av_malloc_array() */ av_alloc_size(1, 2) static inline void *av_mallocz_array(size_t nmemb, size_t size) { if (!size || nmemb >= INT_MAX / size) return NULL; return av_mallocz(nmemb * size); } /** * Duplicate the string s. * @param s string to be duplicated * @return Pointer to a newly-allocated string containing a * copy of s or NULL if the string cannot be allocated. */ char *av_strdup(const char *s) av_malloc_attrib; /** * Duplicate the buffer p. * @param p buffer to be duplicated * @return Pointer to a newly allocated buffer containing a * copy of p or NULL if the buffer cannot be allocated. */ void *av_memdup(const void *p, size_t size); /** * Free a memory block which has been allocated with av_malloc(z)() or * av_realloc() and set the pointer pointing to it to NULL. * @param ptr Pointer to the pointer to the memory block which should * be freed. * @see av_free() */ void av_freep(void *ptr); /** * Add an element to a dynamic array. * * The array to grow is supposed to be an array of pointers to * structures, and the element to add must be a pointer to an already * allocated structure. * * The array is reallocated when its size reaches powers of 2. * Therefore, the amortized cost of adding an element is constant. * * In case of success, the pointer to the array is updated in order to * point to the new grown array, and the number pointed to by nb_ptr * is incremented. * In case of failure, the array is freed, *tab_ptr is set to NULL and * *nb_ptr is set to 0. * * @param tab_ptr pointer to the array to grow * @param nb_ptr pointer to the number of elements in the array * @param elem element to add * @see av_dynarray2_add() */ void av_dynarray_add(void *tab_ptr, int *nb_ptr, void *elem); /** * Add an element of size elem_size to a dynamic array. * * The array is reallocated when its number of elements reaches powers of 2. * Therefore, the amortized cost of adding an element is constant. * * In case of success, the pointer to the array is updated in order to * point to the new grown array, and the number pointed to by nb_ptr * is incremented. * In case of failure, the array is freed, *tab_ptr is set to NULL and * *nb_ptr is set to 0. * * @param tab_ptr pointer to the array to grow * @param nb_ptr pointer to the number of elements in the array * @param elem_size size in bytes of the elements in the array * @param elem_data pointer to the data of the element to add. If NULL, the space of * the new added element is not filled. * @return pointer to the data of the element to copy in the new allocated space. * If NULL, the new allocated space is left uninitialized." * @see av_dynarray_add() */ void *av_dynarray2_add(void **tab_ptr, int *nb_ptr, size_t elem_size, const uint8_t *elem_data); /** * Multiply two size_t values checking for overflow. * @return 0 if success, AVERROR(EINVAL) if overflow. */ static inline int av_size_mult(size_t a, size_t b, size_t *r) { size_t t = a * b; /* Hack inspired from glibc: only try the division if nelem and elsize * are both greater than sqrt(SIZE_MAX). */ if ((a | b) >= ((size_t)1 << (sizeof(size_t) * 4)) && a && t / a != b) return AVERROR(EINVAL); *r = t; return 0; } /** * Set the maximum size that may me allocated in one block. */ void av_max_alloc(size_t max); /** * deliberately overlapping memcpy implementation * @param dst destination buffer * @param back how many bytes back we start (the initial size of the overlapping window), must be > 0 * @param cnt number of bytes to copy, must be >= 0 * * cnt > back is valid, this will copy the bytes we just copied, * thus creating a repeating pattern with a period length of back. */ void av_memcpy_backptr(uint8_t *dst, int back, int cnt); /** * Reallocate the given block if it is not large enough, otherwise do nothing. * * @see av_realloc */ void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size); /** * Allocate a buffer, reusing the given one if large enough. * * Contrary to av_fast_realloc the current buffer contents might not be * preserved and on error the old buffer is freed, thus no special * handling to avoid memleaks is necessary. * * @param ptr pointer to pointer to already allocated buffer, overwritten with pointer to new buffer * @param size size of the buffer *ptr points to * @param min_size minimum size of *ptr buffer after returning, *ptr will be NULL and * *size 0 if an error occurred. */ void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size); /** * @} */ #endif /* AVUTIL_MEM_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/murmur3.h ================================================ /* * Copyright (C) 2013 Reimar Döffinger * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_MURMUR3_H #define AVUTIL_MURMUR3_H #include struct AVMurMur3 *av_murmur3_alloc(void); void av_murmur3_init_seeded(struct AVMurMur3 *c, uint64_t seed); void av_murmur3_init(struct AVMurMur3 *c); void av_murmur3_update(struct AVMurMur3 *c, const uint8_t *src, int len); void av_murmur3_final(struct AVMurMur3 *c, uint8_t dst[16]); #endif /* AVUTIL_MURMUR3_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/old_pix_fmts.h ================================================ /* * copyright (c) 2006-2012 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_OLD_PIX_FMTS_H #define AVUTIL_OLD_PIX_FMTS_H /* * This header exists to prevent new pixel formats from being accidentally added * to the deprecated list. * Do not include it directly. It will be removed on next major bump * * Do not add new items to this list. Use the AVPixelFormat enum instead. */ PIX_FMT_NONE = AV_PIX_FMT_NONE, PIX_FMT_YUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples) PIX_FMT_YUYV422, ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr PIX_FMT_RGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB... PIX_FMT_BGR24, ///< packed RGB 8:8:8, 24bpp, BGRBGR... PIX_FMT_YUV422P, ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) PIX_FMT_YUV444P, ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples) PIX_FMT_YUV410P, ///< planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples) PIX_FMT_YUV411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) PIX_FMT_GRAY8, ///< Y , 8bpp PIX_FMT_MONOWHITE, ///< Y , 1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb PIX_FMT_MONOBLACK, ///< Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb PIX_FMT_PAL8, ///< 8 bit with PIX_FMT_RGB32 palette PIX_FMT_YUVJ420P, ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV420P and setting color_range PIX_FMT_YUVJ422P, ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV422P and setting color_range PIX_FMT_YUVJ444P, ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV444P and setting color_range #if FF_API_XVMC PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing PIX_FMT_XVMC_MPEG2_IDCT, #endif /* FF_API_XVMC */ PIX_FMT_UYVY422, ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1 PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3 PIX_FMT_BGR8, ///< packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb) PIX_FMT_BGR4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb) PIX_FMT_RGB8, ///< packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb) PIX_FMT_RGB4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb) PIX_FMT_NV12, ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) PIX_FMT_NV21, ///< as above, but U and V bytes are swapped PIX_FMT_ARGB, ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB... PIX_FMT_RGBA, ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA... PIX_FMT_ABGR, ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR... PIX_FMT_BGRA, ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA... PIX_FMT_GRAY16BE, ///< Y , 16bpp, big-endian PIX_FMT_GRAY16LE, ///< Y , 16bpp, little-endian PIX_FMT_YUV440P, ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples) PIX_FMT_YUVJ440P, ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of PIX_FMT_YUV440P and setting color_range PIX_FMT_YUVA420P, ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples) #if FF_API_VDPAU PIX_FMT_VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers #endif PIX_FMT_RGB48BE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian PIX_FMT_RGB48LE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian PIX_FMT_RGB565BE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian PIX_FMT_RGB565LE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian PIX_FMT_RGB555BE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0 PIX_FMT_RGB555LE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0 PIX_FMT_BGR565BE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), big-endian PIX_FMT_BGR565LE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), little-endian PIX_FMT_BGR555BE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1 PIX_FMT_BGR555LE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1 PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers PIX_FMT_VAAPI_VLD, ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_YUV420P16LE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian PIX_FMT_YUV420P16BE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian PIX_FMT_YUV422P16LE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian PIX_FMT_YUV422P16BE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian PIX_FMT_YUV444P16LE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian PIX_FMT_YUV444P16BE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian #if FF_API_VDPAU PIX_FMT_VDPAU_MPEG4, ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers #endif PIX_FMT_DXVA2_VLD, ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer PIX_FMT_RGB444LE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0 PIX_FMT_RGB444BE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0 PIX_FMT_BGR444LE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1 PIX_FMT_BGR444BE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1 PIX_FMT_GRAY8A, ///< 8bit gray, 8bit alpha PIX_FMT_BGR48BE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian PIX_FMT_BGR48LE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian //the following 10 formats have the disadvantage of needing 1 format for each bit depth, thus //If you want to support multiple bit depths, then using PIX_FMT_YUV420P16* with the bpp stored separately //is better PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian PIX_FMT_VDA_VLD, ///< hardware decoding through VDA #ifdef AV_PIX_FMT_ABI_GIT_MASTER PIX_FMT_RGBA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_RGBA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian PIX_FMT_BGRA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_BGRA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian #endif PIX_FMT_GBRP, ///< planar GBR 4:4:4 24bpp PIX_FMT_GBRP9BE, ///< planar GBR 4:4:4 27bpp, big endian PIX_FMT_GBRP9LE, ///< planar GBR 4:4:4 27bpp, little endian PIX_FMT_GBRP10BE, ///< planar GBR 4:4:4 30bpp, big endian PIX_FMT_GBRP10LE, ///< planar GBR 4:4:4 30bpp, little endian PIX_FMT_GBRP16BE, ///< planar GBR 4:4:4 48bpp, big endian PIX_FMT_GBRP16LE, ///< planar GBR 4:4:4 48bpp, little endian #ifndef AV_PIX_FMT_ABI_GIT_MASTER PIX_FMT_RGBA64BE=0x123, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_RGBA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian PIX_FMT_BGRA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_BGRA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian #endif PIX_FMT_0RGB=0x123+4, ///< packed RGB 8:8:8, 32bpp, 0RGB0RGB... PIX_FMT_RGB0, ///< packed RGB 8:8:8, 32bpp, RGB0RGB0... PIX_FMT_0BGR, ///< packed BGR 8:8:8, 32bpp, 0BGR0BGR... PIX_FMT_BGR0, ///< packed BGR 8:8:8, 32bpp, BGR0BGR0... PIX_FMT_YUVA444P, ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples) PIX_FMT_YUVA422P, ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples) PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian PIX_FMT_GBRP12BE, ///< planar GBR 4:4:4 36bpp, big endian PIX_FMT_GBRP12LE, ///< planar GBR 4:4:4 36bpp, little endian PIX_FMT_GBRP14BE, ///< planar GBR 4:4:4 42bpp, big endian PIX_FMT_GBRP14LE, ///< planar GBR 4:4:4 42bpp, little endian PIX_FMT_NB, ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions #endif /* AVUTIL_OLD_PIX_FMTS_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/opt.h ================================================ /* * AVOptions * copyright (c) 2005 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_OPT_H #define AVUTIL_OPT_H /** * @file * AVOptions */ #include "rational.h" #include "avutil.h" #include "dict.h" #include "log.h" #include "pixfmt.h" #include "samplefmt.h" /** * @defgroup avoptions AVOptions * @ingroup lavu_data * @{ * AVOptions provide a generic system to declare options on arbitrary structs * ("objects"). An option can have a help text, a type and a range of possible * values. Options may then be enumerated, read and written to. * * @section avoptions_implement Implementing AVOptions * This section describes how to add AVOptions capabilities to a struct. * * All AVOptions-related information is stored in an AVClass. Therefore * the first member of the struct should be a pointer to an AVClass describing it. * The option field of the AVClass must be set to a NULL-terminated static array * of AVOptions. Each AVOption must have a non-empty name, a type, a default * value and for number-type AVOptions also a range of allowed values. It must * also declare an offset in bytes from the start of the struct, where the field * associated with this AVOption is located. Other fields in the AVOption struct * should also be set when applicable, but are not required. * * The following example illustrates an AVOptions-enabled struct: * @code * typedef struct test_struct { * AVClass *class; * int int_opt; * char *str_opt; * uint8_t *bin_opt; * int bin_len; * } test_struct; * * static const AVOption test_options[] = { * { "test_int", "This is a test option of int type.", offsetof(test_struct, int_opt), * AV_OPT_TYPE_INT, { .i64 = -1 }, INT_MIN, INT_MAX }, * { "test_str", "This is a test option of string type.", offsetof(test_struct, str_opt), * AV_OPT_TYPE_STRING }, * { "test_bin", "This is a test option of binary type.", offsetof(test_struct, bin_opt), * AV_OPT_TYPE_BINARY }, * { NULL }, * }; * * static const AVClass test_class = { * .class_name = "test class", * .item_name = av_default_item_name, * .option = test_options, * .version = LIBAVUTIL_VERSION_INT, * }; * @endcode * * Next, when allocating your struct, you must ensure that the AVClass pointer * is set to the correct value. Then, av_opt_set_defaults() can be called to * initialize defaults. After that the struct is ready to be used with the * AVOptions API. * * When cleaning up, you may use the av_opt_free() function to automatically * free all the allocated string and binary options. * * Continuing with the above example: * * @code * test_struct *alloc_test_struct(void) * { * test_struct *ret = av_malloc(sizeof(*ret)); * ret->class = &test_class; * av_opt_set_defaults(ret); * return ret; * } * void free_test_struct(test_struct **foo) * { * av_opt_free(*foo); * av_freep(foo); * } * @endcode * * @subsection avoptions_implement_nesting Nesting * It may happen that an AVOptions-enabled struct contains another * AVOptions-enabled struct as a member (e.g. AVCodecContext in * libavcodec exports generic options, while its priv_data field exports * codec-specific options). In such a case, it is possible to set up the * parent struct to export a child's options. To do that, simply * implement AVClass.child_next() and AVClass.child_class_next() in the * parent struct's AVClass. * Assuming that the test_struct from above now also contains a * child_struct field: * * @code * typedef struct child_struct { * AVClass *class; * int flags_opt; * } child_struct; * static const AVOption child_opts[] = { * { "test_flags", "This is a test option of flags type.", * offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX }, * { NULL }, * }; * static const AVClass child_class = { * .class_name = "child class", * .item_name = av_default_item_name, * .option = child_opts, * .version = LIBAVUTIL_VERSION_INT, * }; * * void *child_next(void *obj, void *prev) * { * test_struct *t = obj; * if (!prev && t->child_struct) * return t->child_struct; * return NULL * } * const AVClass child_class_next(const AVClass *prev) * { * return prev ? NULL : &child_class; * } * @endcode * Putting child_next() and child_class_next() as defined above into * test_class will now make child_struct's options accessible through * test_struct (again, proper setup as described above needs to be done on * child_struct right after it is created). * * From the above example it might not be clear why both child_next() * and child_class_next() are needed. The distinction is that child_next() * iterates over actually existing objects, while child_class_next() * iterates over all possible child classes. E.g. if an AVCodecContext * was initialized to use a codec which has private options, then its * child_next() will return AVCodecContext.priv_data and finish * iterating. OTOH child_class_next() on AVCodecContext.av_class will * iterate over all available codecs with private options. * * @subsection avoptions_implement_named_constants Named constants * It is possible to create named constants for options. Simply set the unit * field of the option the constants should apply to a string and * create the constants themselves as options of type AV_OPT_TYPE_CONST * with their unit field set to the same string. * Their default_val field should contain the value of the named * constant. * For example, to add some named constants for the test_flags option * above, put the following into the child_opts array: * @code * { "test_flags", "This is a test option of flags type.", * offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX, "test_unit" }, * { "flag1", "This is a flag with value 16", 0, AV_OPT_TYPE_CONST, { .i64 = 16 }, 0, 0, "test_unit" }, * @endcode * * @section avoptions_use Using AVOptions * This section deals with accessing options in an AVOptions-enabled struct. * Such structs in FFmpeg are e.g. AVCodecContext in libavcodec or * AVFormatContext in libavformat. * * @subsection avoptions_use_examine Examining AVOptions * The basic functions for examining options are av_opt_next(), which iterates * over all options defined for one object, and av_opt_find(), which searches * for an option with the given name. * * The situation is more complicated with nesting. An AVOptions-enabled struct * may have AVOptions-enabled children. Passing the AV_OPT_SEARCH_CHILDREN flag * to av_opt_find() will make the function search children recursively. * * For enumerating there are basically two cases. The first is when you want to * get all options that may potentially exist on the struct and its children * (e.g. when constructing documentation). In that case you should call * av_opt_child_class_next() recursively on the parent struct's AVClass. The * second case is when you have an already initialized struct with all its * children and you want to get all options that can be actually written or read * from it. In that case you should call av_opt_child_next() recursively (and * av_opt_next() on each result). * * @subsection avoptions_use_get_set Reading and writing AVOptions * When setting options, you often have a string read directly from the * user. In such a case, simply passing it to av_opt_set() is enough. For * non-string type options, av_opt_set() will parse the string according to the * option type. * * Similarly av_opt_get() will read any option type and convert it to a string * which will be returned. Do not forget that the string is allocated, so you * have to free it with av_free(). * * In some cases it may be more convenient to put all options into an * AVDictionary and call av_opt_set_dict() on it. A specific case of this * are the format/codec open functions in lavf/lavc which take a dictionary * filled with option as a parameter. This allows to set some options * that cannot be set otherwise, since e.g. the input file format is not known * before the file is actually opened. */ enum AVOptionType{ AV_OPT_TYPE_FLAGS, AV_OPT_TYPE_INT, AV_OPT_TYPE_INT64, AV_OPT_TYPE_DOUBLE, AV_OPT_TYPE_FLOAT, AV_OPT_TYPE_STRING, AV_OPT_TYPE_RATIONAL, AV_OPT_TYPE_BINARY, ///< offset must point to a pointer immediately followed by an int for the length AV_OPT_TYPE_CONST = 128, AV_OPT_TYPE_IMAGE_SIZE = MKBETAG('S','I','Z','E'), ///< offset must point to two consecutive integers AV_OPT_TYPE_PIXEL_FMT = MKBETAG('P','F','M','T'), AV_OPT_TYPE_SAMPLE_FMT = MKBETAG('S','F','M','T'), AV_OPT_TYPE_VIDEO_RATE = MKBETAG('V','R','A','T'), ///< offset must point to AVRational AV_OPT_TYPE_DURATION = MKBETAG('D','U','R',' '), AV_OPT_TYPE_COLOR = MKBETAG('C','O','L','R'), AV_OPT_TYPE_CHANNEL_LAYOUT = MKBETAG('C','H','L','A'), #if FF_API_OLD_AVOPTIONS FF_OPT_TYPE_FLAGS = 0, FF_OPT_TYPE_INT, FF_OPT_TYPE_INT64, FF_OPT_TYPE_DOUBLE, FF_OPT_TYPE_FLOAT, FF_OPT_TYPE_STRING, FF_OPT_TYPE_RATIONAL, FF_OPT_TYPE_BINARY, ///< offset must point to a pointer immediately followed by an int for the length FF_OPT_TYPE_CONST=128, #endif }; /** * AVOption */ typedef struct AVOption { const char *name; /** * short English help text * @todo What about other languages? */ const char *help; /** * The offset relative to the context structure where the option * value is stored. It should be 0 for named constants. */ int offset; enum AVOptionType type; /** * the default value for scalar options */ union { int64_t i64; double dbl; const char *str; /* TODO those are unused now */ AVRational q; } default_val; double min; ///< minimum valid value for the option double max; ///< maximum valid value for the option int flags; #define AV_OPT_FLAG_ENCODING_PARAM 1 ///< a generic parameter which can be set by the user for muxing or encoding #define AV_OPT_FLAG_DECODING_PARAM 2 ///< a generic parameter which can be set by the user for demuxing or decoding #if FF_API_OPT_TYPE_METADATA #define AV_OPT_FLAG_METADATA 4 ///< some data extracted or inserted into the file like title, comment, ... #endif #define AV_OPT_FLAG_AUDIO_PARAM 8 #define AV_OPT_FLAG_VIDEO_PARAM 16 #define AV_OPT_FLAG_SUBTITLE_PARAM 32 /** * The option is inteded for exporting values to the caller. */ #define AV_OPT_FLAG_EXPORT 64 /** * The option may not be set through the AVOptions API, only read. * This flag only makes sense when AV_OPT_FLAG_EXPORT is also set. */ #define AV_OPT_FLAG_READONLY 128 #define AV_OPT_FLAG_FILTERING_PARAM (1<<16) ///< a generic parameter which can be set by the user for filtering //FIXME think about enc-audio, ... style flags /** * The logical unit to which the option belongs. Non-constant * options and corresponding named constants share the same * unit. May be NULL. */ const char *unit; } AVOption; /** * A single allowed range of values, or a single allowed value. */ typedef struct AVOptionRange { const char *str; double value_min, value_max; ///< For string ranges this represents the min/max length, for dimensions this represents the min/max pixel count double component_min, component_max; ///< For string this represents the unicode range for chars, 0-127 limits to ASCII int is_range; ///< if set to 1 the struct encodes a range, if set to 0 a single value } AVOptionRange; /** * List of AVOptionRange structs */ typedef struct AVOptionRanges { AVOptionRange **range; int nb_ranges; } AVOptionRanges; #if FF_API_FIND_OPT /** * Look for an option in obj. Look only for the options which * have the flags set as specified in mask and flags (that is, * for which it is the case that (opt->flags & mask) == flags). * * @param[in] obj a pointer to a struct whose first element is a * pointer to an AVClass * @param[in] name the name of the option to look for * @param[in] unit the unit of the option to look for, or any if NULL * @return a pointer to the option found, or NULL if no option * has been found * * @deprecated use av_opt_find. */ attribute_deprecated const AVOption *av_find_opt(void *obj, const char *name, const char *unit, int mask, int flags); #endif #if FF_API_OLD_AVOPTIONS /** * Set the field of obj with the given name to value. * * @param[in] obj A struct whose first element is a pointer to an * AVClass. * @param[in] name the name of the field to set * @param[in] val The value to set. If the field is not of a string * type, then the given string is parsed. * SI postfixes and some named scalars are supported. * If the field is of a numeric type, it has to be a numeric or named * scalar. Behavior with more than one scalar and +- infix operators * is undefined. * If the field is of a flags type, it has to be a sequence of numeric * scalars or named flags separated by '+' or '-'. Prefixing a flag * with '+' causes it to be set without affecting the other flags; * similarly, '-' unsets a flag. * @param[out] o_out if non-NULL put here a pointer to the AVOption * found * @param alloc this parameter is currently ignored * @return 0 if the value has been set, or an AVERROR code in case of * error: * AVERROR_OPTION_NOT_FOUND if no matching option exists * AVERROR(ERANGE) if the value is out of range * AVERROR(EINVAL) if the value is not valid * @deprecated use av_opt_set() */ attribute_deprecated int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out); attribute_deprecated const AVOption *av_set_double(void *obj, const char *name, double n); attribute_deprecated const AVOption *av_set_q(void *obj, const char *name, AVRational n); attribute_deprecated const AVOption *av_set_int(void *obj, const char *name, int64_t n); double av_get_double(void *obj, const char *name, const AVOption **o_out); AVRational av_get_q(void *obj, const char *name, const AVOption **o_out); int64_t av_get_int(void *obj, const char *name, const AVOption **o_out); attribute_deprecated const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len); attribute_deprecated const AVOption *av_next_option(void *obj, const AVOption *last); #endif /** * Show the obj options. * * @param req_flags requested flags for the options to show. Show only the * options for which it is opt->flags & req_flags. * @param rej_flags rejected flags for the options to show. Show only the * options for which it is !(opt->flags & req_flags). * @param av_log_obj log context to use for showing the options */ int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags); /** * Set the values of all AVOption fields to their default values. * * @param s an AVOption-enabled struct (its first member must be a pointer to AVClass) */ void av_opt_set_defaults(void *s); #if FF_API_OLD_AVOPTIONS attribute_deprecated void av_opt_set_defaults2(void *s, int mask, int flags); #endif /** * Parse the key/value pairs list in opts. For each key/value pair * found, stores the value in the field in ctx that is named like the * key. ctx must be an AVClass context, storing is done using * AVOptions. * * @param opts options string to parse, may be NULL * @param key_val_sep a 0-terminated list of characters used to * separate key from value * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other * @return the number of successfully set key/value pairs, or a negative * value corresponding to an AVERROR code in case of error: * AVERROR(EINVAL) if opts cannot be parsed, * the error code issued by av_set_string3() if a key/value pair * cannot be set */ int av_set_options_string(void *ctx, const char *opts, const char *key_val_sep, const char *pairs_sep); /** * Parse the key-value pairs list in opts. For each key=value pair found, * set the value of the corresponding option in ctx. * * @param ctx the AVClass object to set options on * @param opts the options string, key-value pairs separated by a * delimiter * @param shorthand a NULL-terminated array of options names for shorthand * notation: if the first field in opts has no key part, * the key is taken from the first element of shorthand; * then again for the second, etc., until either opts is * finished, shorthand is finished or a named option is * found; after that, all options must be named * @param key_val_sep a 0-terminated list of characters used to separate * key from value, for example '=' * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other, for example ':' or ',' * @return the number of successfully set key=value pairs, or a negative * value corresponding to an AVERROR code in case of error: * AVERROR(EINVAL) if opts cannot be parsed, * the error code issued by av_set_string3() if a key/value pair * cannot be set * * Options names must use only the following characters: a-z A-Z 0-9 - . / _ * Separators must use characters distinct from option names and from each * other. */ int av_opt_set_from_string(void *ctx, const char *opts, const char *const *shorthand, const char *key_val_sep, const char *pairs_sep); /** * Free all string and binary options in obj. */ void av_opt_free(void *obj); /** * Check whether a particular flag is set in a flags field. * * @param field_name the name of the flag field option * @param flag_name the name of the flag to check * @return non-zero if the flag is set, zero if the flag isn't set, * isn't of the right type, or the flags field doesn't exist. */ int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name); /** * Set all the options from a given dictionary on an object. * * @param obj a struct whose first element is a pointer to AVClass * @param options options to process. This dictionary will be freed and replaced * by a new one containing all options not found in obj. * Of course this new dictionary needs to be freed by caller * with av_dict_free(). * * @return 0 on success, a negative AVERROR if some option was found in obj, * but could not be set. * * @see av_dict_copy() */ int av_opt_set_dict(void *obj, struct AVDictionary **options); /** * Extract a key-value pair from the beginning of a string. * * @param ropts pointer to the options string, will be updated to * point to the rest of the string (one of the pairs_sep * or the final NUL) * @param key_val_sep a 0-terminated list of characters used to separate * key from value, for example '=' * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other, for example ':' or ',' * @param flags flags; see the AV_OPT_FLAG_* values below * @param rkey parsed key; must be freed using av_free() * @param rval parsed value; must be freed using av_free() * * @return >=0 for success, or a negative value corresponding to an * AVERROR code in case of error; in particular: * AVERROR(EINVAL) if no key is present * */ int av_opt_get_key_value(const char **ropts, const char *key_val_sep, const char *pairs_sep, unsigned flags, char **rkey, char **rval); enum { /** * Accept to parse a value without a key; the key will then be returned * as NULL. */ AV_OPT_FLAG_IMPLICIT_KEY = 1, }; /** * @defgroup opt_eval_funcs Evaluating option strings * @{ * This group of functions can be used to evaluate option strings * and get numbers out of them. They do the same thing as av_opt_set(), * except the result is written into the caller-supplied pointer. * * @param obj a struct whose first element is a pointer to AVClass. * @param o an option for which the string is to be evaluated. * @param val string to be evaluated. * @param *_out value of the string will be written here. * * @return 0 on success, a negative number on failure. */ int av_opt_eval_flags (void *obj, const AVOption *o, const char *val, int *flags_out); int av_opt_eval_int (void *obj, const AVOption *o, const char *val, int *int_out); int av_opt_eval_int64 (void *obj, const AVOption *o, const char *val, int64_t *int64_out); int av_opt_eval_float (void *obj, const AVOption *o, const char *val, float *float_out); int av_opt_eval_double(void *obj, const AVOption *o, const char *val, double *double_out); int av_opt_eval_q (void *obj, const AVOption *o, const char *val, AVRational *q_out); /** * @} */ #define AV_OPT_SEARCH_CHILDREN 0x0001 /**< Search in possible children of the given object first. */ /** * The obj passed to av_opt_find() is fake -- only a double pointer to AVClass * instead of a required pointer to a struct containing AVClass. This is * useful for searching for options without needing to allocate the corresponding * object. */ #define AV_OPT_SEARCH_FAKE_OBJ 0x0002 /** * Look for an option in an object. Consider only options which * have all the specified flags set. * * @param[in] obj A pointer to a struct whose first element is a * pointer to an AVClass. * Alternatively a double pointer to an AVClass, if * AV_OPT_SEARCH_FAKE_OBJ search flag is set. * @param[in] name The name of the option to look for. * @param[in] unit When searching for named constants, name of the unit * it belongs to. * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG). * @param search_flags A combination of AV_OPT_SEARCH_*. * * @return A pointer to the option found, or NULL if no option * was found. * * @note Options found with AV_OPT_SEARCH_CHILDREN flag may not be settable * directly with av_set_string3(). Use special calls which take an options * AVDictionary (e.g. avformat_open_input()) to set options found with this * flag. */ const AVOption *av_opt_find(void *obj, const char *name, const char *unit, int opt_flags, int search_flags); /** * Look for an option in an object. Consider only options which * have all the specified flags set. * * @param[in] obj A pointer to a struct whose first element is a * pointer to an AVClass. * Alternatively a double pointer to an AVClass, if * AV_OPT_SEARCH_FAKE_OBJ search flag is set. * @param[in] name The name of the option to look for. * @param[in] unit When searching for named constants, name of the unit * it belongs to. * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG). * @param search_flags A combination of AV_OPT_SEARCH_*. * @param[out] target_obj if non-NULL, an object to which the option belongs will be * written here. It may be different from obj if AV_OPT_SEARCH_CHILDREN is present * in search_flags. This parameter is ignored if search_flags contain * AV_OPT_SEARCH_FAKE_OBJ. * * @return A pointer to the option found, or NULL if no option * was found. */ const AVOption *av_opt_find2(void *obj, const char *name, const char *unit, int opt_flags, int search_flags, void **target_obj); /** * Iterate over all AVOptions belonging to obj. * * @param obj an AVOptions-enabled struct or a double pointer to an * AVClass describing it. * @param prev result of the previous call to av_opt_next() on this object * or NULL * @return next AVOption or NULL */ const AVOption *av_opt_next(void *obj, const AVOption *prev); /** * Iterate over AVOptions-enabled children of obj. * * @param prev result of a previous call to this function or NULL * @return next AVOptions-enabled child or NULL */ void *av_opt_child_next(void *obj, void *prev); /** * Iterate over potential AVOptions-enabled children of parent. * * @param prev result of a previous call to this function or NULL * @return AVClass corresponding to next potential child or NULL */ const AVClass *av_opt_child_class_next(const AVClass *parent, const AVClass *prev); /** * @defgroup opt_set_funcs Option setting functions * @{ * Those functions set the field of obj with the given name to value. * * @param[in] obj A struct whose first element is a pointer to an AVClass. * @param[in] name the name of the field to set * @param[in] val The value to set. In case of av_opt_set() if the field is not * of a string type, then the given string is parsed. * SI postfixes and some named scalars are supported. * If the field is of a numeric type, it has to be a numeric or named * scalar. Behavior with more than one scalar and +- infix operators * is undefined. * If the field is of a flags type, it has to be a sequence of numeric * scalars or named flags separated by '+' or '-'. Prefixing a flag * with '+' causes it to be set without affecting the other flags; * similarly, '-' unsets a flag. * @param search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN * is passed here, then the option may be set on a child of obj. * * @return 0 if the value has been set, or an AVERROR code in case of * error: * AVERROR_OPTION_NOT_FOUND if no matching option exists * AVERROR(ERANGE) if the value is out of range * AVERROR(EINVAL) if the value is not valid */ int av_opt_set (void *obj, const char *name, const char *val, int search_flags); int av_opt_set_int (void *obj, const char *name, int64_t val, int search_flags); int av_opt_set_double(void *obj, const char *name, double val, int search_flags); int av_opt_set_q (void *obj, const char *name, AVRational val, int search_flags); int av_opt_set_bin (void *obj, const char *name, const uint8_t *val, int size, int search_flags); int av_opt_set_image_size(void *obj, const char *name, int w, int h, int search_flags); int av_opt_set_pixel_fmt (void *obj, const char *name, enum AVPixelFormat fmt, int search_flags); int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags); int av_opt_set_video_rate(void *obj, const char *name, AVRational val, int search_flags); int av_opt_set_channel_layout(void *obj, const char *name, int64_t ch_layout, int search_flags); /** * Set a binary option to an integer list. * * @param obj AVClass object to set options on * @param name name of the binary option * @param val pointer to an integer list (must have the correct type with * regard to the contents of the list) * @param term list terminator (usually 0 or -1) * @param flags search flags */ #define av_opt_set_int_list(obj, name, val, term, flags) \ (av_int_list_length(val, term) > INT_MAX / sizeof(*(val)) ? \ AVERROR(EINVAL) : \ av_opt_set_bin(obj, name, (const uint8_t *)(val), \ av_int_list_length(val, term) * sizeof(*(val)), flags)) /** * @} */ /** * @defgroup opt_get_funcs Option getting functions * @{ * Those functions get a value of the option with the given name from an object. * * @param[in] obj a struct whose first element is a pointer to an AVClass. * @param[in] name name of the option to get. * @param[in] search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN * is passed here, then the option may be found in a child of obj. * @param[out] out_val value of the option will be written here * @return >=0 on success, a negative error code otherwise */ /** * @note the returned string will be av_malloc()ed and must be av_free()ed by the caller */ int av_opt_get (void *obj, const char *name, int search_flags, uint8_t **out_val); int av_opt_get_int (void *obj, const char *name, int search_flags, int64_t *out_val); int av_opt_get_double(void *obj, const char *name, int search_flags, double *out_val); int av_opt_get_q (void *obj, const char *name, int search_flags, AVRational *out_val); int av_opt_get_image_size(void *obj, const char *name, int search_flags, int *w_out, int *h_out); int av_opt_get_pixel_fmt (void *obj, const char *name, int search_flags, enum AVPixelFormat *out_fmt); int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt); int av_opt_get_video_rate(void *obj, const char *name, int search_flags, AVRational *out_val); int av_opt_get_channel_layout(void *obj, const char *name, int search_flags, int64_t *ch_layout); /** * @} */ /** * Gets a pointer to the requested field in a struct. * This function allows accessing a struct even when its fields are moved or * renamed since the application making the access has been compiled, * * @returns a pointer to the field, it can be cast to the correct type and read * or written to. */ void *av_opt_ptr(const AVClass *avclass, void *obj, const char *name); /** * Free an AVOptionRanges struct and set it to NULL. */ void av_opt_freep_ranges(AVOptionRanges **ranges); /** * Get a list of allowed ranges for the given option. * * The returned list may depend on other fields in obj like for example profile. * * @param flags is a bitmask of flags, undefined flags should not be set and should be ignored * AV_OPT_SEARCH_FAKE_OBJ indicates that the obj is a double pointer to a AVClass instead of a full instance * * The result must be freed with av_opt_freep_ranges. * * @return >= 0 on success, a negative errro code otherwise */ int av_opt_query_ranges(AVOptionRanges **, void *obj, const char *key, int flags); /** * Get a default list of allowed ranges for the given option. * * This list is constructed without using the AVClass.query_ranges() callback * and can be used as fallback from within the callback. * * @param flags is a bitmask of flags, undefined flags should not be set and should be ignored * AV_OPT_SEARCH_FAKE_OBJ indicates that the obj is a double pointer to a AVClass instead of a full instance * * The result must be freed with av_opt_free_ranges. * * @return >= 0 on success, a negative errro code otherwise */ int av_opt_query_ranges_default(AVOptionRanges **, void *obj, const char *key, int flags); /** * @} */ #endif /* AVUTIL_OPT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/parseutils.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PARSEUTILS_H #define AVUTIL_PARSEUTILS_H #include #include "rational.h" /** * @file * misc parsing utilities */ /** * Parse str and store the parsed ratio in q. * * Note that a ratio with infinite (1/0) or negative value is * considered valid, so you should check on the returned value if you * want to exclude those values. * * The undefined value can be expressed using the "0:0" string. * * @param[in,out] q pointer to the AVRational which will contain the ratio * @param[in] str the string to parse: it has to be a string in the format * num:den, a float number or an expression * @param[in] max the maximum allowed numerator and denominator * @param[in] log_offset log level offset which is applied to the log * level of log_ctx * @param[in] log_ctx parent logging context * @return >= 0 on success, a negative error code otherwise */ int av_parse_ratio(AVRational *q, const char *str, int max, int log_offset, void *log_ctx); #define av_parse_ratio_quiet(rate, str, max) \ av_parse_ratio(rate, str, max, AV_LOG_MAX_OFFSET, NULL) /** * Parse str and put in width_ptr and height_ptr the detected values. * * @param[in,out] width_ptr pointer to the variable which will contain the detected * width value * @param[in,out] height_ptr pointer to the variable which will contain the detected * height value * @param[in] str the string to parse: it has to be a string in the format * width x height or a valid video size abbreviation. * @return >= 0 on success, a negative error code otherwise */ int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str); /** * Parse str and store the detected values in *rate. * * @param[in,out] rate pointer to the AVRational which will contain the detected * frame rate * @param[in] str the string to parse: it has to be a string in the format * rate_num / rate_den, a float number or a valid video rate abbreviation * @return >= 0 on success, a negative error code otherwise */ int av_parse_video_rate(AVRational *rate, const char *str); /** * Put the RGBA values that correspond to color_string in rgba_color. * * @param color_string a string specifying a color. It can be the name of * a color (case insensitive match) or a [0x|#]RRGGBB[AA] sequence, * possibly followed by "@" and a string representing the alpha * component. * The alpha component may be a string composed by "0x" followed by an * hexadecimal number or a decimal number between 0.0 and 1.0, which * represents the opacity value (0x00/0.0 means completely transparent, * 0xff/1.0 completely opaque). * If the alpha component is not specified then 0xff is assumed. * The string "random" will result in a random color. * @param slen length of the initial part of color_string containing the * color. It can be set to -1 if color_string is a null terminated string * containing nothing else than the color. * @return >= 0 in case of success, a negative value in case of * failure (for example if color_string cannot be parsed). */ int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen, void *log_ctx); /** * Get the name of a color from the internal table of hard-coded named * colors. * * This function is meant to enumerate the color names recognized by * av_parse_color(). * * @param color_idx index of the requested color, starting from 0 * @param rgbp if not NULL, will point to a 3-elements array with the color value in RGB * @return the color name string or NULL if color_idx is not in the array */ const char *av_get_known_color_name(int color_idx, const uint8_t **rgb); /** * Parse timestr and return in *time a corresponding number of * microseconds. * * @param timeval puts here the number of microseconds corresponding * to the string in timestr. If the string represents a duration, it * is the number of microseconds contained in the time interval. If * the string is a date, is the number of microseconds since 1st of * January, 1970 up to the time of the parsed date. If timestr cannot * be successfully parsed, set *time to INT64_MIN. * @param timestr a string representing a date or a duration. * - If a date the syntax is: * @code * [{YYYY-MM-DD|YYYYMMDD}[T|t| ]]{{HH:MM:SS[.m...]]]}|{HHMMSS[.m...]]]}}[Z] * now * @endcode * If the value is "now" it takes the current time. * Time is local time unless Z is appended, in which case it is * interpreted as UTC. * If the year-month-day part is not specified it takes the current * year-month-day. * - If a duration the syntax is: * @code * [-][HH:]MM:SS[.m...] * [-]S+[.m...] * @endcode * @param duration flag which tells how to interpret timestr, if not * zero timestr is interpreted as a duration, otherwise as a date * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code otherwise */ int av_parse_time(int64_t *timeval, const char *timestr, int duration); /** * Parse the input string p according to the format string fmt and * store its results in the structure dt. * This implementation supports only a subset of the formats supported * by the standard strptime(). * * In particular it actually supports the parameters: * - %H: the hour as a decimal number, using a 24-hour clock, in the * range '00' through '23' * - %J: hours as a decimal number, in the range '0' through INT_MAX * - %M: the minute as a decimal number, using a 24-hour clock, in the * range '00' through '59' * - %S: the second as a decimal number, using a 24-hour clock, in the * range '00' through '59' * - %Y: the year as a decimal number, using the Gregorian calendar * - %m: the month as a decimal number, in the range '1' through '12' * - %d: the day of the month as a decimal number, in the range '1' * through '31' * - %%: a literal '%' * * @return a pointer to the first character not processed in this * function call, or NULL in case the function fails to match all of * the fmt string and therefore an error occurred */ char *av_small_strptime(const char *p, const char *fmt, struct tm *dt); /** * Attempt to find a specific tag in a URL. * * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. * Return 1 if found. */ int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info); /** * Convert the decomposed UTC time in tm to a time_t value. */ time_t av_timegm(struct tm *tm); #endif /* AVUTIL_PARSEUTILS_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/pixdesc.h ================================================ /* * pixel format descriptor * Copyright (c) 2009 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PIXDESC_H #define AVUTIL_PIXDESC_H #include #include "attributes.h" #include "pixfmt.h" typedef struct AVComponentDescriptor{ uint16_t plane :2; ///< which of the 4 planes contains the component /** * Number of elements between 2 horizontally consecutive pixels minus 1. * Elements are bits for bitstream formats, bytes otherwise. */ uint16_t step_minus1 :3; /** * Number of elements before the component of the first pixel plus 1. * Elements are bits for bitstream formats, bytes otherwise. */ uint16_t offset_plus1 :3; uint16_t shift :3; ///< number of least significant bits that must be shifted away to get the value uint16_t depth_minus1 :4; ///< number of bits in the component minus 1 }AVComponentDescriptor; /** * Descriptor that unambiguously describes how the bits of a pixel are * stored in the up to 4 data planes of an image. It also stores the * subsampling factors and number of components. * * @note This is separate of the colorspace (RGB, YCbCr, YPbPr, JPEG-style YUV * and all the YUV variants) AVPixFmtDescriptor just stores how values * are stored not what these values represent. */ typedef struct AVPixFmtDescriptor{ const char *name; uint8_t nb_components; ///< The number of components each pixel has, (1-4) /** * Amount to shift the luma width right to find the chroma width. * For YV12 this is 1 for example. * chroma_width = -((-luma_width) >> log2_chroma_w) * The note above is needed to ensure rounding up. * This value only refers to the chroma components. */ uint8_t log2_chroma_w; ///< chroma_width = -((-luma_width )>>log2_chroma_w) /** * Amount to shift the luma height right to find the chroma height. * For YV12 this is 1 for example. * chroma_height= -((-luma_height) >> log2_chroma_h) * The note above is needed to ensure rounding up. * This value only refers to the chroma components. */ uint8_t log2_chroma_h; uint8_t flags; /** * Parameters that describe how pixels are packed. * If the format has 2 or 4 components, then alpha is last. * If the format has 1 or 2 components, then luma is 0. * If the format has 3 or 4 components, * if the RGB flag is set then 0 is red, 1 is green and 2 is blue; * otherwise 0 is luma, 1 is chroma-U and 2 is chroma-V. */ AVComponentDescriptor comp[4]; }AVPixFmtDescriptor; /** * Pixel format is big-endian. */ #define AV_PIX_FMT_FLAG_BE (1 << 0) /** * Pixel format has a palette in data[1], values are indexes in this palette. */ #define AV_PIX_FMT_FLAG_PAL (1 << 1) /** * All values of a component are bit-wise packed end to end. */ #define AV_PIX_FMT_FLAG_BITSTREAM (1 << 2) /** * Pixel format is an HW accelerated format. */ #define AV_PIX_FMT_FLAG_HWACCEL (1 << 3) /** * At least one pixel component is not in the first data plane. */ #define AV_PIX_FMT_FLAG_PLANAR (1 << 4) /** * The pixel format contains RGB-like data (as opposed to YUV/grayscale). */ #define AV_PIX_FMT_FLAG_RGB (1 << 5) /** * The pixel format is "pseudo-paletted". This means that FFmpeg treats it as * paletted internally, but the palette is generated by the decoder and is not * stored in the file. */ #define AV_PIX_FMT_FLAG_PSEUDOPAL (1 << 6) /** * The pixel format has an alpha channel. */ #define AV_PIX_FMT_FLAG_ALPHA (1 << 7) #if FF_API_PIX_FMT /** * @deprecated use the AV_PIX_FMT_FLAG_* flags */ #define PIX_FMT_BE AV_PIX_FMT_FLAG_BE #define PIX_FMT_PAL AV_PIX_FMT_FLAG_PAL #define PIX_FMT_BITSTREAM AV_PIX_FMT_FLAG_BITSTREAM #define PIX_FMT_HWACCEL AV_PIX_FMT_FLAG_HWACCEL #define PIX_FMT_PLANAR AV_PIX_FMT_FLAG_PLANAR #define PIX_FMT_RGB AV_PIX_FMT_FLAG_RGB #define PIX_FMT_PSEUDOPAL AV_PIX_FMT_FLAG_PSEUDOPAL #define PIX_FMT_ALPHA AV_PIX_FMT_FLAG_ALPHA #endif #if FF_API_PIX_FMT_DESC /** * The array of all the pixel format descriptors. */ extern attribute_deprecated const AVPixFmtDescriptor av_pix_fmt_descriptors[]; #endif /** * Read a line from an image, and write the values of the * pixel format component c to dst. * * @param data the array containing the pointers to the planes of the image * @param linesize the array containing the linesizes of the image * @param desc the pixel format descriptor for the image * @param x the horizontal coordinate of the first pixel to read * @param y the vertical coordinate of the first pixel to read * @param w the width of the line to read, that is the number of * values to write to dst * @param read_pal_component if not zero and the format is a paletted * format writes the values corresponding to the palette * component c in data[1] to dst, rather than the palette indexes in * data[0]. The behavior is undefined if the format is not paletted. */ void av_read_image_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component); /** * Write the values from src to the pixel format component c of an * image line. * * @param src array containing the values to write * @param data the array containing the pointers to the planes of the * image to write into. It is supposed to be zeroed. * @param linesize the array containing the linesizes of the image * @param desc the pixel format descriptor for the image * @param x the horizontal coordinate of the first pixel to write * @param y the vertical coordinate of the first pixel to write * @param w the width of the line to write, that is the number of * values to write to the image line */ void av_write_image_line(const uint16_t *src, uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w); /** * Return the pixel format corresponding to name. * * If there is no pixel format with name name, then looks for a * pixel format with the name corresponding to the native endian * format of name. * For example in a little-endian system, first looks for "gray16", * then for "gray16le". * * Finally if no pixel format has been found, returns AV_PIX_FMT_NONE. */ enum AVPixelFormat av_get_pix_fmt(const char *name); /** * Return the short name for a pixel format, NULL in case pix_fmt is * unknown. * * @see av_get_pix_fmt(), av_get_pix_fmt_string() */ const char *av_get_pix_fmt_name(enum AVPixelFormat pix_fmt); /** * Print in buf the string corresponding to the pixel format with * number pix_fmt, or a header if pix_fmt is negative. * * @param buf the buffer where to write the string * @param buf_size the size of buf * @param pix_fmt the number of the pixel format to print the * corresponding info string, or a negative value to print the * corresponding header. */ char *av_get_pix_fmt_string (char *buf, int buf_size, enum AVPixelFormat pix_fmt); /** * Return the number of bits per pixel used by the pixel format * described by pixdesc. Note that this is not the same as the number * of bits per sample. * * The returned number of bits refers to the number of bits actually * used for storing the pixel information, that is padding bits are * not counted. */ int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc); /** * Return the number of bits per pixel for the pixel format * described by pixdesc, including any padding or unused bits. */ int av_get_padded_bits_per_pixel(const AVPixFmtDescriptor *pixdesc); /** * @return a pixel format descriptor for provided pixel format or NULL if * this pixel format is unknown. */ const AVPixFmtDescriptor *av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt); /** * Iterate over all pixel format descriptors known to libavutil. * * @param prev previous descriptor. NULL to get the first descriptor. * * @return next descriptor or NULL after the last descriptor */ const AVPixFmtDescriptor *av_pix_fmt_desc_next(const AVPixFmtDescriptor *prev); /** * @return an AVPixelFormat id described by desc, or AV_PIX_FMT_NONE if desc * is not a valid pointer to a pixel format descriptor. */ enum AVPixelFormat av_pix_fmt_desc_get_id(const AVPixFmtDescriptor *desc); /** * Utility function to access log2_chroma_w log2_chroma_h from * the pixel format AVPixFmtDescriptor. * * See avcodec_get_chroma_sub_sample() for a function that asserts a * valid pixel format instead of returning an error code. * Its recommanded that you use avcodec_get_chroma_sub_sample unless * you do check the return code! * * @param[in] pix_fmt the pixel format * @param[out] h_shift store log2_chroma_w * @param[out] v_shift store log2_chroma_h * * @return 0 on success, AVERROR(ENOSYS) on invalid or unknown pixel format */ int av_pix_fmt_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift); /** * @return number of planes in pix_fmt, a negative AVERROR if pix_fmt is not a * valid pixel format. */ int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt); void ff_check_pixfmt_descriptors(void); /** * Utility function to swap the endianness of a pixel format. * * @param[in] pix_fmt the pixel format * * @return pixel format with swapped endianness if it exists, * otherwise AV_PIX_FMT_NONE */ enum AVPixelFormat av_pix_fmt_swap_endianness(enum AVPixelFormat pix_fmt); #endif /* AVUTIL_PIXDESC_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/pixfmt.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PIXFMT_H #define AVUTIL_PIXFMT_H /** * @file * pixel format definitions * */ #include "libavutil/avconfig.h" #include "version.h" #define AVPALETTE_SIZE 1024 #define AVPALETTE_COUNT 256 /** * Pixel format. * * @note * AV_PIX_FMT_RGB32 is handled in an endian-specific manner. An RGBA * color is put together as: * (A << 24) | (R << 16) | (G << 8) | B * This is stored as BGRA on little-endian CPU architectures and ARGB on * big-endian CPUs. * * @par * When the pixel format is palettized RGB (AV_PIX_FMT_PAL8), the palettized * image data is stored in AVFrame.data[0]. The palette is transported in * AVFrame.data[1], is 1024 bytes long (256 4-byte entries) and is * formatted the same as in AV_PIX_FMT_RGB32 described above (i.e., it is * also endian-specific). Note also that the individual RGB palette * components stored in AVFrame.data[1] should be in the range 0..255. * This is important as many custom PAL8 video codecs that were designed * to run on the IBM VGA graphics adapter use 6-bit palette components. * * @par * For all the 8bit per pixel formats, an RGB32 palette is in data[1] like * for pal8. This palette is filled in automatically by the function * allocating the picture. * * @note * Make sure that all newly added big-endian formats have (pix_fmt & 1) == 1 * and that all newly added little-endian formats have (pix_fmt & 1) == 0. * This allows simpler detection of big vs little-endian. */ enum AVPixelFormat { AV_PIX_FMT_NONE = -1, AV_PIX_FMT_YUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples) AV_PIX_FMT_YUYV422, ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr AV_PIX_FMT_RGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB... AV_PIX_FMT_BGR24, ///< packed RGB 8:8:8, 24bpp, BGRBGR... AV_PIX_FMT_YUV422P, ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) AV_PIX_FMT_YUV444P, ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples) AV_PIX_FMT_YUV410P, ///< planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples) AV_PIX_FMT_YUV411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) AV_PIX_FMT_GRAY8, ///< Y , 8bpp AV_PIX_FMT_MONOWHITE, ///< Y , 1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb AV_PIX_FMT_MONOBLACK, ///< Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb AV_PIX_FMT_PAL8, ///< 8 bit with PIX_FMT_RGB32 palette AV_PIX_FMT_YUVJ420P, ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV420P and setting color_range AV_PIX_FMT_YUVJ422P, ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV422P and setting color_range AV_PIX_FMT_YUVJ444P, ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV444P and setting color_range #if FF_API_XVMC AV_PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing AV_PIX_FMT_XVMC_MPEG2_IDCT, #define AV_PIX_FMT_XVMC AV_PIX_FMT_XVMC_MPEG2_IDCT #endif /* FF_API_XVMC */ AV_PIX_FMT_UYVY422, ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1 AV_PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3 AV_PIX_FMT_BGR8, ///< packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb) AV_PIX_FMT_BGR4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits AV_PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb) AV_PIX_FMT_RGB8, ///< packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb) AV_PIX_FMT_RGB4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits AV_PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb) AV_PIX_FMT_NV12, ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) AV_PIX_FMT_NV21, ///< as above, but U and V bytes are swapped AV_PIX_FMT_ARGB, ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB... AV_PIX_FMT_RGBA, ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA... AV_PIX_FMT_ABGR, ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR... AV_PIX_FMT_BGRA, ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA... AV_PIX_FMT_GRAY16BE, ///< Y , 16bpp, big-endian AV_PIX_FMT_GRAY16LE, ///< Y , 16bpp, little-endian AV_PIX_FMT_YUV440P, ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples) AV_PIX_FMT_YUVJ440P, ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of PIX_FMT_YUV440P and setting color_range AV_PIX_FMT_YUVA420P, ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples) #if FF_API_VDPAU AV_PIX_FMT_VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers AV_PIX_FMT_VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers AV_PIX_FMT_VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers AV_PIX_FMT_VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers AV_PIX_FMT_VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers #endif AV_PIX_FMT_RGB48BE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian AV_PIX_FMT_RGB48LE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian AV_PIX_FMT_RGB565BE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian AV_PIX_FMT_RGB565LE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian AV_PIX_FMT_RGB555BE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0 AV_PIX_FMT_RGB555LE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0 AV_PIX_FMT_BGR565BE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), big-endian AV_PIX_FMT_BGR565LE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), little-endian AV_PIX_FMT_BGR555BE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1 AV_PIX_FMT_BGR555LE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1 AV_PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers AV_PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers AV_PIX_FMT_VAAPI_VLD, ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers AV_PIX_FMT_YUV420P16LE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV420P16BE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV422P16LE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV422P16BE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV444P16LE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV444P16BE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian #if FF_API_VDPAU AV_PIX_FMT_VDPAU_MPEG4, ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers #endif AV_PIX_FMT_DXVA2_VLD, ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer AV_PIX_FMT_RGB444LE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0 AV_PIX_FMT_RGB444BE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0 AV_PIX_FMT_BGR444LE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1 AV_PIX_FMT_BGR444BE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1 AV_PIX_FMT_GRAY8A, ///< 8bit gray, 8bit alpha AV_PIX_FMT_BGR48BE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian AV_PIX_FMT_BGR48LE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian /** * The following 12 formats have the disadvantage of needing 1 format for each bit depth. * Notice that each 9/10 bits sample is stored in 16 bits with extra padding. * If you want to support multiple bit depths, then using AV_PIX_FMT_YUV420P16* with the bpp stored separately is better. */ AV_PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_VDA_VLD, ///< hardware decoding through VDA #ifdef AV_PIX_FMT_ABI_GIT_MASTER AV_PIX_FMT_RGBA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian AV_PIX_FMT_RGBA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian AV_PIX_FMT_BGRA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian AV_PIX_FMT_BGRA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian #endif AV_PIX_FMT_GBRP, ///< planar GBR 4:4:4 24bpp AV_PIX_FMT_GBRP9BE, ///< planar GBR 4:4:4 27bpp, big-endian AV_PIX_FMT_GBRP9LE, ///< planar GBR 4:4:4 27bpp, little-endian AV_PIX_FMT_GBRP10BE, ///< planar GBR 4:4:4 30bpp, big-endian AV_PIX_FMT_GBRP10LE, ///< planar GBR 4:4:4 30bpp, little-endian AV_PIX_FMT_GBRP16BE, ///< planar GBR 4:4:4 48bpp, big-endian AV_PIX_FMT_GBRP16LE, ///< planar GBR 4:4:4 48bpp, little-endian /** * duplicated pixel formats for compatibility with libav. * FFmpeg supports these formats since May 8 2012 and Jan 28 2012 (commits f9ca1ac7 and 143a5c55) * Libav added them Oct 12 2012 with incompatible values (commit 6d5600e85) */ AV_PIX_FMT_YUVA422P_LIBAV, ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples) AV_PIX_FMT_YUVA444P_LIBAV, ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples) AV_PIX_FMT_YUVA420P9BE, ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), big-endian AV_PIX_FMT_YUVA420P9LE, ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), little-endian AV_PIX_FMT_YUVA422P9BE, ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), big-endian AV_PIX_FMT_YUVA422P9LE, ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), little-endian AV_PIX_FMT_YUVA444P9BE, ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), big-endian AV_PIX_FMT_YUVA444P9LE, ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), little-endian AV_PIX_FMT_YUVA420P10BE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian) AV_PIX_FMT_YUVA420P10LE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian) AV_PIX_FMT_YUVA422P10BE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA422P10LE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian) AV_PIX_FMT_YUVA444P10BE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA444P10LE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian) AV_PIX_FMT_YUVA420P16BE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian) AV_PIX_FMT_YUVA420P16LE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian) AV_PIX_FMT_YUVA422P16BE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA422P16LE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian) AV_PIX_FMT_YUVA444P16BE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA444P16LE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian) AV_PIX_FMT_VDPAU, ///< HW acceleration through VDPAU, Picture.data[3] contains a VdpVideoSurface AV_PIX_FMT_XYZ12LE, ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as little-endian, the 4 lower bits are set to 0 AV_PIX_FMT_XYZ12BE, ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as big-endian, the 4 lower bits are set to 0 AV_PIX_FMT_NV16, ///< interleaved chroma YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) AV_PIX_FMT_NV20LE, ///< interleaved chroma YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_NV20BE, ///< interleaved chroma YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian #ifndef AV_PIX_FMT_ABI_GIT_MASTER AV_PIX_FMT_RGBA64BE=0x123, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian AV_PIX_FMT_RGBA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian AV_PIX_FMT_BGRA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian AV_PIX_FMT_BGRA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian #endif AV_PIX_FMT_0RGB=0x123+4, ///< packed RGB 8:8:8, 32bpp, 0RGB0RGB... AV_PIX_FMT_RGB0, ///< packed RGB 8:8:8, 32bpp, RGB0RGB0... AV_PIX_FMT_0BGR, ///< packed BGR 8:8:8, 32bpp, 0BGR0BGR... AV_PIX_FMT_BGR0, ///< packed BGR 8:8:8, 32bpp, BGR0BGR0... AV_PIX_FMT_YUVA444P, ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples) AV_PIX_FMT_YUVA422P, ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples) AV_PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_GBRP12BE, ///< planar GBR 4:4:4 36bpp, big-endian AV_PIX_FMT_GBRP12LE, ///< planar GBR 4:4:4 36bpp, little-endian AV_PIX_FMT_GBRP14BE, ///< planar GBR 4:4:4 42bpp, big-endian AV_PIX_FMT_GBRP14LE, ///< planar GBR 4:4:4 42bpp, little-endian AV_PIX_FMT_GBRAP, ///< planar GBRA 4:4:4:4 32bpp AV_PIX_FMT_GBRAP16BE, ///< planar GBRA 4:4:4:4 64bpp, big-endian AV_PIX_FMT_GBRAP16LE, ///< planar GBRA 4:4:4:4 64bpp, little-endian AV_PIX_FMT_YUVJ411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor of PIX_FMT_YUV411P and setting color_range AV_PIX_FMT_BAYER_BGGR8, ///< bayer, BGBG..(odd line), GRGR..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_RGGB8, ///< bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_GBRG8, ///< bayer, GBGB..(odd line), RGRG..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_GRBG8, ///< bayer, GRGR..(odd line), BGBG..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_BGGR16LE, ///< bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_BGGR16BE, ///< bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, big-endian */ AV_PIX_FMT_BAYER_RGGB16LE, ///< bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_RGGB16BE, ///< bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, big-endian */ AV_PIX_FMT_BAYER_GBRG16LE, ///< bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_GBRG16BE, ///< bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, big-endian */ AV_PIX_FMT_BAYER_GRBG16LE, ///< bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_GRBG16BE, ///< bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, big-endian */ #if !FF_API_XVMC AV_PIX_FMT_XVMC,///< XVideo Motion Acceleration via common packet passing #endif /* !FF_API_XVMC */ AV_PIX_FMT_NB, ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions #if FF_API_PIX_FMT #include "old_pix_fmts.h" #endif }; #if AV_HAVE_INCOMPATIBLE_LIBAV_ABI #define AV_PIX_FMT_YUVA422P AV_PIX_FMT_YUVA422P_LIBAV #define AV_PIX_FMT_YUVA444P AV_PIX_FMT_YUVA444P_LIBAV #endif #define AV_PIX_FMT_Y400A AV_PIX_FMT_GRAY8A #define AV_PIX_FMT_GBR24P AV_PIX_FMT_GBRP #if AV_HAVE_BIGENDIAN # define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##be #else # define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##le #endif #define AV_PIX_FMT_RGB32 AV_PIX_FMT_NE(ARGB, BGRA) #define AV_PIX_FMT_RGB32_1 AV_PIX_FMT_NE(RGBA, ABGR) #define AV_PIX_FMT_BGR32 AV_PIX_FMT_NE(ABGR, RGBA) #define AV_PIX_FMT_BGR32_1 AV_PIX_FMT_NE(BGRA, ARGB) #define AV_PIX_FMT_0RGB32 AV_PIX_FMT_NE(0RGB, BGR0) #define AV_PIX_FMT_0BGR32 AV_PIX_FMT_NE(0BGR, RGB0) #define AV_PIX_FMT_GRAY16 AV_PIX_FMT_NE(GRAY16BE, GRAY16LE) #define AV_PIX_FMT_RGB48 AV_PIX_FMT_NE(RGB48BE, RGB48LE) #define AV_PIX_FMT_RGB565 AV_PIX_FMT_NE(RGB565BE, RGB565LE) #define AV_PIX_FMT_RGB555 AV_PIX_FMT_NE(RGB555BE, RGB555LE) #define AV_PIX_FMT_RGB444 AV_PIX_FMT_NE(RGB444BE, RGB444LE) #define AV_PIX_FMT_BGR48 AV_PIX_FMT_NE(BGR48BE, BGR48LE) #define AV_PIX_FMT_BGR565 AV_PIX_FMT_NE(BGR565BE, BGR565LE) #define AV_PIX_FMT_BGR555 AV_PIX_FMT_NE(BGR555BE, BGR555LE) #define AV_PIX_FMT_BGR444 AV_PIX_FMT_NE(BGR444BE, BGR444LE) #define AV_PIX_FMT_YUV420P9 AV_PIX_FMT_NE(YUV420P9BE , YUV420P9LE) #define AV_PIX_FMT_YUV422P9 AV_PIX_FMT_NE(YUV422P9BE , YUV422P9LE) #define AV_PIX_FMT_YUV444P9 AV_PIX_FMT_NE(YUV444P9BE , YUV444P9LE) #define AV_PIX_FMT_YUV420P10 AV_PIX_FMT_NE(YUV420P10BE, YUV420P10LE) #define AV_PIX_FMT_YUV422P10 AV_PIX_FMT_NE(YUV422P10BE, YUV422P10LE) #define AV_PIX_FMT_YUV444P10 AV_PIX_FMT_NE(YUV444P10BE, YUV444P10LE) #define AV_PIX_FMT_YUV420P12 AV_PIX_FMT_NE(YUV420P12BE, YUV420P12LE) #define AV_PIX_FMT_YUV422P12 AV_PIX_FMT_NE(YUV422P12BE, YUV422P12LE) #define AV_PIX_FMT_YUV444P12 AV_PIX_FMT_NE(YUV444P12BE, YUV444P12LE) #define AV_PIX_FMT_YUV420P14 AV_PIX_FMT_NE(YUV420P14BE, YUV420P14LE) #define AV_PIX_FMT_YUV422P14 AV_PIX_FMT_NE(YUV422P14BE, YUV422P14LE) #define AV_PIX_FMT_YUV444P14 AV_PIX_FMT_NE(YUV444P14BE, YUV444P14LE) #define AV_PIX_FMT_YUV420P16 AV_PIX_FMT_NE(YUV420P16BE, YUV420P16LE) #define AV_PIX_FMT_YUV422P16 AV_PIX_FMT_NE(YUV422P16BE, YUV422P16LE) #define AV_PIX_FMT_YUV444P16 AV_PIX_FMT_NE(YUV444P16BE, YUV444P16LE) #define AV_PIX_FMT_RGBA64 AV_PIX_FMT_NE(RGBA64BE, RGBA64LE) #define AV_PIX_FMT_BGRA64 AV_PIX_FMT_NE(BGRA64BE, BGRA64LE) #define AV_PIX_FMT_GBRP9 AV_PIX_FMT_NE(GBRP9BE , GBRP9LE) #define AV_PIX_FMT_GBRP10 AV_PIX_FMT_NE(GBRP10BE, GBRP10LE) #define AV_PIX_FMT_GBRP12 AV_PIX_FMT_NE(GBRP12BE, GBRP12LE) #define AV_PIX_FMT_GBRP14 AV_PIX_FMT_NE(GBRP14BE, GBRP14LE) #define AV_PIX_FMT_GBRP16 AV_PIX_FMT_NE(GBRP16BE, GBRP16LE) #define AV_PIX_FMT_GBRAP16 AV_PIX_FMT_NE(GBRAP16BE, GBRAP16LE) #define AV_PIX_FMT_BAYER_BGGR16 AV_PIX_FMT_NE(BAYER_BGGR16BE, BAYER_BGGR16LE) #define AV_PIX_FMT_BAYER_RGGB16 AV_PIX_FMT_NE(BAYER_RGGB16BE, BAYER_RGGB16LE) #define AV_PIX_FMT_BAYER_GBRG16 AV_PIX_FMT_NE(BAYER_GBRG16BE, BAYER_GBRG16LE) #define AV_PIX_FMT_BAYER_GRBG16 AV_PIX_FMT_NE(BAYER_GRBG16BE, BAYER_GRBG16LE) #define AV_PIX_FMT_YUVA420P9 AV_PIX_FMT_NE(YUVA420P9BE , YUVA420P9LE) #define AV_PIX_FMT_YUVA422P9 AV_PIX_FMT_NE(YUVA422P9BE , YUVA422P9LE) #define AV_PIX_FMT_YUVA444P9 AV_PIX_FMT_NE(YUVA444P9BE , YUVA444P9LE) #define AV_PIX_FMT_YUVA420P10 AV_PIX_FMT_NE(YUVA420P10BE, YUVA420P10LE) #define AV_PIX_FMT_YUVA422P10 AV_PIX_FMT_NE(YUVA422P10BE, YUVA422P10LE) #define AV_PIX_FMT_YUVA444P10 AV_PIX_FMT_NE(YUVA444P10BE, YUVA444P10LE) #define AV_PIX_FMT_YUVA420P16 AV_PIX_FMT_NE(YUVA420P16BE, YUVA420P16LE) #define AV_PIX_FMT_YUVA422P16 AV_PIX_FMT_NE(YUVA422P16BE, YUVA422P16LE) #define AV_PIX_FMT_YUVA444P16 AV_PIX_FMT_NE(YUVA444P16BE, YUVA444P16LE) #define AV_PIX_FMT_XYZ12 AV_PIX_FMT_NE(XYZ12BE, XYZ12LE) #define AV_PIX_FMT_NV20 AV_PIX_FMT_NE(NV20BE, NV20LE) #if FF_API_PIX_FMT #define PixelFormat AVPixelFormat #define PIX_FMT_Y400A AV_PIX_FMT_Y400A #define PIX_FMT_GBR24P AV_PIX_FMT_GBR24P #define PIX_FMT_NE(be, le) AV_PIX_FMT_NE(be, le) #define PIX_FMT_RGB32 AV_PIX_FMT_RGB32 #define PIX_FMT_RGB32_1 AV_PIX_FMT_RGB32_1 #define PIX_FMT_BGR32 AV_PIX_FMT_BGR32 #define PIX_FMT_BGR32_1 AV_PIX_FMT_BGR32_1 #define PIX_FMT_0RGB32 AV_PIX_FMT_0RGB32 #define PIX_FMT_0BGR32 AV_PIX_FMT_0BGR32 #define PIX_FMT_GRAY16 AV_PIX_FMT_GRAY16 #define PIX_FMT_RGB48 AV_PIX_FMT_RGB48 #define PIX_FMT_RGB565 AV_PIX_FMT_RGB565 #define PIX_FMT_RGB555 AV_PIX_FMT_RGB555 #define PIX_FMT_RGB444 AV_PIX_FMT_RGB444 #define PIX_FMT_BGR48 AV_PIX_FMT_BGR48 #define PIX_FMT_BGR565 AV_PIX_FMT_BGR565 #define PIX_FMT_BGR555 AV_PIX_FMT_BGR555 #define PIX_FMT_BGR444 AV_PIX_FMT_BGR444 #define PIX_FMT_YUV420P9 AV_PIX_FMT_YUV420P9 #define PIX_FMT_YUV422P9 AV_PIX_FMT_YUV422P9 #define PIX_FMT_YUV444P9 AV_PIX_FMT_YUV444P9 #define PIX_FMT_YUV420P10 AV_PIX_FMT_YUV420P10 #define PIX_FMT_YUV422P10 AV_PIX_FMT_YUV422P10 #define PIX_FMT_YUV444P10 AV_PIX_FMT_YUV444P10 #define PIX_FMT_YUV420P12 AV_PIX_FMT_YUV420P12 #define PIX_FMT_YUV422P12 AV_PIX_FMT_YUV422P12 #define PIX_FMT_YUV444P12 AV_PIX_FMT_YUV444P12 #define PIX_FMT_YUV420P14 AV_PIX_FMT_YUV420P14 #define PIX_FMT_YUV422P14 AV_PIX_FMT_YUV422P14 #define PIX_FMT_YUV444P14 AV_PIX_FMT_YUV444P14 #define PIX_FMT_YUV420P16 AV_PIX_FMT_YUV420P16 #define PIX_FMT_YUV422P16 AV_PIX_FMT_YUV422P16 #define PIX_FMT_YUV444P16 AV_PIX_FMT_YUV444P16 #define PIX_FMT_RGBA64 AV_PIX_FMT_RGBA64 #define PIX_FMT_BGRA64 AV_PIX_FMT_BGRA64 #define PIX_FMT_GBRP9 AV_PIX_FMT_GBRP9 #define PIX_FMT_GBRP10 AV_PIX_FMT_GBRP10 #define PIX_FMT_GBRP12 AV_PIX_FMT_GBRP12 #define PIX_FMT_GBRP14 AV_PIX_FMT_GBRP14 #define PIX_FMT_GBRP16 AV_PIX_FMT_GBRP16 #endif #endif /* AVUTIL_PIXFMT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/random_seed.h ================================================ /* * Copyright (c) 2009 Baptiste Coudurier * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_RANDOM_SEED_H #define AVUTIL_RANDOM_SEED_H #include /** * @addtogroup lavu_crypto * @{ */ /** * Get a seed to use in conjunction with random functions. * This function tries to provide a good seed at a best effort bases. * Its possible to call this function multiple times if more bits are needed. * It can be quite slow, which is why it should only be used as seed for a faster * PRNG. The quality of the seed depends on the platform. */ uint32_t av_get_random_seed(void); /** * @} */ #endif /* AVUTIL_RANDOM_SEED_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/rational.h ================================================ /* * rational numbers * Copyright (c) 2003 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * rational numbers * @author Michael Niedermayer */ #ifndef AVUTIL_RATIONAL_H #define AVUTIL_RATIONAL_H #include #include #include "attributes.h" /** * @addtogroup lavu_math * @{ */ /** * rational number numerator/denominator */ typedef struct AVRational{ int num; ///< numerator int den; ///< denominator } AVRational; /** * Create a rational. * Useful for compilers that do not support compound literals. * @note The return value is not reduced. */ static inline AVRational av_make_q(int num, int den) { AVRational r = { num, den }; return r; } /** * Compare two rationals. * @param a first rational * @param b second rational * @return 0 if a==b, 1 if a>b, -1 if a>63)|1; else if(b.den && a.den) return 0; else if(a.num && b.num) return (a.num>>31) - (b.num>>31); else return INT_MIN; } /** * Convert rational to double. * @param a rational to convert * @return (double) a */ static inline double av_q2d(AVRational a){ return a.num / (double) a.den; } /** * Reduce a fraction. * This is useful for framerate calculations. * @param dst_num destination numerator * @param dst_den destination denominator * @param num source numerator * @param den source denominator * @param max the maximum allowed for dst_num & dst_den * @return 1 if exact, 0 otherwise */ int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max); /** * Multiply two rationals. * @param b first rational * @param c second rational * @return b*c */ AVRational av_mul_q(AVRational b, AVRational c) av_const; /** * Divide one rational by another. * @param b first rational * @param c second rational * @return b/c */ AVRational av_div_q(AVRational b, AVRational c) av_const; /** * Add two rationals. * @param b first rational * @param c second rational * @return b+c */ AVRational av_add_q(AVRational b, AVRational c) av_const; /** * Subtract one rational from another. * @param b first rational * @param c second rational * @return b-c */ AVRational av_sub_q(AVRational b, AVRational c) av_const; /** * Invert a rational. * @param q value * @return 1 / q */ static av_always_inline AVRational av_inv_q(AVRational q) { AVRational r = { q.den, q.num }; return r; } /** * Convert a double precision floating point number to a rational. * inf is expressed as {1,0} or {-1,0} depending on the sign. * * @param d double to convert * @param max the maximum allowed numerator and denominator * @return (AVRational) d */ AVRational av_d2q(double d, int max) av_const; /** * @return 1 if q1 is nearer to q than q2, -1 if q2 is nearer * than q1, 0 if they have the same distance. */ int av_nearer_q(AVRational q, AVRational q1, AVRational q2); /** * Find the nearest value in q_list to q. * @param q_list an array of rationals terminated by {0, 0} * @return the index of the nearest value found in the array */ int av_find_nearest_q_idx(AVRational q, const AVRational* q_list); /** * @} */ #endif /* AVUTIL_RATIONAL_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/ripemd.h ================================================ /* * Copyright (C) 2007 Michael Niedermayer * Copyright (C) 2013 James Almer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_RIPEMD_H #define AVUTIL_RIPEMD_H #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_ripemd RIPEMD * @ingroup lavu_crypto * @{ */ extern const int av_ripemd_size; struct AVRIPEMD; /** * Allocate an AVRIPEMD context. */ struct AVRIPEMD *av_ripemd_alloc(void); /** * Initialize RIPEMD hashing. * * @param context pointer to the function context (of size av_ripemd_size) * @param bits number of bits in digest (128, 160, 256 or 320 bits) * @return zero if initialization succeeded, -1 otherwise */ int av_ripemd_init(struct AVRIPEMD* context, int bits); /** * Update hash value. * * @param context hash function context * @param data input data to update hash with * @param len input data length */ void av_ripemd_update(struct AVRIPEMD* context, const uint8_t* data, unsigned int len); /** * Finish hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored */ void av_ripemd_final(struct AVRIPEMD* context, uint8_t *digest); /** * @} */ #endif /* AVUTIL_RIPEMD_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/samplefmt.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SAMPLEFMT_H #define AVUTIL_SAMPLEFMT_H #include #include "avutil.h" #include "attributes.h" /** * Audio Sample Formats * * @par * The data described by the sample format is always in native-endian order. * Sample values can be expressed by native C types, hence the lack of a signed * 24-bit sample format even though it is a common raw audio data format. * * @par * The floating-point formats are based on full volume being in the range * [-1.0, 1.0]. Any values outside this range are beyond full volume level. * * @par * The data layout as used in av_samples_fill_arrays() and elsewhere in FFmpeg * (such as AVFrame in libavcodec) is as follows: * * For planar sample formats, each audio channel is in a separate data plane, * and linesize is the buffer size, in bytes, for a single plane. All data * planes must be the same size. For packed sample formats, only the first data * plane is used, and samples for each channel are interleaved. In this case, * linesize is the buffer size, in bytes, for the 1 plane. */ enum AVSampleFormat { AV_SAMPLE_FMT_NONE = -1, AV_SAMPLE_FMT_U8, ///< unsigned 8 bits AV_SAMPLE_FMT_S16, ///< signed 16 bits AV_SAMPLE_FMT_S32, ///< signed 32 bits AV_SAMPLE_FMT_FLT, ///< float AV_SAMPLE_FMT_DBL, ///< double AV_SAMPLE_FMT_U8P, ///< unsigned 8 bits, planar AV_SAMPLE_FMT_S16P, ///< signed 16 bits, planar AV_SAMPLE_FMT_S32P, ///< signed 32 bits, planar AV_SAMPLE_FMT_FLTP, ///< float, planar AV_SAMPLE_FMT_DBLP, ///< double, planar AV_SAMPLE_FMT_NB ///< Number of sample formats. DO NOT USE if linking dynamically }; /** * Return the name of sample_fmt, or NULL if sample_fmt is not * recognized. */ const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt); /** * Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE * on error. */ enum AVSampleFormat av_get_sample_fmt(const char *name); /** * Return the planar<->packed alternative form of the given sample format, or * AV_SAMPLE_FMT_NONE on error. If the passed sample_fmt is already in the * requested planar/packed format, the format returned is the same as the * input. */ enum AVSampleFormat av_get_alt_sample_fmt(enum AVSampleFormat sample_fmt, int planar); /** * Get the packed alternative form of the given sample format. * * If the passed sample_fmt is already in packed format, the format returned is * the same as the input. * * @return the packed alternative form of the given sample format or AV_SAMPLE_FMT_NONE on error. */ enum AVSampleFormat av_get_packed_sample_fmt(enum AVSampleFormat sample_fmt); /** * Get the planar alternative form of the given sample format. * * If the passed sample_fmt is already in planar format, the format returned is * the same as the input. * * @return the planar alternative form of the given sample format or AV_SAMPLE_FMT_NONE on error. */ enum AVSampleFormat av_get_planar_sample_fmt(enum AVSampleFormat sample_fmt); /** * Generate a string corresponding to the sample format with * sample_fmt, or a header if sample_fmt is negative. * * @param buf the buffer where to write the string * @param buf_size the size of buf * @param sample_fmt the number of the sample format to print the * corresponding info string, or a negative value to print the * corresponding header. * @return the pointer to the filled buffer or NULL if sample_fmt is * unknown or in case of other errors */ char *av_get_sample_fmt_string(char *buf, int buf_size, enum AVSampleFormat sample_fmt); #if FF_API_GET_BITS_PER_SAMPLE_FMT /** * @deprecated Use av_get_bytes_per_sample() instead. */ attribute_deprecated int av_get_bits_per_sample_fmt(enum AVSampleFormat sample_fmt); #endif /** * Return number of bytes per sample. * * @param sample_fmt the sample format * @return number of bytes per sample or zero if unknown for the given * sample format */ int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt); /** * Check if the sample format is planar. * * @param sample_fmt the sample format to inspect * @return 1 if the sample format is planar, 0 if it is interleaved */ int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt); /** * Get the required buffer size for the given audio parameters. * * @param[out] linesize calculated linesize, may be NULL * @param nb_channels the number of channels * @param nb_samples the number of samples in a single channel * @param sample_fmt the sample format * @param align buffer size alignment (0 = default, 1 = no alignment) * @return required buffer size, or negative error code on failure */ int av_samples_get_buffer_size(int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * Fill plane data pointers and linesize for samples with sample * format sample_fmt. * * The audio_data array is filled with the pointers to the samples data planes: * for planar, set the start point of each channel's data within the buffer, * for packed, set the start point of the entire buffer only. * * The value pointed to by linesize is set to the aligned size of each * channel's data buffer for planar layout, or to the aligned size of the * buffer for all channels for packed layout. * * The buffer in buf must be big enough to contain all the samples * (use av_samples_get_buffer_size() to compute its minimum size), * otherwise the audio_data pointers will point to invalid data. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param[out] audio_data array to be filled with the pointer for each channel * @param[out] linesize calculated linesize, may be NULL * @param buf the pointer to a buffer containing the samples * @param nb_channels the number of channels * @param nb_samples the number of samples in a single channel * @param sample_fmt the sample format * @param align buffer size alignment (0 = default, 1 = no alignment) * @return >=0 on success or a negative error code on failure * @todo return minimum size in bytes required for the buffer in case * of success at the next bump */ int av_samples_fill_arrays(uint8_t **audio_data, int *linesize, const uint8_t *buf, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * Allocate a samples buffer for nb_samples samples, and fill data pointers and * linesize accordingly. * The allocated samples buffer can be freed by using av_freep(&audio_data[0]) * Allocated data will be initialized to silence. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param[out] audio_data array to be filled with the pointer for each channel * @param[out] linesize aligned size for audio buffer(s), may be NULL * @param nb_channels number of audio channels * @param nb_samples number of samples per channel * @param align buffer size alignment (0 = default, 1 = no alignment) * @return >=0 on success or a negative error code on failure * @todo return the size of the allocated buffer in case of success at the next bump * @see av_samples_fill_arrays() * @see av_samples_alloc_array_and_samples() */ int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * Allocate a data pointers array, samples buffer for nb_samples * samples, and fill data pointers and linesize accordingly. * * This is the same as av_samples_alloc(), but also allocates the data * pointers array. * * @see av_samples_alloc() */ int av_samples_alloc_array_and_samples(uint8_t ***audio_data, int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * Copy samples from src to dst. * * @param dst destination array of pointers to data planes * @param src source array of pointers to data planes * @param dst_offset offset in samples at which the data will be written to dst * @param src_offset offset in samples at which the data will be read from src * @param nb_samples number of samples to be copied * @param nb_channels number of audio channels * @param sample_fmt audio sample format */ int av_samples_copy(uint8_t **dst, uint8_t * const *src, int dst_offset, int src_offset, int nb_samples, int nb_channels, enum AVSampleFormat sample_fmt); /** * Fill an audio buffer with silence. * * @param audio_data array of pointers to data planes * @param offset offset in samples at which to start filling * @param nb_samples number of samples to fill * @param nb_channels number of audio channels * @param sample_fmt audio sample format */ int av_samples_set_silence(uint8_t **audio_data, int offset, int nb_samples, int nb_channels, enum AVSampleFormat sample_fmt); #endif /* AVUTIL_SAMPLEFMT_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/sha.h ================================================ /* * Copyright (C) 2007 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SHA_H #define AVUTIL_SHA_H #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_sha SHA * @ingroup lavu_crypto * @{ */ extern const int av_sha_size; struct AVSHA; /** * Allocate an AVSHA context. */ struct AVSHA *av_sha_alloc(void); /** * Initialize SHA-1 or SHA-2 hashing. * * @param context pointer to the function context (of size av_sha_size) * @param bits number of bits in digest (SHA-1 - 160 bits, SHA-2 224 or 256 bits) * @return zero if initialization succeeded, -1 otherwise */ int av_sha_init(struct AVSHA* context, int bits); /** * Update hash value. * * @param context hash function context * @param data input data to update hash with * @param len input data length */ void av_sha_update(struct AVSHA* context, const uint8_t* data, unsigned int len); /** * Finish hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored */ void av_sha_final(struct AVSHA* context, uint8_t *digest); /** * @} */ #endif /* AVUTIL_SHA_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/sha512.h ================================================ /* * Copyright (C) 2007 Michael Niedermayer * Copyright (C) 2013 James Almer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SHA512_H #define AVUTIL_SHA512_H #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_sha512 SHA512 * @ingroup lavu_crypto * @{ */ extern const int av_sha512_size; struct AVSHA512; /** * Allocate an AVSHA512 context. */ struct AVSHA512 *av_sha512_alloc(void); /** * Initialize SHA-2 512 hashing. * * @param context pointer to the function context (of size av_sha512_size) * @param bits number of bits in digest (224, 256, 384 or 512 bits) * @return zero if initialization succeeded, -1 otherwise */ int av_sha512_init(struct AVSHA512* context, int bits); /** * Update hash value. * * @param context hash function context * @param data input data to update hash with * @param len input data length */ void av_sha512_update(struct AVSHA512* context, const uint8_t* data, unsigned int len); /** * Finish hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored */ void av_sha512_final(struct AVSHA512* context, uint8_t *digest); /** * @} */ #endif /* AVUTIL_SHA512_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/stereo3d.h ================================================ /* * Copyright (c) 2013 Vittorio Giovara * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include "frame.h" /** * List of possible 3D Types */ enum AVStereo3DType { /** * Video is not stereoscopic (and metadata has to be there). */ AV_STEREO3D_2D, /** * Views are next to each other. * * LLLLRRRR * LLLLRRRR * LLLLRRRR * ... */ AV_STEREO3D_SIDEBYSIDE, /** * Views are on top of each other. * * LLLLLLLL * LLLLLLLL * RRRRRRRR * RRRRRRRR */ AV_STEREO3D_TOPBOTTOM, /** * Views are alternated temporally. * * frame0 frame1 frame2 ... * LLLLLLLL RRRRRRRR LLLLLLLL * LLLLLLLL RRRRRRRR LLLLLLLL * LLLLLLLL RRRRRRRR LLLLLLLL * ... ... ... */ AV_STEREO3D_FRAMESEQUENCE, /** * Views are packed in a checkerboard-like structure per pixel. * * LRLRLRLR * RLRLRLRL * LRLRLRLR * ... */ AV_STEREO3D_CHECKERBOARD, /** * Views are next to each other, but when upscaling * apply a checkerboard pattern. * * LLLLRRRR L L L L R R R R * LLLLRRRR => L L L L R R R R * LLLLRRRR L L L L R R R R * LLLLRRRR L L L L R R R R */ AV_STEREO3D_SIDEBYSIDE_QUINCUNX, /** * Views are packed per line, as if interlaced. * * LLLLLLLL * RRRRRRRR * LLLLLLLL * ... */ AV_STEREO3D_LINES, /** * Views are packed per column. * * LRLRLRLR * LRLRLRLR * LRLRLRLR * ... */ AV_STEREO3D_COLUMNS, }; /** * Inverted views, Right/Bottom represents the left view. */ #define AV_STEREO3D_FLAG_INVERT (1 << 0) /** * Stereo 3D type: this structure describes how two videos are packed * within a single video surface, with additional information as needed. * * @note The struct must be allocated with av_stereo3d_alloc() and * its size is not a part of the public ABI. */ typedef struct AVStereo3D { /** * How views are packed within the video. */ enum AVStereo3DType type; /** * Additional information about the frame packing. */ int flags; } AVStereo3D; /** * Allocate an AVStereo3D structure and set its fields to default values. * The resulting struct can be freed using av_freep(). * * @return An AVStereo3D filled with default values or NULL on failure. */ AVStereo3D *av_stereo3d_alloc(void); /** * Allocate a complete AVFrameSideData and add it to the frame. * * @param frame The frame which side data is added to. * * @return The AVStereo3D structure to be filled by caller. */ AVStereo3D *av_stereo3d_create_side_data(AVFrame *frame); ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/time.h ================================================ /* * Copyright (c) 2000-2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_TIME_H #define AVUTIL_TIME_H #include /** * Get the current time in microseconds. */ int64_t av_gettime(void); /** * Sleep for a period of time. Although the duration is expressed in * microseconds, the actual delay may be rounded to the precision of the * system timer. * * @param usec Number of microseconds to sleep. * @return zero on success or (negative) error code. */ int av_usleep(unsigned usec); #endif /* AVUTIL_TIME_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/timecode.h ================================================ /* * Copyright (c) 2006 Smartjog S.A.S, Baptiste Coudurier * Copyright (c) 2011-2012 Smartjog S.A.S, Clément Bœsch * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Timecode helpers header */ #ifndef AVUTIL_TIMECODE_H #define AVUTIL_TIMECODE_H #include #include "rational.h" #define AV_TIMECODE_STR_SIZE 16 enum AVTimecodeFlag { AV_TIMECODE_FLAG_DROPFRAME = 1<<0, ///< timecode is drop frame AV_TIMECODE_FLAG_24HOURSMAX = 1<<1, ///< timecode wraps after 24 hours AV_TIMECODE_FLAG_ALLOWNEGATIVE = 1<<2, ///< negative time values are allowed }; typedef struct { int start; ///< timecode frame start (first base frame number) uint32_t flags; ///< flags such as drop frame, +24 hours support, ... AVRational rate; ///< frame rate in rational form unsigned fps; ///< frame per second; must be consistent with the rate field } AVTimecode; /** * Adjust frame number for NTSC drop frame time code. * * @param framenum frame number to adjust * @param fps frame per second, 30 or 60 * @return adjusted frame number * @warning adjustment is only valid in NTSC 29.97 and 59.94 */ int av_timecode_adjust_ntsc_framenum2(int framenum, int fps); /** * Convert frame number to SMPTE 12M binary representation. * * @param tc timecode data correctly initialized * @param framenum frame number * @return the SMPTE binary representation * * @note Frame number adjustment is automatically done in case of drop timecode, * you do NOT have to call av_timecode_adjust_ntsc_framenum2(). * @note The frame number is relative to tc->start. * @note Color frame (CF), binary group flags (BGF) and biphase mark polarity * correction (PC) bits are set to zero. */ uint32_t av_timecode_get_smpte_from_framenum(const AVTimecode *tc, int framenum); /** * Load timecode string in buf. * * @param buf destination buffer, must be at least AV_TIMECODE_STR_SIZE long * @param tc timecode data correctly initialized * @param framenum frame number * @return the buf parameter * * @note Timecode representation can be a negative timecode and have more than * 24 hours, but will only be honored if the flags are correctly set. * @note The frame number is relative to tc->start. */ char *av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum); /** * Get the timecode string from the SMPTE timecode format. * * @param buf destination buffer, must be at least AV_TIMECODE_STR_SIZE long * @param tcsmpte the 32-bit SMPTE timecode * @param prevent_df prevent the use of a drop flag when it is known the DF bit * is arbitrary * @return the buf parameter */ char *av_timecode_make_smpte_tc_string(char *buf, uint32_t tcsmpte, int prevent_df); /** * Get the timecode string from the 25-bit timecode format (MPEG GOP format). * * @param buf destination buffer, must be at least AV_TIMECODE_STR_SIZE long * @param tc25bit the 25-bits timecode * @return the buf parameter */ char *av_timecode_make_mpeg_tc_string(char *buf, uint32_t tc25bit); /** * Init a timecode struct with the passed parameters. * * @param log_ctx a pointer to an arbitrary struct of which the first field * is a pointer to an AVClass struct (used for av_log) * @param tc pointer to an allocated AVTimecode * @param rate frame rate in rational form * @param flags miscellaneous flags such as drop frame, +24 hours, ... * (see AVTimecodeFlag) * @param frame_start the first frame number * @return 0 on success, AVERROR otherwise */ int av_timecode_init(AVTimecode *tc, AVRational rate, int flags, int frame_start, void *log_ctx); /** * Parse timecode representation (hh:mm:ss[:;.]ff). * * @param log_ctx a pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct (used for av_log). * @param tc pointer to an allocated AVTimecode * @param rate frame rate in rational form * @param str timecode string which will determine the frame start * @return 0 on success, AVERROR otherwise */ int av_timecode_init_from_string(AVTimecode *tc, AVRational rate, const char *str, void *log_ctx); /** * Check if the timecode feature is available for the given frame rate * * @return 0 if supported, <0 otherwise */ int av_timecode_check_frame_rate(AVRational rate); #endif /* AVUTIL_TIMECODE_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/timestamp.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * timestamp utils, mostly useful for debugging/logging purposes */ #ifndef AVUTIL_TIMESTAMP_H #define AVUTIL_TIMESTAMP_H #include "common.h" #if defined(__cplusplus) && !defined(__STDC_FORMAT_MACROS) && !defined(PRId64) #error missing -D__STDC_FORMAT_MACROS / #define __STDC_FORMAT_MACROS #endif #define AV_TS_MAX_STRING_SIZE 32 /** * Fill the provided buffer with a string containing a timestamp * representation. * * @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE * @param ts the timestamp to represent * @return the buffer in input */ static inline char *av_ts_make_string(char *buf, int64_t ts) { if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS"); else snprintf(buf, AV_TS_MAX_STRING_SIZE, "%"PRId64, ts); return buf; } /** * Convenience macro, the return value should be used only directly in * function arguments but never stand-alone. */ #define av_ts2str(ts) av_ts_make_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts) /** * Fill the provided buffer with a string containing a timestamp time * representation. * * @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE * @param ts the timestamp to represent * @param tb the timebase of the timestamp * @return the buffer in input */ static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb) { if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS"); else snprintf(buf, AV_TS_MAX_STRING_SIZE, "%.6g", av_q2d(*tb) * ts); return buf; } /** * Convenience macro, the return value should be used only directly in * function arguments but never stand-alone. */ #define av_ts2timestr(ts, tb) av_ts_make_time_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts, tb) #endif /* AVUTIL_TIMESTAMP_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/version.h ================================================ /* * copyright (c) 2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_VERSION_H #define AVUTIL_VERSION_H #include "macros.h" /** * @defgroup version_utils Library Version Macros * * Useful to check and match library version in order to maintain * backward compatibility. * * @{ */ #define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c) #define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c #define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c) /** * @} */ /** * @file * @ingroup lavu * Libavutil version macros */ /** * @defgroup lavu_ver Version and Build diagnostics * * Macros and function useful to check at compiletime and at runtime * which version of libavutil is in use. * * @{ */ #define LIBAVUTIL_VERSION_MAJOR 52 #define LIBAVUTIL_VERSION_MINOR 66 #define LIBAVUTIL_VERSION_MICRO 100 #define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_VERSION AV_VERSION(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_BUILD LIBAVUTIL_VERSION_INT #define LIBAVUTIL_IDENT "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION) /** * @} * * @defgroup depr_guards Deprecation guards * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. * * @{ */ #ifndef FF_API_GET_BITS_PER_SAMPLE_FMT #define FF_API_GET_BITS_PER_SAMPLE_FMT (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_FIND_OPT #define FF_API_FIND_OPT (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_OLD_AVOPTIONS #define FF_API_OLD_AVOPTIONS (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_PIX_FMT #define FF_API_PIX_FMT (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_CONTEXT_SIZE #define FF_API_CONTEXT_SIZE (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_PIX_FMT_DESC #define FF_API_PIX_FMT_DESC (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_AV_REVERSE #define FF_API_AV_REVERSE (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_AUDIOCONVERT #define FF_API_AUDIOCONVERT (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_CPU_FLAG_MMX2 #define FF_API_CPU_FLAG_MMX2 (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_SAMPLES_UTILS_RETURN_ZERO #define FF_API_SAMPLES_UTILS_RETURN_ZERO (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_LLS_PRIVATE #define FF_API_LLS_PRIVATE (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_LLS1 #define FF_API_LLS1 (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_AVFRAME_LAVC #define FF_API_AVFRAME_LAVC (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_VDPAU #define FF_API_VDPAU (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_GET_CHANNEL_LAYOUT_COMPAT #define FF_API_GET_CHANNEL_LAYOUT_COMPAT (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_OLD_OPENCL #define FF_API_OLD_OPENCL (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_XVMC #define FF_API_XVMC (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_INTFLOAT #define FF_API_INTFLOAT (LIBAVUTIL_VERSION_MAJOR < 54) #endif #ifndef FF_API_OPT_TYPE_METADATA #define FF_API_OPT_TYPE_METADATA (LIBAVUTIL_VERSION_MAJOR < 54) #endif /** * @} */ #endif /* AVUTIL_VERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libavutil/xtea.h ================================================ /* * A 32-bit implementation of the XTEA algorithm * Copyright (c) 2012 Samuel Pitoiset * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_XTEA_H #define AVUTIL_XTEA_H #include /** * @file * @brief Public header for libavutil XTEA algorithm * @defgroup lavu_xtea XTEA * @ingroup lavu_crypto * @{ */ typedef struct AVXTEA { uint32_t key[16]; } AVXTEA; /** * Initialize an AVXTEA context. * * @param ctx an AVXTEA context * @param key a key of 16 bytes used for encryption/decryption */ void av_xtea_init(struct AVXTEA *ctx, const uint8_t key[16]); /** * Encrypt or decrypt a buffer using a previously initialized context. * * @param ctx an AVXTEA context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param iv initialization vector for CBC mode, if NULL then ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_xtea_crypt(struct AVXTEA *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_XTEA_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libswresample/swresample.h ================================================ /* * Copyright (C) 2011-2013 Michael Niedermayer (michaelni@gmx.at) * * This file is part of libswresample * * libswresample is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * libswresample is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with libswresample; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWRESAMPLE_SWRESAMPLE_H #define SWRESAMPLE_SWRESAMPLE_H /** * @file * @ingroup lswr * libswresample public header */ /** * @defgroup lswr Libswresample * @{ * * Libswresample (lswr) is a library that handles audio resampling, sample * format conversion and mixing. * * Interaction with lswr is done through SwrContext, which is * allocated with swr_alloc() or swr_alloc_set_opts(). It is opaque, so all parameters * must be set with the @ref avoptions API. * * For example the following code will setup conversion from planar float sample * format to interleaved signed 16-bit integer, downsampling from 48kHz to * 44.1kHz and downmixing from 5.1 channels to stereo (using the default mixing * matrix): * @code * SwrContext *swr = swr_alloc(); * av_opt_set_channel_layout(swr, "in_channel_layout", AV_CH_LAYOUT_5POINT1, 0); * av_opt_set_channel_layout(swr, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0); * av_opt_set_int(swr, "in_sample_rate", 48000, 0); * av_opt_set_int(swr, "out_sample_rate", 44100, 0); * av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0); * av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0); * @endcode * * Once all values have been set, it must be initialized with swr_init(). If * you need to change the conversion parameters, you can change the parameters * as described above, or by using swr_alloc_set_opts(), then call swr_init() * again. * * The conversion itself is done by repeatedly calling swr_convert(). * Note that the samples may get buffered in swr if you provide insufficient * output space or if sample rate conversion is done, which requires "future" * samples. Samples that do not require future input can be retrieved at any * time by using swr_convert() (in_count can be set to 0). * At the end of conversion the resampling buffer can be flushed by calling * swr_convert() with NULL in and 0 in_count. * * The delay between input and output, can at any time be found by using * swr_get_delay(). * * The following code demonstrates the conversion loop assuming the parameters * from above and caller-defined functions get_input() and handle_output(): * @code * uint8_t **input; * int in_samples; * * while (get_input(&input, &in_samples)) { * uint8_t *output; * int out_samples = av_rescale_rnd(swr_get_delay(swr, 48000) + * in_samples, 44100, 48000, AV_ROUND_UP); * av_samples_alloc(&output, NULL, 2, out_samples, * AV_SAMPLE_FMT_S16, 0); * out_samples = swr_convert(swr, &output, out_samples, * input, in_samples); * handle_output(output, out_samples); * av_freep(&output); * } * @endcode * * When the conversion is finished, the conversion * context and everything associated with it must be freed with swr_free(). * There will be no memory leak if the data is not completely flushed before * swr_free(). */ #include #include "libavutil/samplefmt.h" #include "libswresample/version.h" #if LIBSWRESAMPLE_VERSION_MAJOR < 1 #define SWR_CH_MAX 32 ///< Maximum number of channels #endif #define SWR_FLAG_RESAMPLE 1 ///< Force resampling even if equal sample rate //TODO use int resample ? //long term TODO can we enable this dynamically? enum SwrDitherType { SWR_DITHER_NONE = 0, SWR_DITHER_RECTANGULAR, SWR_DITHER_TRIANGULAR, SWR_DITHER_TRIANGULAR_HIGHPASS, SWR_DITHER_NS = 64, ///< not part of API/ABI SWR_DITHER_NS_LIPSHITZ, SWR_DITHER_NS_F_WEIGHTED, SWR_DITHER_NS_MODIFIED_E_WEIGHTED, SWR_DITHER_NS_IMPROVED_E_WEIGHTED, SWR_DITHER_NS_SHIBATA, SWR_DITHER_NS_LOW_SHIBATA, SWR_DITHER_NS_HIGH_SHIBATA, SWR_DITHER_NB, ///< not part of API/ABI }; /** Resampling Engines */ enum SwrEngine { SWR_ENGINE_SWR, /**< SW Resampler */ SWR_ENGINE_SOXR, /**< SoX Resampler */ SWR_ENGINE_NB, ///< not part of API/ABI }; /** Resampling Filter Types */ enum SwrFilterType { SWR_FILTER_TYPE_CUBIC, /**< Cubic */ SWR_FILTER_TYPE_BLACKMAN_NUTTALL, /**< Blackman Nuttall Windowed Sinc */ SWR_FILTER_TYPE_KAISER, /**< Kaiser Windowed Sinc */ }; typedef struct SwrContext SwrContext; /** * Get the AVClass for swrContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *swr_get_class(void); /** * Allocate SwrContext. * * If you use this function you will need to set the parameters (manually or * with swr_alloc_set_opts()) before calling swr_init(). * * @see swr_alloc_set_opts(), swr_init(), swr_free() * @return NULL on error, allocated context otherwise */ struct SwrContext *swr_alloc(void); /** * Initialize context after user parameters have been set. * * @return AVERROR error code in case of failure. */ int swr_init(struct SwrContext *s); /** * Check whether an swr context has been initialized or not. * * @return positive if it has been initialized, 0 if not initialized */ int swr_is_initialized(struct SwrContext *s); /** * Allocate SwrContext if needed and set/reset common parameters. * * This function does not require s to be allocated with swr_alloc(). On the * other hand, swr_alloc() can use swr_alloc_set_opts() to set the parameters * on the allocated context. * * @param s Swr context, can be NULL * @param out_ch_layout output channel layout (AV_CH_LAYOUT_*) * @param out_sample_fmt output sample format (AV_SAMPLE_FMT_*). * @param out_sample_rate output sample rate (frequency in Hz) * @param in_ch_layout input channel layout (AV_CH_LAYOUT_*) * @param in_sample_fmt input sample format (AV_SAMPLE_FMT_*). * @param in_sample_rate input sample rate (frequency in Hz) * @param log_offset logging level offset * @param log_ctx parent logging context, can be NULL * * @see swr_init(), swr_free() * @return NULL on error, allocated context otherwise */ struct SwrContext *swr_alloc_set_opts(struct SwrContext *s, int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate, int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate, int log_offset, void *log_ctx); /** * Free the given SwrContext and set the pointer to NULL. */ void swr_free(struct SwrContext **s); /** * Convert audio. * * in and in_count can be set to 0 to flush the last few samples out at the * end. * * If more input is provided than output space then the input will be buffered. * You can avoid this buffering by providing more output space than input. * Convertion will run directly without copying whenever possible. * * @param s allocated Swr context, with parameters set * @param out output buffers, only the first one need be set in case of packed audio * @param out_count amount of space available for output in samples per channel * @param in input buffers, only the first one need to be set in case of packed audio * @param in_count number of input samples available in one channel * * @return number of samples output per channel, negative value on error */ int swr_convert(struct SwrContext *s, uint8_t **out, int out_count, const uint8_t **in , int in_count); /** * Convert the next timestamp from input to output * timestamps are in 1/(in_sample_rate * out_sample_rate) units. * * @note There are 2 slightly differently behaving modes. * First is when automatic timestamp compensation is not used, (min_compensation >= FLT_MAX) * in this case timestamps will be passed through with delays compensated * Second is when automatic timestamp compensation is used, (min_compensation < FLT_MAX) * in this case the output timestamps will match output sample numbers * * @param pts timestamp for the next input sample, INT64_MIN if unknown * @return the output timestamp for the next output sample */ int64_t swr_next_pts(struct SwrContext *s, int64_t pts); /** * Activate resampling compensation. */ int swr_set_compensation(struct SwrContext *s, int sample_delta, int compensation_distance); /** * Set a customized input channel mapping. * * @param s allocated Swr context, not yet initialized * @param channel_map customized input channel mapping (array of channel * indexes, -1 for a muted channel) * @return AVERROR error code in case of failure. */ int swr_set_channel_mapping(struct SwrContext *s, const int *channel_map); /** * Set a customized remix matrix. * * @param s allocated Swr context, not yet initialized * @param matrix remix coefficients; matrix[i + stride * o] is * the weight of input channel i in output channel o * @param stride offset between lines of the matrix * @return AVERROR error code in case of failure. */ int swr_set_matrix(struct SwrContext *s, const double *matrix, int stride); /** * Drops the specified number of output samples. */ int swr_drop_output(struct SwrContext *s, int count); /** * Injects the specified number of silence samples. */ int swr_inject_silence(struct SwrContext *s, int count); /** * Gets the delay the next input sample will experience relative to the next output sample. * * Swresample can buffer data if more input has been provided than available * output space, also converting between sample rates needs a delay. * This function returns the sum of all such delays. * The exact delay is not necessarily an integer value in either input or * output sample rate. Especially when downsampling by a large value, the * output sample rate may be a poor choice to represent the delay, similarly * for upsampling and the input sample rate. * * @param s swr context * @param base timebase in which the returned delay will be * if its set to 1 the returned delay is in seconds * if its set to 1000 the returned delay is in milli seconds * if its set to the input sample rate then the returned delay is in input samples * if its set to the output sample rate then the returned delay is in output samples * an exact rounding free delay can be found by using LCM(in_sample_rate, out_sample_rate) * @returns the delay in 1/base units. */ int64_t swr_get_delay(struct SwrContext *s, int64_t base); /** * Return the LIBSWRESAMPLE_VERSION_INT constant. */ unsigned swresample_version(void); /** * Return the swr build-time configuration. */ const char *swresample_configuration(void); /** * Return the swr license. */ const char *swresample_license(void); /** * @} */ #endif /* SWRESAMPLE_SWRESAMPLE_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libswresample/version.h ================================================ /* * Version macros. * * This file is part of libswresample * * libswresample is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * libswresample is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with libswresample; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWR_VERSION_H #define SWR_VERSION_H /** * @file * Libswresample version macros */ #include "libavutil/avutil.h" #define LIBSWRESAMPLE_VERSION_MAJOR 0 #define LIBSWRESAMPLE_VERSION_MINOR 18 #define LIBSWRESAMPLE_VERSION_MICRO 100 #define LIBSWRESAMPLE_VERSION_INT AV_VERSION_INT(LIBSWRESAMPLE_VERSION_MAJOR, \ LIBSWRESAMPLE_VERSION_MINOR, \ LIBSWRESAMPLE_VERSION_MICRO) #define LIBSWRESAMPLE_VERSION AV_VERSION(LIBSWRESAMPLE_VERSION_MAJOR, \ LIBSWRESAMPLE_VERSION_MINOR, \ LIBSWRESAMPLE_VERSION_MICRO) #define LIBSWRESAMPLE_BUILD LIBSWRESAMPLE_VERSION_INT #define LIBSWRESAMPLE_IDENT "SwR" AV_STRINGIFY(LIBSWRESAMPLE_VERSION) #endif /* SWR_VERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libswscale/swscale.h ================================================ /* * Copyright (C) 2001-2011 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWSCALE_SWSCALE_H #define SWSCALE_SWSCALE_H /** * @file * @ingroup libsws * external API header */ #include #include "libavutil/avutil.h" #include "libavutil/log.h" #include "libavutil/pixfmt.h" #include "version.h" /** * @defgroup libsws Color conversion and scaling * @{ * * Return the LIBSWSCALE_VERSION_INT constant. */ unsigned swscale_version(void); /** * Return the libswscale build-time configuration. */ const char *swscale_configuration(void); /** * Return the libswscale license. */ const char *swscale_license(void); /* values for the flags, the stuff on the command line is different */ #define SWS_FAST_BILINEAR 1 #define SWS_BILINEAR 2 #define SWS_BICUBIC 4 #define SWS_X 8 #define SWS_POINT 0x10 #define SWS_AREA 0x20 #define SWS_BICUBLIN 0x40 #define SWS_GAUSS 0x80 #define SWS_SINC 0x100 #define SWS_LANCZOS 0x200 #define SWS_SPLINE 0x400 #define SWS_SRC_V_CHR_DROP_MASK 0x30000 #define SWS_SRC_V_CHR_DROP_SHIFT 16 #define SWS_PARAM_DEFAULT 123456 #define SWS_PRINT_INFO 0x1000 //the following 3 flags are not completely implemented //internal chrominace subsampling info #define SWS_FULL_CHR_H_INT 0x2000 //input subsampling info #define SWS_FULL_CHR_H_INP 0x4000 #define SWS_DIRECT_BGR 0x8000 #define SWS_ACCURATE_RND 0x40000 #define SWS_BITEXACT 0x80000 #define SWS_ERROR_DIFFUSION 0x800000 #if FF_API_SWS_CPU_CAPS /** * CPU caps are autodetected now, those flags * are only provided for API compatibility. */ #define SWS_CPU_CAPS_MMX 0x80000000 #define SWS_CPU_CAPS_MMXEXT 0x20000000 #define SWS_CPU_CAPS_MMX2 0x20000000 #define SWS_CPU_CAPS_3DNOW 0x40000000 #define SWS_CPU_CAPS_ALTIVEC 0x10000000 #define SWS_CPU_CAPS_BFIN 0x01000000 #define SWS_CPU_CAPS_SSE2 0x02000000 #endif #define SWS_MAX_REDUCE_CUTOFF 0.002 #define SWS_CS_ITU709 1 #define SWS_CS_FCC 4 #define SWS_CS_ITU601 5 #define SWS_CS_ITU624 5 #define SWS_CS_SMPTE170M 5 #define SWS_CS_SMPTE240M 7 #define SWS_CS_DEFAULT 5 /** * Return a pointer to yuv<->rgb coefficients for the given colorspace * suitable for sws_setColorspaceDetails(). * * @param colorspace One of the SWS_CS_* macros. If invalid, * SWS_CS_DEFAULT is used. */ const int *sws_getCoefficients(int colorspace); // when used for filters they must have an odd number of elements // coeffs cannot be shared between vectors typedef struct SwsVector { double *coeff; ///< pointer to the list of coefficients int length; ///< number of coefficients in the vector } SwsVector; // vectors can be shared typedef struct SwsFilter { SwsVector *lumH; SwsVector *lumV; SwsVector *chrH; SwsVector *chrV; } SwsFilter; struct SwsContext; /** * Return a positive value if pix_fmt is a supported input format, 0 * otherwise. */ int sws_isSupportedInput(enum AVPixelFormat pix_fmt); /** * Return a positive value if pix_fmt is a supported output format, 0 * otherwise. */ int sws_isSupportedOutput(enum AVPixelFormat pix_fmt); /** * @param[in] pix_fmt the pixel format * @return a positive value if an endianness conversion for pix_fmt is * supported, 0 otherwise. */ int sws_isSupportedEndiannessConversion(enum AVPixelFormat pix_fmt); /** * Allocate an empty SwsContext. This must be filled and passed to * sws_init_context(). For filling see AVOptions, options.c and * sws_setColorspaceDetails(). */ struct SwsContext *sws_alloc_context(void); /** * Initialize the swscaler context sws_context. * * @return zero or positive value on success, a negative value on * error */ int sws_init_context(struct SwsContext *sws_context, SwsFilter *srcFilter, SwsFilter *dstFilter); /** * Free the swscaler context swsContext. * If swsContext is NULL, then does nothing. */ void sws_freeContext(struct SwsContext *swsContext); #if FF_API_SWS_GETCONTEXT /** * Allocate and return an SwsContext. You need it to perform * scaling/conversion operations using sws_scale(). * * @param srcW the width of the source image * @param srcH the height of the source image * @param srcFormat the source image format * @param dstW the width of the destination image * @param dstH the height of the destination image * @param dstFormat the destination image format * @param flags specify which algorithm and options to use for rescaling * @return a pointer to an allocated context, or NULL in case of error * @note this function is to be removed after a saner alternative is * written * @deprecated Use sws_getCachedContext() instead. */ struct SwsContext *sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param); #endif /** * Scale the image slice in srcSlice and put the resulting scaled * slice in the image in dst. A slice is a sequence of consecutive * rows in an image. * * Slices have to be provided in sequential order, either in * top-bottom or bottom-top order. If slices are provided in * non-sequential order the behavior of the function is undefined. * * @param c the scaling context previously created with * sws_getContext() * @param srcSlice the array containing the pointers to the planes of * the source slice * @param srcStride the array containing the strides for each plane of * the source image * @param srcSliceY the position in the source image of the slice to * process, that is the number (counted starting from * zero) in the image of the first row of the slice * @param srcSliceH the height of the source slice, that is the number * of rows in the slice * @param dst the array containing the pointers to the planes of * the destination image * @param dstStride the array containing the strides for each plane of * the destination image * @return the height of the output slice */ int sws_scale(struct SwsContext *c, const uint8_t *const srcSlice[], const int srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const int dstStride[]); /** * @param dstRange flag indicating the while-black range of the output (1=jpeg / 0=mpeg) * @param srcRange flag indicating the while-black range of the input (1=jpeg / 0=mpeg) * @param table the yuv2rgb coefficients describing the output yuv space, normally ff_yuv2rgb_coeffs[x] * @param inv_table the yuv2rgb coefficients describing the input yuv space, normally ff_yuv2rgb_coeffs[x] * @param brightness 16.16 fixed point brightness correction * @param contrast 16.16 fixed point contrast correction * @param saturation 16.16 fixed point saturation correction * @return -1 if not supported */ int sws_setColorspaceDetails(struct SwsContext *c, const int inv_table[4], int srcRange, const int table[4], int dstRange, int brightness, int contrast, int saturation); /** * @return -1 if not supported */ int sws_getColorspaceDetails(struct SwsContext *c, int **inv_table, int *srcRange, int **table, int *dstRange, int *brightness, int *contrast, int *saturation); /** * Allocate and return an uninitialized vector with length coefficients. */ SwsVector *sws_allocVec(int length); /** * Return a normalized Gaussian curve used to filter stuff * quality = 3 is high quality, lower is lower quality. */ SwsVector *sws_getGaussianVec(double variance, double quality); /** * Allocate and return a vector with length coefficients, all * with the same value c. */ SwsVector *sws_getConstVec(double c, int length); /** * Allocate and return a vector with just one coefficient, with * value 1.0. */ SwsVector *sws_getIdentityVec(void); /** * Scale all the coefficients of a by the scalar value. */ void sws_scaleVec(SwsVector *a, double scalar); /** * Scale all the coefficients of a so that their sum equals height. */ void sws_normalizeVec(SwsVector *a, double height); void sws_convVec(SwsVector *a, SwsVector *b); void sws_addVec(SwsVector *a, SwsVector *b); void sws_subVec(SwsVector *a, SwsVector *b); void sws_shiftVec(SwsVector *a, int shift); /** * Allocate and return a clone of the vector a, that is a vector * with the same coefficients as a. */ SwsVector *sws_cloneVec(SwsVector *a); /** * Print with av_log() a textual representation of the vector a * if log_level <= av_log_level. */ void sws_printVec2(SwsVector *a, AVClass *log_ctx, int log_level); void sws_freeVec(SwsVector *a); SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur, float lumaSharpen, float chromaSharpen, float chromaHShift, float chromaVShift, int verbose); void sws_freeFilter(SwsFilter *filter); /** * Check if context can be reused, otherwise reallocate a new one. * * If context is NULL, just calls sws_getContext() to get a new * context. Otherwise, checks if the parameters are the ones already * saved in context. If that is the case, returns the current * context. Otherwise, frees context and gets a new context with * the new parameters. * * Be warned that srcFilter and dstFilter are not checked, they * are assumed to remain the same. */ struct SwsContext *sws_getCachedContext(struct SwsContext *context, int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param); /** * Convert an 8-bit paletted frame into a frame with a color depth of 32 bits. * * The output frame will have the same packed format as the palette. * * @param src source frame buffer * @param dst destination frame buffer * @param num_pixels number of pixels to convert * @param palette array with [256] entries, which must match color arrangement (RGB or BGR) of src */ void sws_convertPalette8ToPacked32(const uint8_t *src, uint8_t *dst, int num_pixels, const uint8_t *palette); /** * Convert an 8-bit paletted frame into a frame with a color depth of 24 bits. * * With the palette format "ABCD", the destination frame ends up with the format "ABC". * * @param src source frame buffer * @param dst destination frame buffer * @param num_pixels number of pixels to convert * @param palette array with [256] entries, which must match color arrangement (RGB or BGR) of src */ void sws_convertPalette8ToPacked24(const uint8_t *src, uint8_t *dst, int num_pixels, const uint8_t *palette); /** * Get the AVClass for swsContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *sws_get_class(void); /** * @} */ #endif /* SWSCALE_SWSCALE_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/libswscale/version.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWSCALE_VERSION_H #define SWSCALE_VERSION_H /** * @file * swscale version macros */ #include "libavutil/version.h" #define LIBSWSCALE_VERSION_MAJOR 2 #define LIBSWSCALE_VERSION_MINOR 5 #define LIBSWSCALE_VERSION_MICRO 102 #define LIBSWSCALE_VERSION_INT AV_VERSION_INT(LIBSWSCALE_VERSION_MAJOR, \ LIBSWSCALE_VERSION_MINOR, \ LIBSWSCALE_VERSION_MICRO) #define LIBSWSCALE_VERSION AV_VERSION(LIBSWSCALE_VERSION_MAJOR, \ LIBSWSCALE_VERSION_MINOR, \ LIBSWSCALE_VERSION_MICRO) #define LIBSWSCALE_BUILD LIBSWSCALE_VERSION_INT #define LIBSWSCALE_IDENT "SwS" AV_STRINGIFY(LIBSWSCALE_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #ifndef FF_API_SWS_GETCONTEXT #define FF_API_SWS_GETCONTEXT (LIBSWSCALE_VERSION_MAJOR < 3) #endif #ifndef FF_API_SWS_CPU_CAPS #define FF_API_SWS_CPU_CAPS (LIBSWSCALE_VERSION_MAJOR < 3) #endif #ifndef FF_API_SWS_FORMAT_NAME #define FF_API_SWS_FORMAT_NAME (LIBSWSCALE_VERSION_MAJOR < 3) #endif #endif /* SWSCALE_VERSION_H */ ================================================ FILE: src/3rdparty/ffmpeg/include/stdint.h ================================================ // ISO C9x compliant stdint.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006-2008 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ #if _MSC_VER > 1000 #pragma once #endif #include // For Visual Studio 6 in C++ mode and for many Visual Studio versions when // compiling for ARM we should wrap include with 'extern "C++" {}' // or compiler give many errors like this: // error C2733: second C linkage of overloaded function 'wmemchr' not allowed #ifdef __cplusplus extern "C" { #endif # include #ifdef __cplusplus } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 # define _W64 __w64 # else # define _W64 # endif #endif // 7.18.1 Integer types // 7.18.1.1 Exact-width integer types // Visual Studio 6 and Embedded Visual C++ 4 doesn't // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #else typedef signed __int8 int8_t; typedef signed __int16 int16_t; typedef signed __int32 int32_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; #endif typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else // _WIN64 ][ typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types typedef int64_t intmax_t; typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) #define INT8_MAX _I8_MAX #define INT16_MIN ((int16_t)_I16_MIN) #define INT16_MAX _I16_MAX #define INT32_MIN ((int32_t)_I32_MIN) #define INT32_MAX _I32_MAX #define INT64_MIN ((int64_t)_I64_MIN) #define INT64_MAX _I64_MAX #define UINT8_MAX _UI8_MAX #define UINT16_MAX _UI16_MAX #define UINT32_MAX _UI32_MAX #define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types #define INT_FAST8_MIN INT8_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MIN INT16_MIN #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MIN INT32_MIN #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MIN INT64_MIN #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ # define INTPTR_MIN INT64_MIN # define INTPTR_MAX INT64_MAX # define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ # define INTPTR_MIN INT32_MIN # define INTPTR_MAX INT32_MAX # define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ # define PTRDIFF_MIN _I64_MIN # define PTRDIFF_MAX _I64_MAX #else // _WIN64 ][ # define PTRDIFF_MIN _I32_MIN # define PTRDIFF_MAX _I32_MAX #endif // _WIN64 ] #define SIG_ATOMIC_MIN INT_MIN #define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ # ifdef _WIN64 // [ # define SIZE_MAX _UI64_MAX # else // _WIN64 ][ # define SIZE_MAX _UI32_MAX # endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in #ifndef WCHAR_MIN // [ # define WCHAR_MIN 0 #endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ # define WCHAR_MAX _UI16_MAX #endif // WCHAR_MAX ] #define WINT_MIN 0 #define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants #define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 #define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants #define INTMAX_C INT64_C #define UINTMAX_C UINT64_C #endif // __STDC_CONSTANT_MACROS ] #endif // _MSC_STDINT_H_ ] ================================================ FILE: src/3rdparty/glut/include/GL/glut.h ================================================ #ifndef __glut_h__ #define __glut_h__ /* Copyright (c) Mark J. Kilgard, 1994, 1995, 1996, 1998. */ /* This program is freely distributable without licensing fees and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ #if defined(_WIN32) /* GLUT 3.7 now tries to avoid including to avoid name space pollution, but Win32's needs APIENTRY and WINGDIAPI defined properly. */ # if 0 /* This would put tons of macros and crap in our clean name space. */ # define WIN32_LEAN_AND_MEAN # include # else /* XXX This is from Win32's */ # ifndef APIENTRY # define GLUT_APIENTRY_DEFINED # if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__) || defined(__LCC__) # define APIENTRY __stdcall # else # define APIENTRY # endif # endif /* XXX This is from Win32's */ # ifndef CALLBACK # if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS) || defined(__LCC__) # define CALLBACK __stdcall # else # define CALLBACK # endif # endif /* XXX Hack for lcc compiler. It doesn't support __declspec(dllimport), just __stdcall. */ # if defined( __LCC__ ) # undef WINGDIAPI # define WINGDIAPI __stdcall # else /* XXX This is from Win32's and */ # ifndef WINGDIAPI # define GLUT_WINGDIAPI_DEFINED # define WINGDIAPI __declspec(dllimport) # endif # endif /* XXX This is from Win32's */ # ifndef _WCHAR_T_DEFINED typedef unsigned short wchar_t; # define _WCHAR_T_DEFINED # endif # endif /* To disable automatic library usage for GLUT, define GLUT_NO_LIB_PRAGMA in your compile preprocessor options. */ # if !defined(GLUT_BUILDING_LIB) && !defined(GLUT_NO_LIB_PRAGMA) # pragma comment (lib, "winmm.lib") /* link with Windows MultiMedia lib */ /* To enable automatic SGI OpenGL for Windows library usage for GLUT, define GLUT_USE_SGI_OPENGL in your compile preprocessor options. */ # ifdef GLUT_USE_SGI_OPENGL # pragma comment (lib, "opengl.lib") /* link with SGI OpenGL for Windows lib */ # pragma comment (lib, "glu.lib") /* link with SGI OpenGL Utility lib */ # pragma comment (lib, "glut.lib") /* link with Win32 GLUT for SGI OpenGL lib */ # else # pragma comment (lib, "opengl32.lib") /* link with Microsoft OpenGL lib */ # pragma comment (lib, "glu32.lib") /* link with Microsoft OpenGL Utility lib */ # pragma comment (lib, "glut32.lib") /* link with Win32 GLUT lib */ # endif # endif /* To disable supression of annoying warnings about floats being promoted to doubles, define GLUT_NO_WARNING_DISABLE in your compile preprocessor options. */ # ifndef GLUT_NO_WARNING_DISABLE # pragma warning (disable:4244) /* Disable bogus VC++ 4.2 conversion warnings. */ # pragma warning (disable:4305) /* VC++ 5.0 version of above warning. */ # endif /* Win32 has an annoying issue where there are multiple C run-time libraries (CRTs). If the executable is linked with a different CRT from the GLUT DLL, the GLUT DLL will not share the same CRT static data seen by the executable. In particular, atexit callbacks registered in the executable will not be called if GLUT calls its (different) exit routine). GLUT is typically built with the "/MD" option (the CRT with multithreading DLL support), but the Visual C++ linker default is "/ML" (the single threaded CRT). One workaround to this issue is requiring users to always link with the same CRT as GLUT is compiled with. That requires users supply a non-standard option. GLUT 3.7 has its own built-in workaround where the executable's "exit" function pointer is covertly passed to GLUT. GLUT then calls the executable's exit function pointer to ensure that any "atexit" calls registered by the application are called if GLUT needs to exit. Note that the __glut*WithExit routines should NEVER be called directly. To avoid the atexit workaround, #define GLUT_DISABLE_ATEXIT_HACK. */ /* XXX This is from Win32's */ # if !defined(_MSC_VER) && !defined(__cdecl) /* Define __cdecl for non-Microsoft compilers. */ # define __cdecl # define GLUT_DEFINED___CDECL # endif # ifndef _CRTIMP # ifdef _NTSDK /* Definition compatible with NT SDK */ # define _CRTIMP # else /* Current definition */ # ifdef _DLL # define _CRTIMP __declspec(dllimport) # else # define _CRTIMP # endif # endif # define GLUT_DEFINED__CRTIMP # endif /* GLUT API entry point declarations for Win32. */ # ifdef GLUT_BUILDING_LIB # define GLUTAPI __declspec(dllexport) # else # ifdef _DLL # define GLUTAPI __declspec(dllimport) # else # define GLUTAPI extern # endif # endif /* GLUT callback calling convention for Win32. */ # define GLUTCALLBACK __cdecl #endif /* _WIN32 */ #include #include #ifdef __cplusplus extern "C" { #endif #if defined(_WIN32) # ifndef GLUT_BUILDING_LIB extern _CRTIMP void __cdecl exit(int); # endif #else /* non-Win32 case. */ /* Define APIENTRY and CALLBACK to nothing if we aren't on Win32. */ # define APIENTRY # define GLUT_APIENTRY_DEFINED # define CALLBACK /* Define GLUTAPI and GLUTCALLBACK as below if we aren't on Win32. */ # define GLUTAPI extern # define GLUTCALLBACK /* Prototype exit for the non-Win32 case (see above). */ extern void exit(int); #endif /** GLUT API revision history: GLUT_API_VERSION is updated to reflect incompatible GLUT API changes (interface changes, semantic changes, deletions, or additions). GLUT_API_VERSION=1 First public release of GLUT. 11/29/94 GLUT_API_VERSION=2 Added support for OpenGL/GLX multisampling, extension. Supports new input devices like tablet, dial and button box, and Spaceball. Easy to query OpenGL extensions. GLUT_API_VERSION=3 glutMenuStatus added. GLUT_API_VERSION=4 glutInitDisplayString, glutWarpPointer, glutBitmapLength, glutStrokeLength, glutWindowStatusFunc, dynamic video resize subAPI, glutPostWindowRedisplay, glutKeyboardUpFunc, glutSpecialUpFunc, glutIgnoreKeyRepeat, glutSetKeyRepeat, glutJoystickFunc, glutForceJoystickFunc (NOT FINALIZED!). **/ #ifndef GLUT_API_VERSION /* allow this to be overriden */ #define GLUT_API_VERSION 3 #endif /** GLUT implementation revision history: GLUT_XLIB_IMPLEMENTATION is updated to reflect both GLUT API revisions and implementation revisions (ie, bug fixes). GLUT_XLIB_IMPLEMENTATION=1 mjk's first public release of GLUT Xlib-based implementation. 11/29/94 GLUT_XLIB_IMPLEMENTATION=2 mjk's second public release of GLUT Xlib-based implementation providing GLUT version 2 interfaces. GLUT_XLIB_IMPLEMENTATION=3 mjk's GLUT 2.2 images. 4/17/95 GLUT_XLIB_IMPLEMENTATION=4 mjk's GLUT 2.3 images. 6/?/95 GLUT_XLIB_IMPLEMENTATION=5 mjk's GLUT 3.0 images. 10/?/95 GLUT_XLIB_IMPLEMENTATION=7 mjk's GLUT 3.1+ with glutWarpPoitner. 7/24/96 GLUT_XLIB_IMPLEMENTATION=8 mjk's GLUT 3.1+ with glutWarpPoitner and video resize. 1/3/97 GLUT_XLIB_IMPLEMENTATION=9 mjk's GLUT 3.4 release with early GLUT 4 routines. GLUT_XLIB_IMPLEMENTATION=11 Mesa 2.5's GLUT 3.6 release. GLUT_XLIB_IMPLEMENTATION=12 mjk's GLUT 3.6 release with early GLUT 4 routines + signal handling. GLUT_XLIB_IMPLEMENTATION=13 mjk's GLUT 3.7 beta with GameGLUT support. GLUT_XLIB_IMPLEMENTATION=14 mjk's GLUT 3.7 beta with f90gl friend interface. GLUT_XLIB_IMPLEMENTATION=15 mjk's GLUT 3.7 beta sync'ed with Mesa **/ #ifndef GLUT_XLIB_IMPLEMENTATION /* Allow this to be overriden. */ #define GLUT_XLIB_IMPLEMENTATION 15 #endif /* Display mode bit masks. */ #define GLUT_RGB 0 #define GLUT_RGBA GLUT_RGB #define GLUT_INDEX 1 #define GLUT_SINGLE 0 #define GLUT_DOUBLE 2 #define GLUT_ACCUM 4 #define GLUT_ALPHA 8 #define GLUT_DEPTH 16 #define GLUT_STENCIL 32 #if (GLUT_API_VERSION >= 2) #define GLUT_MULTISAMPLE 128 #define GLUT_STEREO 256 #endif #if (GLUT_API_VERSION >= 3) #define GLUT_LUMINANCE 512 #endif /* Mouse buttons. */ #define GLUT_LEFT_BUTTON 0 #define GLUT_MIDDLE_BUTTON 1 #define GLUT_RIGHT_BUTTON 2 /* Mouse button state. */ #define GLUT_DOWN 0 #define GLUT_UP 1 #if (GLUT_API_VERSION >= 2) /* function keys */ #define GLUT_KEY_F1 1 #define GLUT_KEY_F2 2 #define GLUT_KEY_F3 3 #define GLUT_KEY_F4 4 #define GLUT_KEY_F5 5 #define GLUT_KEY_F6 6 #define GLUT_KEY_F7 7 #define GLUT_KEY_F8 8 #define GLUT_KEY_F9 9 #define GLUT_KEY_F10 10 #define GLUT_KEY_F11 11 #define GLUT_KEY_F12 12 /* directional keys */ #define GLUT_KEY_LEFT 100 #define GLUT_KEY_UP 101 #define GLUT_KEY_RIGHT 102 #define GLUT_KEY_DOWN 103 #define GLUT_KEY_PAGE_UP 104 #define GLUT_KEY_PAGE_DOWN 105 #define GLUT_KEY_HOME 106 #define GLUT_KEY_END 107 #define GLUT_KEY_INSERT 108 #endif /* Entry/exit state. */ #define GLUT_LEFT 0 #define GLUT_ENTERED 1 /* Menu usage state. */ #define GLUT_MENU_NOT_IN_USE 0 #define GLUT_MENU_IN_USE 1 /* Visibility state. */ #define GLUT_NOT_VISIBLE 0 #define GLUT_VISIBLE 1 /* Window status state. */ #define GLUT_HIDDEN 0 #define GLUT_FULLY_RETAINED 1 #define GLUT_PARTIALLY_RETAINED 2 #define GLUT_FULLY_COVERED 3 /* Color index component selection values. */ #define GLUT_RED 0 #define GLUT_GREEN 1 #define GLUT_BLUE 2 #if defined(_WIN32) /* Stroke font constants (use these in GLUT program). */ #define GLUT_STROKE_ROMAN ((void*)0) #define GLUT_STROKE_MONO_ROMAN ((void*)1) /* Bitmap font constants (use these in GLUT program). */ #define GLUT_BITMAP_9_BY_15 ((void*)2) #define GLUT_BITMAP_8_BY_13 ((void*)3) #define GLUT_BITMAP_TIMES_ROMAN_10 ((void*)4) #define GLUT_BITMAP_TIMES_ROMAN_24 ((void*)5) #if (GLUT_API_VERSION >= 3) #define GLUT_BITMAP_HELVETICA_10 ((void*)6) #define GLUT_BITMAP_HELVETICA_12 ((void*)7) #define GLUT_BITMAP_HELVETICA_18 ((void*)8) #endif #else /* Stroke font opaque addresses (use constants instead in source code). */ GLUTAPI void *glutStrokeRoman; GLUTAPI void *glutStrokeMonoRoman; /* Stroke font constants (use these in GLUT program). */ #define GLUT_STROKE_ROMAN (&glutStrokeRoman) #define GLUT_STROKE_MONO_ROMAN (&glutStrokeMonoRoman) /* Bitmap font opaque addresses (use constants instead in source code). */ GLUTAPI void *glutBitmap9By15; GLUTAPI void *glutBitmap8By13; GLUTAPI void *glutBitmapTimesRoman10; GLUTAPI void *glutBitmapTimesRoman24; GLUTAPI void *glutBitmapHelvetica10; GLUTAPI void *glutBitmapHelvetica12; GLUTAPI void *glutBitmapHelvetica18; /* Bitmap font constants (use these in GLUT program). */ #define GLUT_BITMAP_9_BY_15 (&glutBitmap9By15) #define GLUT_BITMAP_8_BY_13 (&glutBitmap8By13) #define GLUT_BITMAP_TIMES_ROMAN_10 (&glutBitmapTimesRoman10) #define GLUT_BITMAP_TIMES_ROMAN_24 (&glutBitmapTimesRoman24) #if (GLUT_API_VERSION >= 3) #define GLUT_BITMAP_HELVETICA_10 (&glutBitmapHelvetica10) #define GLUT_BITMAP_HELVETICA_12 (&glutBitmapHelvetica12) #define GLUT_BITMAP_HELVETICA_18 (&glutBitmapHelvetica18) #endif #endif /* glutGet parameters. */ #define GLUT_WINDOW_X ((GLenum) 100) #define GLUT_WINDOW_Y ((GLenum) 101) #define GLUT_WINDOW_WIDTH ((GLenum) 102) #define GLUT_WINDOW_HEIGHT ((GLenum) 103) #define GLUT_WINDOW_BUFFER_SIZE ((GLenum) 104) #define GLUT_WINDOW_STENCIL_SIZE ((GLenum) 105) #define GLUT_WINDOW_DEPTH_SIZE ((GLenum) 106) #define GLUT_WINDOW_RED_SIZE ((GLenum) 107) #define GLUT_WINDOW_GREEN_SIZE ((GLenum) 108) #define GLUT_WINDOW_BLUE_SIZE ((GLenum) 109) #define GLUT_WINDOW_ALPHA_SIZE ((GLenum) 110) #define GLUT_WINDOW_ACCUM_RED_SIZE ((GLenum) 111) #define GLUT_WINDOW_ACCUM_GREEN_SIZE ((GLenum) 112) #define GLUT_WINDOW_ACCUM_BLUE_SIZE ((GLenum) 113) #define GLUT_WINDOW_ACCUM_ALPHA_SIZE ((GLenum) 114) #define GLUT_WINDOW_DOUBLEBUFFER ((GLenum) 115) #define GLUT_WINDOW_RGBA ((GLenum) 116) #define GLUT_WINDOW_PARENT ((GLenum) 117) #define GLUT_WINDOW_NUM_CHILDREN ((GLenum) 118) #define GLUT_WINDOW_COLORMAP_SIZE ((GLenum) 119) #if (GLUT_API_VERSION >= 2) #define GLUT_WINDOW_NUM_SAMPLES ((GLenum) 120) #define GLUT_WINDOW_STEREO ((GLenum) 121) #endif #if (GLUT_API_VERSION >= 3) #define GLUT_WINDOW_CURSOR ((GLenum) 122) #endif #define GLUT_SCREEN_WIDTH ((GLenum) 200) #define GLUT_SCREEN_HEIGHT ((GLenum) 201) #define GLUT_SCREEN_WIDTH_MM ((GLenum) 202) #define GLUT_SCREEN_HEIGHT_MM ((GLenum) 203) #define GLUT_MENU_NUM_ITEMS ((GLenum) 300) #define GLUT_DISPLAY_MODE_POSSIBLE ((GLenum) 400) #define GLUT_INIT_WINDOW_X ((GLenum) 500) #define GLUT_INIT_WINDOW_Y ((GLenum) 501) #define GLUT_INIT_WINDOW_WIDTH ((GLenum) 502) #define GLUT_INIT_WINDOW_HEIGHT ((GLenum) 503) #define GLUT_INIT_DISPLAY_MODE ((GLenum) 504) #if (GLUT_API_VERSION >= 2) #define GLUT_ELAPSED_TIME ((GLenum) 700) #endif #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13) #define GLUT_WINDOW_FORMAT_ID ((GLenum) 123) #endif #if (GLUT_API_VERSION >= 2) /* glutDeviceGet parameters. */ #define GLUT_HAS_KEYBOARD ((GLenum) 600) #define GLUT_HAS_MOUSE ((GLenum) 601) #define GLUT_HAS_SPACEBALL ((GLenum) 602) #define GLUT_HAS_DIAL_AND_BUTTON_BOX ((GLenum) 603) #define GLUT_HAS_TABLET ((GLenum) 604) #define GLUT_NUM_MOUSE_BUTTONS ((GLenum) 605) #define GLUT_NUM_SPACEBALL_BUTTONS ((GLenum) 606) #define GLUT_NUM_BUTTON_BOX_BUTTONS ((GLenum) 607) #define GLUT_NUM_DIALS ((GLenum) 608) #define GLUT_NUM_TABLET_BUTTONS ((GLenum) 609) #endif #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13) #define GLUT_DEVICE_IGNORE_KEY_REPEAT ((GLenum) 610) #define GLUT_DEVICE_KEY_REPEAT ((GLenum) 611) #define GLUT_HAS_JOYSTICK ((GLenum) 612) #define GLUT_OWNS_JOYSTICK ((GLenum) 613) #define GLUT_JOYSTICK_BUTTONS ((GLenum) 614) #define GLUT_JOYSTICK_AXES ((GLenum) 615) #define GLUT_JOYSTICK_POLL_RATE ((GLenum) 616) #endif #if (GLUT_API_VERSION >= 3) /* glutLayerGet parameters. */ #define GLUT_OVERLAY_POSSIBLE ((GLenum) 800) #define GLUT_LAYER_IN_USE ((GLenum) 801) #define GLUT_HAS_OVERLAY ((GLenum) 802) #define GLUT_TRANSPARENT_INDEX ((GLenum) 803) #define GLUT_NORMAL_DAMAGED ((GLenum) 804) #define GLUT_OVERLAY_DAMAGED ((GLenum) 805) #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9) /* glutVideoResizeGet parameters. */ #define GLUT_VIDEO_RESIZE_POSSIBLE ((GLenum) 900) #define GLUT_VIDEO_RESIZE_IN_USE ((GLenum) 901) #define GLUT_VIDEO_RESIZE_X_DELTA ((GLenum) 902) #define GLUT_VIDEO_RESIZE_Y_DELTA ((GLenum) 903) #define GLUT_VIDEO_RESIZE_WIDTH_DELTA ((GLenum) 904) #define GLUT_VIDEO_RESIZE_HEIGHT_DELTA ((GLenum) 905) #define GLUT_VIDEO_RESIZE_X ((GLenum) 906) #define GLUT_VIDEO_RESIZE_Y ((GLenum) 907) #define GLUT_VIDEO_RESIZE_WIDTH ((GLenum) 908) #define GLUT_VIDEO_RESIZE_HEIGHT ((GLenum) 909) #endif /* glutUseLayer parameters. */ #define GLUT_NORMAL ((GLenum) 0) #define GLUT_OVERLAY ((GLenum) 1) /* glutGetModifiers return mask. */ #define GLUT_ACTIVE_SHIFT 1 #define GLUT_ACTIVE_CTRL 2 #define GLUT_ACTIVE_ALT 4 /* glutSetCursor parameters. */ /* Basic arrows. */ #define GLUT_CURSOR_RIGHT_ARROW 0 #define GLUT_CURSOR_LEFT_ARROW 1 /* Symbolic cursor shapes. */ #define GLUT_CURSOR_INFO 2 #define GLUT_CURSOR_DESTROY 3 #define GLUT_CURSOR_HELP 4 #define GLUT_CURSOR_CYCLE 5 #define GLUT_CURSOR_SPRAY 6 #define GLUT_CURSOR_WAIT 7 #define GLUT_CURSOR_TEXT 8 #define GLUT_CURSOR_CROSSHAIR 9 /* Directional cursors. */ #define GLUT_CURSOR_UP_DOWN 10 #define GLUT_CURSOR_LEFT_RIGHT 11 /* Sizing cursors. */ #define GLUT_CURSOR_TOP_SIDE 12 #define GLUT_CURSOR_BOTTOM_SIDE 13 #define GLUT_CURSOR_LEFT_SIDE 14 #define GLUT_CURSOR_RIGHT_SIDE 15 #define GLUT_CURSOR_TOP_LEFT_CORNER 16 #define GLUT_CURSOR_TOP_RIGHT_CORNER 17 #define GLUT_CURSOR_BOTTOM_RIGHT_CORNER 18 #define GLUT_CURSOR_BOTTOM_LEFT_CORNER 19 /* Inherit from parent window. */ #define GLUT_CURSOR_INHERIT 100 /* Blank cursor. */ #define GLUT_CURSOR_NONE 101 /* Fullscreen crosshair (if available). */ #define GLUT_CURSOR_FULL_CROSSHAIR 102 #endif /* GLUT initialization sub-API. */ GLUTAPI void APIENTRY glutInit(int *argcp, char **argv); #if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK) GLUTAPI void APIENTRY __glutInitWithExit(int *argcp, char **argv, void (__cdecl *exitfunc)(int)); #ifndef GLUT_BUILDING_LIB static void APIENTRY glutInit_ATEXIT_HACK(int *argcp, char **argv) { __glutInitWithExit(argcp, argv, exit); } #define glutInit glutInit_ATEXIT_HACK #endif #endif GLUTAPI void APIENTRY glutInitDisplayMode(unsigned int mode); #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9) GLUTAPI void APIENTRY glutInitDisplayString(const char *string); #endif GLUTAPI void APIENTRY glutInitWindowPosition(int x, int y); GLUTAPI void APIENTRY glutInitWindowSize(int width, int height); GLUTAPI void APIENTRY glutMainLoop(void); /* GLUT window sub-API. */ GLUTAPI int APIENTRY glutCreateWindow(const char *title); #if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK) GLUTAPI int APIENTRY __glutCreateWindowWithExit(const char *title, void (__cdecl *exitfunc)(int)); #ifndef GLUT_BUILDING_LIB static int APIENTRY glutCreateWindow_ATEXIT_HACK(const char *title) { return __glutCreateWindowWithExit(title, exit); } #define glutCreateWindow glutCreateWindow_ATEXIT_HACK #endif #endif GLUTAPI int APIENTRY glutCreateSubWindow(int win, int x, int y, int width, int height); GLUTAPI void APIENTRY glutDestroyWindow(int win); GLUTAPI void APIENTRY glutPostRedisplay(void); #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 11) GLUTAPI void APIENTRY glutPostWindowRedisplay(int win); #endif GLUTAPI void APIENTRY glutSwapBuffers(void); GLUTAPI int APIENTRY glutGetWindow(void); GLUTAPI void APIENTRY glutSetWindow(int win); GLUTAPI void APIENTRY glutSetWindowTitle(const char *title); GLUTAPI void APIENTRY glutSetIconTitle(const char *title); GLUTAPI void APIENTRY glutPositionWindow(int x, int y); GLUTAPI void APIENTRY glutReshapeWindow(int width, int height); GLUTAPI void APIENTRY glutPopWindow(void); GLUTAPI void APIENTRY glutPushWindow(void); GLUTAPI void APIENTRY glutIconifyWindow(void); GLUTAPI void APIENTRY glutShowWindow(void); GLUTAPI void APIENTRY glutHideWindow(void); #if (GLUT_API_VERSION >= 3) GLUTAPI void APIENTRY glutFullScreen(void); GLUTAPI void APIENTRY glutSetCursor(int cursor); #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9) GLUTAPI void APIENTRY glutWarpPointer(int x, int y); #endif /* GLUT overlay sub-API. */ GLUTAPI void APIENTRY glutEstablishOverlay(void); GLUTAPI void APIENTRY glutRemoveOverlay(void); GLUTAPI void APIENTRY glutUseLayer(GLenum layer); GLUTAPI void APIENTRY glutPostOverlayRedisplay(void); #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 11) GLUTAPI void APIENTRY glutPostWindowOverlayRedisplay(int win); #endif GLUTAPI void APIENTRY glutShowOverlay(void); GLUTAPI void APIENTRY glutHideOverlay(void); #endif /* GLUT menu sub-API. */ GLUTAPI int APIENTRY glutCreateMenu(void (GLUTCALLBACK *func)(int)); #if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK) GLUTAPI int APIENTRY __glutCreateMenuWithExit(void (GLUTCALLBACK *func)(int), void (__cdecl *exitfunc)(int)); #ifndef GLUT_BUILDING_LIB static int APIENTRY glutCreateMenu_ATEXIT_HACK(void (GLUTCALLBACK *func)(int)) { return __glutCreateMenuWithExit(func, exit); } #define glutCreateMenu glutCreateMenu_ATEXIT_HACK #endif #endif GLUTAPI void APIENTRY glutDestroyMenu(int menu); GLUTAPI int APIENTRY glutGetMenu(void); GLUTAPI void APIENTRY glutSetMenu(int menu); GLUTAPI void APIENTRY glutAddMenuEntry(const char *label, int value); GLUTAPI void APIENTRY glutAddSubMenu(const char *label, int submenu); GLUTAPI void APIENTRY glutChangeToMenuEntry(int item, const char *label, int value); GLUTAPI void APIENTRY glutChangeToSubMenu(int item, const char *label, int submenu); GLUTAPI void APIENTRY glutRemoveMenuItem(int item); GLUTAPI void APIENTRY glutAttachMenu(int button); GLUTAPI void APIENTRY glutDetachMenu(int button); /* GLUT window callback sub-API. */ GLUTAPI void APIENTRY glutDisplayFunc(void (GLUTCALLBACK *func)(void)); GLUTAPI void APIENTRY glutReshapeFunc(void (GLUTCALLBACK *func)(int width, int height)); GLUTAPI void APIENTRY glutKeyboardFunc(void (GLUTCALLBACK *func)(unsigned char key, int x, int y)); GLUTAPI void APIENTRY glutMouseFunc(void (GLUTCALLBACK *func)(int button, int state, int x, int y)); GLUTAPI void APIENTRY glutMotionFunc(void (GLUTCALLBACK *func)(int x, int y)); GLUTAPI void APIENTRY glutPassiveMotionFunc(void (GLUTCALLBACK *func)(int x, int y)); GLUTAPI void APIENTRY glutEntryFunc(void (GLUTCALLBACK *func)(int state)); GLUTAPI void APIENTRY glutVisibilityFunc(void (GLUTCALLBACK *func)(int state)); GLUTAPI void APIENTRY glutIdleFunc(void (GLUTCALLBACK *func)(void)); GLUTAPI void APIENTRY glutTimerFunc(unsigned int millis, void (GLUTCALLBACK *func)(int value), int value); GLUTAPI void APIENTRY glutMenuStateFunc(void (GLUTCALLBACK *func)(int state)); #if (GLUT_API_VERSION >= 2) GLUTAPI void APIENTRY glutSpecialFunc(void (GLUTCALLBACK *func)(int key, int x, int y)); GLUTAPI void APIENTRY glutSpaceballMotionFunc(void (GLUTCALLBACK *func)(int x, int y, int z)); GLUTAPI void APIENTRY glutSpaceballRotateFunc(void (GLUTCALLBACK *func)(int x, int y, int z)); GLUTAPI void APIENTRY glutSpaceballButtonFunc(void (GLUTCALLBACK *func)(int button, int state)); GLUTAPI void APIENTRY glutButtonBoxFunc(void (GLUTCALLBACK *func)(int button, int state)); GLUTAPI void APIENTRY glutDialsFunc(void (GLUTCALLBACK *func)(int dial, int value)); GLUTAPI void APIENTRY glutTabletMotionFunc(void (GLUTCALLBACK *func)(int x, int y)); GLUTAPI void APIENTRY glutTabletButtonFunc(void (GLUTCALLBACK *func)(int button, int state, int x, int y)); #if (GLUT_API_VERSION >= 3) GLUTAPI void APIENTRY glutMenuStatusFunc(void (GLUTCALLBACK *func)(int status, int x, int y)); GLUTAPI void APIENTRY glutOverlayDisplayFunc(void (GLUTCALLBACK *func)(void)); #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9) GLUTAPI void APIENTRY glutWindowStatusFunc(void (GLUTCALLBACK *func)(int state)); #endif #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13) GLUTAPI void APIENTRY glutKeyboardUpFunc(void (GLUTCALLBACK *func)(unsigned char key, int x, int y)); GLUTAPI void APIENTRY glutSpecialUpFunc(void (GLUTCALLBACK *func)(int key, int x, int y)); GLUTAPI void APIENTRY glutJoystickFunc(void (GLUTCALLBACK *func)(unsigned int buttonMask, int x, int y, int z), int pollInterval); #endif #endif #endif /* GLUT color index sub-API. */ GLUTAPI void APIENTRY glutSetColor(int, GLfloat red, GLfloat green, GLfloat blue); GLUTAPI GLfloat APIENTRY glutGetColor(int ndx, int component); GLUTAPI void APIENTRY glutCopyColormap(int win); /* GLUT state retrieval sub-API. */ GLUTAPI int APIENTRY glutGet(GLenum type); GLUTAPI int APIENTRY glutDeviceGet(GLenum type); #if (GLUT_API_VERSION >= 2) /* GLUT extension support sub-API */ GLUTAPI int APIENTRY glutExtensionSupported(const char *name); #endif #if (GLUT_API_VERSION >= 3) GLUTAPI int APIENTRY glutGetModifiers(void); GLUTAPI int APIENTRY glutLayerGet(GLenum type); #endif /* GLUT font sub-API */ GLUTAPI void APIENTRY glutBitmapCharacter(void *font, int character); GLUTAPI int APIENTRY glutBitmapWidth(void *font, int character); GLUTAPI void APIENTRY glutStrokeCharacter(void *font, int character); GLUTAPI int APIENTRY glutStrokeWidth(void *font, int character); #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9) GLUTAPI int APIENTRY glutBitmapLength(void *font, const unsigned char *string); GLUTAPI int APIENTRY glutStrokeLength(void *font, const unsigned char *string); #endif /* GLUT pre-built models sub-API */ GLUTAPI void APIENTRY glutWireSphere(GLdouble radius, GLint slices, GLint stacks); GLUTAPI void APIENTRY glutSolidSphere(GLdouble radius, GLint slices, GLint stacks); GLUTAPI void APIENTRY glutWireCone(GLdouble base, GLdouble height, GLint slices, GLint stacks); GLUTAPI void APIENTRY glutSolidCone(GLdouble base, GLdouble height, GLint slices, GLint stacks); GLUTAPI void APIENTRY glutWireCube(GLdouble size); GLUTAPI void APIENTRY glutSolidCube(GLdouble size); GLUTAPI void APIENTRY glutWireTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings); GLUTAPI void APIENTRY glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings); GLUTAPI void APIENTRY glutWireDodecahedron(void); GLUTAPI void APIENTRY glutSolidDodecahedron(void); GLUTAPI void APIENTRY glutWireTeapot(GLdouble size); GLUTAPI void APIENTRY glutSolidTeapot(GLdouble size); GLUTAPI void APIENTRY glutWireOctahedron(void); GLUTAPI void APIENTRY glutSolidOctahedron(void); GLUTAPI void APIENTRY glutWireTetrahedron(void); GLUTAPI void APIENTRY glutSolidTetrahedron(void); GLUTAPI void APIENTRY glutWireIcosahedron(void); GLUTAPI void APIENTRY glutSolidIcosahedron(void); #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9) /* GLUT video resize sub-API. */ GLUTAPI int APIENTRY glutVideoResizeGet(GLenum param); GLUTAPI void APIENTRY glutSetupVideoResizing(void); GLUTAPI void APIENTRY glutStopVideoResizing(void); GLUTAPI void APIENTRY glutVideoResize(int x, int y, int width, int height); GLUTAPI void APIENTRY glutVideoPan(int x, int y, int width, int height); /* GLUT debugging sub-API. */ GLUTAPI void APIENTRY glutReportErrors(void); #endif #if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13) /* GLUT device control sub-API. */ /* glutSetKeyRepeat modes. */ #define GLUT_KEY_REPEAT_OFF 0 #define GLUT_KEY_REPEAT_ON 1 #define GLUT_KEY_REPEAT_DEFAULT 2 /* Joystick button masks. */ #define GLUT_JOYSTICK_BUTTON_A 1 #define GLUT_JOYSTICK_BUTTON_B 2 #define GLUT_JOYSTICK_BUTTON_C 4 #define GLUT_JOYSTICK_BUTTON_D 8 GLUTAPI void APIENTRY glutIgnoreKeyRepeat(int ignore); GLUTAPI void APIENTRY glutSetKeyRepeat(int repeatMode); GLUTAPI void APIENTRY glutForceJoystickFunc(void); /* GLUT game mode sub-API. */ /* glutGameModeGet. */ #define GLUT_GAME_MODE_ACTIVE ((GLenum) 0) #define GLUT_GAME_MODE_POSSIBLE ((GLenum) 1) #define GLUT_GAME_MODE_WIDTH ((GLenum) 2) #define GLUT_GAME_MODE_HEIGHT ((GLenum) 3) #define GLUT_GAME_MODE_PIXEL_DEPTH ((GLenum) 4) #define GLUT_GAME_MODE_REFRESH_RATE ((GLenum) 5) #define GLUT_GAME_MODE_DISPLAY_CHANGED ((GLenum) 6) GLUTAPI void APIENTRY glutGameModeString(const char *string); GLUTAPI int APIENTRY glutEnterGameMode(void); GLUTAPI void APIENTRY glutLeaveGameMode(void); GLUTAPI int APIENTRY glutGameModeGet(GLenum mode); #endif #ifdef __cplusplus } #endif #ifdef GLUT_APIENTRY_DEFINED # undef GLUT_APIENTRY_DEFINED # undef APIENTRY #endif #ifdef GLUT_WINGDIAPI_DEFINED # undef GLUT_WINGDIAPI_DEFINED # undef WINGDIAPI #endif #ifdef GLUT_DEFINED___CDECL # undef GLUT_DEFINED___CDECL # undef __cdecl #endif #ifdef GLUT_DEFINED__CRTIMP # undef GLUT_DEFINED__CRTIMP # undef _CRTIMP #endif #endif /* __glut_h__ */ ================================================ FILE: src/3rdparty/glut/lib/glut.def ================================================ DESCRIPTION 'OpenGL Utility Toolkit for Win32' VERSION 3.7 EXPORTS glutAddMenuEntry glutAddSubMenu glutAttachMenu glutBitmapCharacter glutBitmapLength glutBitmapWidth glutButtonBoxFunc glutChangeToMenuEntry glutChangeToSubMenu glutCopyColormap glutCreateMenu __glutCreateMenuWithExit glutCreateSubWindow glutCreateWindow __glutCreateWindowWithExit glutDestroyMenu glutDestroyWindow glutDetachMenu glutDeviceGet glutDialsFunc glutDisplayFunc glutEnterGameMode glutEntryFunc glutEstablishOverlay glutExtensionSupported glutForceJoystickFunc glutFullScreen glutGameModeGet glutGameModeString glutGet glutGetColor glutGetMenu glutGetModifiers glutGetWindow glutHideOverlay glutHideWindow glutIconifyWindow glutIdleFunc glutIgnoreKeyRepeat glutInit __glutInitWithExit glutInitDisplayMode glutInitDisplayString glutInitWindowPosition glutInitWindowSize glutJoystickFunc glutKeyboardFunc glutKeyboardUpFunc glutLayerGet glutLeaveGameMode glutMainLoop glutMenuStateFunc glutMenuStatusFunc glutMotionFunc glutMouseFunc glutOverlayDisplayFunc glutPassiveMotionFunc glutPopWindow glutPositionWindow glutPostOverlayRedisplay glutPostRedisplay glutPostWindowOverlayRedisplay glutPostWindowRedisplay glutPushWindow glutRemoveMenuItem glutRemoveOverlay glutReportErrors glutReshapeFunc glutReshapeWindow glutSetColor glutSetCursor glutSetIconTitle glutSetKeyRepeat glutSetMenu glutSetWindow glutSetWindowTitle glutSetupVideoResizing glutShowOverlay glutShowWindow glutSolidCone glutSolidCube glutSolidDodecahedron glutSolidIcosahedron glutSolidOctahedron glutSolidSphere glutSolidTeapot glutSolidTetrahedron glutSolidTorus glutSpaceballButtonFunc glutSpaceballMotionFunc glutSpaceballRotateFunc glutSpecialFunc glutSpecialUpFunc glutStopVideoResizing glutStrokeCharacter glutStrokeLength glutStrokeWidth glutSwapBuffers glutTabletButtonFunc glutTabletMotionFunc glutTimerFunc glutUseLayer glutVideoPan glutVideoResize glutVideoResizeGet glutVisibilityFunc glutWarpPointer glutWindowStatusFunc glutWireCone glutWireCube glutWireDodecahedron glutWireIcosahedron glutWireOctahedron glutWireSphere glutWireTeapot glutWireTetrahedron glutWireTorus ; __glutSetFCB ; __glutGetFCB ================================================ FILE: src/3rdparty/opencv/include/opencv/cv.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_CV_H__ #define __OPENCV_OLD_CV_H__ #if defined(_MSC_VER) #define CV_DO_PRAGMA(x) __pragma(x) #define __CVSTR2__(x) #x #define __CVSTR1__(x) __CVSTR2__(x) #define __CVMSVCLOC__ __FILE__ "("__CVSTR1__(__LINE__)") : " #define CV_MSG_PRAGMA(_msg) CV_DO_PRAGMA(message (__CVMSVCLOC__ _msg)) #elif defined(__GNUC__) #define CV_DO_PRAGMA(x) _Pragma (#x) #define CV_MSG_PRAGMA(_msg) CV_DO_PRAGMA(message (_msg)) #else #define CV_DO_PRAGMA(x) #define CV_MSG_PRAGMA(_msg) #endif #define CV_WARNING(x) CV_MSG_PRAGMA("Warning: " #x) //CV_WARNING("This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module") #include "opencv2/core/core_c.h" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/photo/photo_c.h" #include "opencv2/video/tracking_c.h" #include "opencv2/objdetect/objdetect_c.h" #if !defined(CV_IMPL) #define CV_IMPL extern "C" #endif //CV_IMPL #endif // __OPENCV_OLD_CV_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv/cv.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_CV_HPP__ #define __OPENCV_OLD_CV_HPP__ //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif #include "cv.h" #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/photo.hpp" #include "opencv2/video.hpp" #include "opencv2/highgui.hpp" #include "opencv2/features2d.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/objdetect.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/cvaux.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_AUX_H__ #define __OPENCV_OLD_AUX_H__ //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif #include "opencv2/core/core_c.h" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/photo/photo_c.h" #include "opencv2/video/tracking_c.h" #include "opencv2/objdetect/objdetect_c.h" #endif /* End of file. */ ================================================ FILE: src/3rdparty/opencv/include/opencv/cvaux.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_AUX_HPP__ #define __OPENCV_OLD_AUX_HPP__ //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif #include "cvaux.h" #include "opencv2/core/utility.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/cvwimage.h ================================================ /////////////////////////////////////////////////////////////////////////////// // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to // this license. If you do not agree to this license, do not download, // install, copy or use the software. // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2008, Google, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation or contributors may not be used to endorse // or promote products derived from this software without specific // prior written permission. // // This software is provided by the copyright holders and contributors "as is" // and any express or implied warranties, including, but not limited to, the // implied warranties of merchantability and fitness for a particular purpose // are disclaimed. In no event shall the Intel Corporation or contributors be // liable for any direct, indirect, incidental, special, exemplary, or // consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. #ifndef __OPENCV_OLD_WIMAGE_HPP__ #define __OPENCV_OLD_WIMAGE_HPP__ #include "opencv2/core/wimage.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/cxcore.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_CXCORE_H__ #define __OPENCV_OLD_CXCORE_H__ //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif #include "opencv2/core/core_c.h" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/cxcore.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_CXCORE_HPP__ #define __OPENCV_OLD_CXCORE_HPP__ //#if defined(__GNUC__) //#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" //#endif #include "cxcore.h" #include "opencv2/core.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/cxeigen.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_EIGEN_HPP__ #define __OPENCV_OLD_EIGEN_HPP__ #include "opencv2/core/eigen.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/cxmisc.h ================================================ #ifndef __OPENCV_OLD_CXMISC_H__ #define __OPENCV_OLD_CXMISC_H__ #ifdef __cplusplus # include "opencv2/core/utility.hpp" #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/highgui.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_HIGHGUI_H__ #define __OPENCV_OLD_HIGHGUI_H__ #include "opencv2/core/core_c.h" #include "opencv2/highgui/highgui_c.h" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv/ml.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OLD_ML_H__ #define __OPENCV_OLD_ML_H__ #include "opencv2/core/core_c.h" #include "opencv2/ml.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/aruco/charuco.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_CHARUCO_HPP__ #define __OPENCV_CHARUCO_HPP__ #include #include #include namespace cv { namespace aruco { //! @addtogroup aruco //! @{ /** * @brief ChArUco board * Specific class for ChArUco boards. A ChArUco board is a planar board where the markers are placed * inside the white squares of a chessboard. The benefits of ChArUco boards is that they provide * both, ArUco markers versatility and chessboard corner precision, which is important for * calibration and pose estimation. * This class also allows the easy creation and drawing of ChArUco boards. */ class CV_EXPORTS CharucoBoard : public Board { public: // vector of chessboard 3D corners precalculated std::vector< Point3f > chessboardCorners; // for each charuco corner, nearest marker id and nearest marker corner id of each marker std::vector< std::vector< int > > nearestMarkerIdx; std::vector< std::vector< int > > nearestMarkerCorners; /** * @brief Draw a ChArUco board * * @param outSize size of the output image in pixels. * @param img output image with the board. The size of this image will be outSize * and the board will be on the center, keeping the board proportions. * @param marginSize minimum margins (in pixels) of the board in the output image * @param borderBits width of the marker borders. * * This function return the image of the ChArUco board, ready to be printed. */ void draw(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1); /** * @brief Create a CharucoBoard object * * @param squaresX number of chessboard squares in X direction * @param squaresY number of chessboard squares in Y direction * @param squareLength chessboard square side length (normally in meters) * @param markerLength marker side length (same unit than squareLength) * @param dictionary dictionary of markers indicating the type of markers. * The first markers in the dictionary are used to fill the white chessboard squares. * @return the output CharucoBoard object * * This functions creates a CharucoBoard object given the number of squares in each direction * and the size of the markers and chessboard squares. */ static CharucoBoard create(int squaresX, int squaresY, float squareLength, float markerLength, Dictionary dictionary); /** * */ Size getChessboardSize() const { return Size(_squaresX, _squaresY); } /** * */ float getSquareLength() const { return _squareLength; } /** * */ float getMarkerLength() const { return _markerLength; } private: void _getNearestMarkerCorners(); // number of markers in X and Y directions int _squaresX, _squaresY; // size of chessboard squares side (normally in meters) float _squareLength; // marker side lenght (normally in meters) float _markerLength; }; /** * @brief Interpolate position of ChArUco board corners * @param markerCorners vector of already detected markers corners. For each marker, its four * corners are provided, (e.g std::vector > ). For N detected markers, the * dimensions of this array should be Nx4. The order of the corners should be clockwise. * @param markerIds list of identifiers for each marker in corners * @param image input image necesary for corner refinement. Note that markers are not detected and * should be sent in corners and ids parameters. * @param board layout of ChArUco board. * @param charucoCorners interpolated chessboard corners * @param charucoIds interpolated chessboard corners identifiers * @param cameraMatrix optional 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs optional vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * * This function receives the detected markers and returns the 2D position of the chessboard corners * from a ChArUco board using the detected Aruco markers. If camera parameters are provided, * the process is based in an approximated pose estimation, else it is based on local homography. * Only visible corners are returned. For each corner, its corresponding identifier is * also returned in charucoIds. * The function returns the number of interpolated corners. */ CV_EXPORTS int interpolateCornersCharuco(InputArrayOfArrays markerCorners, InputArray markerIds, InputArray image, const CharucoBoard &board, OutputArray charucoCorners, OutputArray charucoIds, InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray()); /** * @brief Pose estimation for a ChArUco board given some of their corners * @param charucoCorners vector of detected charuco corners * @param charucoIds list of identifiers for each corner in charucoCorners * @param board layout of ChArUco board. * @param cameraMatrix input 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvec Output vector (e.g. cv::Mat) corresponding to the rotation vector of the board * (@sa Rodrigues). * @param tvec Output vector (e.g. cv::Mat) corresponding to the translation vector of the board. * * This function estimates a Charuco board pose from some detected corners. * The function checks if the input corners are enough and valid to perform pose estimation. * If pose estimation is valid, returns true, else returns false. */ CV_EXPORTS bool estimatePoseCharucoBoard(InputArray charucoCorners, InputArray charucoIds, CharucoBoard &board, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec); /** * @brief Draws a set of Charuco corners * @param image input/output image. It must have 1 or 3 channels. The number of channels is not * altered. * @param charucoCorners vector of detected charuco corners * @param charucoIds list of identifiers for each corner in charucoCorners * @param cornerColor color of the square surrounding each corner * * This function draws a set of detected Charuco corners. If identifiers vector is provided, it also * draws the id of each corner. */ CV_EXPORTS void drawDetectedCornersCharuco(InputOutputArray image, InputArray charucoCorners, InputArray charucoIds = noArray(), Scalar cornerColor = Scalar(255, 0, 0)); /** * @brief Calibrate a camera using Charuco corners * * @param charucoCorners vector of detected charuco corners per frame * @param charucoIds list of identifiers for each corner in charucoCorners per frame * @param board Marker Board layout * @param imageSize input image size * @param cameraMatrix Output 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . If CV\_CALIB\_USE\_INTRINSIC\_GUESS * and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be * initialized before calling the function. * @param distCoeffs Output vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each board view * (e.g. std::vector>). That is, each k-th rotation vector together with the corresponding * k-th translation vector (see the next output parameter description) brings the board pattern * from the model coordinate space (in which object points are specified) to the world coordinate * space, that is, a real position of the board pattern in the k-th pattern view (k=0.. *M* -1). * @param tvecs Output vector of translation vectors estimated for each pattern view. * @param flags flags Different flags for the calibration process (@sa calibrateCamera) * @param criteria Termination criteria for the iterative optimization algorithm. * * This function calibrates a camera using a set of corners of a Charuco Board. The function * receives a list of detected corners and its identifiers from several views of the Board. * The function returns the final re-projection error. */ CV_EXPORTS double calibrateCameraCharuco( InputArrayOfArrays charucoCorners, InputArrayOfArrays charucoIds, const CharucoBoard &board, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs = noArray(), OutputArrayOfArrays tvecs = noArray(), int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON)); /** * @brief Detect ChArUco Diamond markers * * @param image input image necessary for corner subpixel. * @param markerCorners list of detected marker corners from detectMarkers function. * @param markerIds list of marker ids in markerCorners. * @param squareMarkerLengthRate rate between square and marker length: * squareMarkerLengthRate = squareLength/markerLength. The real units are not necessary. * @param diamondCorners output list of detected diamond corners (4 corners per diamond). The order * is the same than in marker corners: top left, top right, bottom right and bottom left. Similar * format than the corners returned by detectMarkers (e.g std::vector > ). * @param diamondIds ids of the diamonds in diamondCorners. The id of each diamond is in fact of * type Vec4i, so each diamond has 4 ids, which are the ids of the aruco markers composing the * diamond. * @param cameraMatrix Optional camera calibration matrix. * @param distCoeffs Optional camera distortion coefficients. * * This function detects Diamond markers from the previous detected ArUco markers. The diamonds * are returned in the diamondCorners and diamondIds parameters. If camera calibration parameters * are provided, the diamond search is based on reprojection. If not, diamond search is based on * homography. Homography is faster than reprojection but can slightly reduce the detection rate. */ CV_EXPORTS void detectCharucoDiamond(InputArray image, InputArrayOfArrays markerCorners, InputArray markerIds, float squareMarkerLengthRate, OutputArrayOfArrays diamondCorners, OutputArray diamondIds, InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray()); /** * @brief Draw a set of detected ChArUco Diamond markers * * @param image input/output image. It must have 1 or 3 channels. The number of channels is not * altered. * @param diamondCorners positions of diamond corners in the same format returned by * detectCharucoDiamond(). (e.g std::vector > ). For N detected markers, * the dimensions of this array should be Nx4. The order of the corners should be clockwise. * @param diamondIds vector of identifiers for diamonds in diamondCorners, in the same format * returned by detectCharucoDiamond() (e.g. std::vector). * Optional, if not provided, ids are not painted. * @param borderColor color of marker borders. Rest of colors (text color and first corner color) * are calculated based on this one. * * Given an array of detected diamonds, this functions draws them in the image. The marker borders * are painted and the markers identifiers if provided. * Useful for debugging purposes. */ CV_EXPORTS void drawDetectedDiamonds(InputOutputArray image, InputArrayOfArrays diamondCorners, InputArray diamondIds = noArray(), Scalar borderColor = Scalar(0, 0, 255)); /** * @brief Draw a ChArUco Diamond marker * * @param dictionary dictionary of markers indicating the type of markers. * @param ids list of 4 ids for each ArUco marker in the ChArUco marker. * @param squareLength size of the chessboard squares in pixels. * @param markerLength size of the markers in pixels. * @param img output image with the marker. The size of this image will be * 3*squareLength + 2*marginSize,. * @param marginSize minimum margins (in pixels) of the marker in the output image * @param borderBits width of the marker borders. * * This function return the image of a ChArUco marker, ready to be printed. */ CV_EXPORTS void drawCharucoDiamond(Dictionary dictionary, Vec4i ids, int squareLength, int markerLength, OutputArray img, int marginSize = 0, int borderBits = 1); //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/aruco/dictionary.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_DICTIONARY_HPP__ #define __OPENCV_DICTIONARY_HPP__ #include namespace cv { namespace aruco { //! @addtogroup aruco //! @{ /** * @brief Dictionary/Set of markers. It contains the inner codification * * bytesList contains the marker codewords where * - bytesList.rows is the dictionary size * - each marker is encoded using `nbytes = ceil(markerSize*markerSize/8.)` * - each row contains all 4 rotations of the marker, so its length is `4*nbytes` * * `bytesList.ptr(i)[k*nbytes + j]` is then the j-th byte of i-th marker, in its k-th rotation. */ class CV_EXPORTS Dictionary { public: Mat bytesList; // marker code information int markerSize; // number of bits per dimension int maxCorrectionBits; // maximum number of bits that can be corrected /** */ Dictionary(const Mat &_bytesList = Mat(), int _markerSize = 0, int _maxcorr = 0); /** * @brief Given a matrix of bits. Returns whether if marker is identified or not. * It returns by reference the correct id (if any) and the correct rotation */ bool identify(const Mat &onlyBits, int &idx, int &rotation, double maxCorrectionRate) const; /** * @brief Returns the distance of the input bits to the specific id. If allRotations is true, * the four posible bits rotation are considered */ int getDistanceToId(InputArray bits, int id, bool allRotations = true) const; /** * @brief Draw a canonical marker image */ void drawMarker(int id, int sidePixels, OutputArray _img, int borderBits = 1) const; /** * @brief Transform matrix of bits to list of bytes in the 4 rotations */ static Mat getByteListFromBits(const Mat &bits); /** * @brief Transform list of bytes to matrix of bits */ static Mat getBitsFromByteList(const Mat &byteList, int markerSize); }; /** * @brief Predefined markers dictionaries/sets * Each dictionary indicates the number of bits and the number of markers contained * - DICT_ARUCO: standard ArUco Library Markers. 1024 markers, 5x5 bits, 0 minimum distance */ enum PREDEFINED_DICTIONARY_NAME { DICT_4X4_50 = 0, DICT_4X4_100, DICT_4X4_250, DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL }; /** * @brief Returns one of the predefined dictionaries defined in PREDEFINED_DICTIONARY_NAME */ CV_EXPORTS const Dictionary &getPredefinedDictionary(PREDEFINED_DICTIONARY_NAME name); /** * @brief Generates a new customizable marker dictionary * * @param nMarkers number of markers in the dictionary * @param markerSize number of bits per dimension of each markers * @param baseDictionary Include the markers in this dictionary at the beginning (optional) * * This function creates a new dictionary composed by nMarkers markers and each markers composed * by markerSize x markerSize bits. If baseDictionary is provided, its markers are directly * included and the rest are generated based on them. If the size of baseDictionary is higher * than nMarkers, only the first nMarkers in baseDictionary are taken and no new marker is added. */ CV_EXPORTS Dictionary generateCustomDictionary(int nMarkers, int markerSize, const Dictionary &baseDictionary = Dictionary()); //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/aruco.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_ARUCO_HPP__ #define __OPENCV_ARUCO_HPP__ #include #include #include "opencv2/aruco/dictionary.hpp" /** * @defgroup aruco ArUco Marker Detection * This module is dedicated to square fiducial markers (also known as Augmented Reality Markers) * These markers are useful for easy, fast and robust camera pose estimation.ç * * The main functionalities are: * - Detection of markers in a image * - Pose estimation from a single marker or from a board/set of markers * - Detection of ChArUco board for high subpixel accuracy * - Camera calibration from both, ArUco boards and ChArUco boards. * - Detection of ChArUco diamond markers * The samples directory includes easy examples of how to use the module. * * The implementation is based on the ArUco Library by R. Muñoz-Salinas and S. Garrido-Jurado. * * @sa S. Garrido-Jurado, R. Muñoz-Salinas, F. J. Madrid-Cuevas, and M. J. Marín-Jiménez. 2014. * "Automatic generation and detection of highly reliable fiducial markers under occlusion". * Pattern Recogn. 47, 6 (June 2014), 2280-2292. DOI=10.1016/j.patcog.2014.01.005 * * @sa http://www.uco.es/investiga/grupos/ava/node/26 * * This module has been originally developed by Sergio Garrido-Jurado as a project * for Google Summer of Code 2015 (GSoC 15). * * */ namespace cv { namespace aruco { //! @addtogroup aruco //! @{ /** * @brief Parameters for the detectMarker process: * - adaptiveThreshWinSizeMin: minimum window size for adaptive thresholding before finding * contours (default 3). * - adaptiveThreshWinSizeMax: maximum window size for adaptive thresholding before finding * contours (default 23). * - adaptiveThreshWinSizeStep: increments from adaptiveThreshWinSizeMin to adaptiveThreshWinSizeMax * during the thresholding (default 10). * - adaptiveThreshConstant: constant for adaptive thresholding before finding contours (default 7) * - minMarkerPerimeterRate: determine minimum perimeter for marker contour to be detected. This * is defined as a rate respect to the maximum dimension of the input image (default 0.03). * - maxMarkerPerimeterRate: determine maximum perimeter for marker contour to be detected. This * is defined as a rate respect to the maximum dimension of the input image (default 4.0). * - polygonalApproxAccuracyRate: minimum accuracy during the polygonal approximation process to * determine which contours are squares. * - minCornerDistanceRate: minimum distance between corners for detected markers relative to its * perimeter (default 0.05) * - minDistanceToBorder: minimum distance of any corner to the image border for detected markers * (in pixels) (default 3) * - minMarkerDistanceRate: minimum mean distance beetween two marker corners to be considered * similar, so that the smaller one is removed. The rate is relative to the smaller perimeter * of the two markers (default 0.05). * - doCornerRefinement: do subpixel refinement or not * - cornerRefinementWinSize: window size for the corner refinement process (in pixels) (default 5). * - cornerRefinementMaxIterations: maximum number of iterations for stop criteria of the corner * refinement process (default 30). * - cornerRefinementMinAccuracy: minimum error for the stop cristeria of the corner refinement * process (default: 0.1) * - markerBorderBits: number of bits of the marker border, i.e. marker border width (default 1). * - perpectiveRemovePixelPerCell: number of bits (per dimension) for each cell of the marker * when removing the perspective (default 8). * - perspectiveRemoveIgnoredMarginPerCell: width of the margin of pixels on each cell not * considered for the determination of the cell bit. Represents the rate respect to the total * size of the cell, i.e. perpectiveRemovePixelPerCell (default 0.13) * - maxErroneousBitsInBorderRate: maximum number of accepted erroneous bits in the border (i.e. * number of allowed white bits in the border). Represented as a rate respect to the total * number of bits per marker (default 0.35). * - minOtsuStdDev: minimun standard deviation in pixels values during the decodification step to * apply Otsu thresholding (otherwise, all the bits are set to 0 or 1 depending on mean higher * than 128 or not) (default 5.0) * - errorCorrectionRate error correction rate respect to the maximun error correction capability * for each dictionary. (default 0.6). */ struct CV_EXPORTS DetectorParameters { DetectorParameters(); int adaptiveThreshWinSizeMin; int adaptiveThreshWinSizeMax; int adaptiveThreshWinSizeStep; double adaptiveThreshConstant; double minMarkerPerimeterRate; double maxMarkerPerimeterRate; double polygonalApproxAccuracyRate; double minCornerDistanceRate; int minDistanceToBorder; double minMarkerDistanceRate; bool doCornerRefinement; int cornerRefinementWinSize; int cornerRefinementMaxIterations; double cornerRefinementMinAccuracy; int markerBorderBits; int perspectiveRemovePixelPerCell; double perspectiveRemoveIgnoredMarginPerCell; double maxErroneousBitsInBorderRate; double minOtsuStdDev; double errorCorrectionRate; }; /** * @brief Basic marker detection * * @param image input image * @param dictionary indicates the type of markers that will be searched * @param corners vector of detected marker corners. For each marker, its four corners * are provided, (e.g std::vector > ). For N detected markers, * the dimensions of this array is Nx4. The order of the corners is clockwise. * @param ids vector of identifiers of the detected markers. The identifier is of type int * (e.g. std::vector). For N detected markers, the size of ids is also N. * The identifiers have the same order than the markers in the imgPoints array. * @param parameters marker detection parameters * @param rejectedImgPoints contains the imgPoints of those squares whose inner code has not a * correct codification. Useful for debugging purposes. * * Performs marker detection in the input image. Only markers included in the specific dictionary * are searched. For each detected marker, it returns the 2D position of its corner in the image * and its corresponding identifier. * Note that this function does not perform pose estimation. * @sa estimatePoseSingleMarkers, estimatePoseBoard * */ CV_EXPORTS void detectMarkers(InputArray image, Dictionary dictionary, OutputArrayOfArrays corners, OutputArray ids, DetectorParameters parameters = DetectorParameters(), OutputArrayOfArrays rejectedImgPoints = noArray()); /** * @brief Pose estimation for single markers * * @param corners vector of already detected markers corners. For each marker, its four corners * are provided, (e.g std::vector > ). For N detected markers, * the dimensions of this array should be Nx4. The order of the corners should be clockwise. * @sa detectMarkers * @param markerLength the length of the markers' side. The returning translation vectors will * be in the same unit. Normally, unit is meters. * @param cameraMatrix input 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvecs array of output rotation vectors (@sa Rodrigues) (e.g. std::vector>). * Each element in rvecs corresponds to the specific marker in imgPoints. * @param tvecs array of output translation vectors (e.g. std::vector>). * Each element in tvecs corresponds to the specific marker in imgPoints. * * This function receives the detected markers and returns their pose estimation respect to * the camera individually. So for each marker, one rotation and translation vector is returned. * The returned transformation is the one that transforms points from each marker coordinate system * to the camera coordinate system. * The marker corrdinate system is centered on the middle of the marker, with the Z axis * perpendicular to the marker plane. * The coordinates of the four corners of the marker in its own coordinate system are: * (-markerLength/2, markerLength/2, 0), (markerLength/2, markerLength/2, 0), * (markerLength/2, -markerLength/2, 0), (-markerLength/2, -markerLength/2, 0) */ CV_EXPORTS void estimatePoseSingleMarkers(InputArrayOfArrays corners, float markerLength, InputArray cameraMatrix, InputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs); /** * @brief Board of markers * * A board is a set of markers in the 3D space with a common cordinate system. * The common form of a board of marker is a planar (2D) board, however any 3D layout can be used. * A Board object is composed by: * - The object points of the marker corners, i.e. their coordinates respect to the board system. * - The dictionary which indicates the type of markers of the board * - The identifier of all the markers in the board. */ class CV_EXPORTS Board { public: // array of object points of all the marker corners in the board // each marker include its 4 corners, i.e. for M markers, the size is Mx4 std::vector< std::vector< Point3f > > objPoints; // the dictionary of markers employed for this board Dictionary dictionary; // vector of the identifiers of the markers in the board (same size than objPoints) // The identifiers refers to the board dictionary std::vector< int > ids; }; /** * @brief Planar board with grid arrangement of markers * More common type of board. All markers are placed in the same plane in a grid arrangment. * The board can be drawn using drawPlanarBoard() function (@sa drawPlanarBoard) */ class CV_EXPORTS GridBoard : public Board { public: /** * @brief Draw a GridBoard * * @param outSize size of the output image in pixels. * @param img output image with the board. The size of this image will be outSize * and the board will be on the center, keeping the board proportions. * @param marginSize minimum margins (in pixels) of the board in the output image * @param borderBits width of the marker borders. * * This function return the image of the GridBoard, ready to be printed. */ void draw(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1); /** * @brief Create a GridBoard object * * @param markersX number of markers in X direction * @param markersY number of markers in Y direction * @param markerLength marker side length (normally in meters) * @param markerSeparation separation between two markers (same unit than markerLenght) * @param dictionary dictionary of markers indicating the type of markers. * The first markersX*markersY markers in the dictionary are used. * @return the output GridBoard object * * This functions creates a GridBoard object given the number of markers in each direction and * the marker size and marker separation. */ static GridBoard create(int markersX, int markersY, float markerLength, float markerSeparation, Dictionary dictionary); /** * */ Size getGridSize() const { return Size(_markersX, _markersY); } /** * */ float getMarkerLength() const { return _markerLength; } /** * */ float getMarkerSeparation() const { return _markerSeparation; } private: // number of markers in X and Y directions int _markersX, _markersY; // marker side lenght (normally in meters) float _markerLength; // separation between markers in the grid float _markerSeparation; }; /** * @brief Pose estimation for a board of markers * * @param corners vector of already detected markers corners. For each marker, its four corners * are provided, (e.g std::vector > ). For N detected markers, the * dimensions of this array should be Nx4. The order of the corners should be clockwise. * @param ids list of identifiers for each marker in corners * @param board layout of markers in the board. The layout is composed by the marker identifiers * and the positions of each marker corner in the board reference system. * @param cameraMatrix input 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvec Output vector (e.g. cv::Mat) corresponding to the rotation vector of the board * (@sa Rodrigues). * @param tvec Output vector (e.g. cv::Mat) corresponding to the translation vector of the board. * * This function receives the detected markers and returns the pose of a marker board composed * by those markers. * A Board of marker has a single world coordinate system which is defined by the board layout. * The returned transformation is the one that transforms points from the board coordinate system * to the camera coordinate system. * Input markers that are not included in the board layout are ignored. * The function returns the number of markers from the input employed for the board pose estimation. * Note that returning a 0 means the pose has not been estimated. */ CV_EXPORTS int estimatePoseBoard(InputArrayOfArrays corners, InputArray ids, const Board &board, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec); /** * @brief Refind not detected markers based on the already detected and the board layout * * @param image input image * @param board layout of markers in the board. * @param detectedCorners vector of already detected marker corners. * @param detectedIds vector of already detected marker identifiers. * @param rejectedCorners vector of rejected candidates during the marker detection process. * @param cameraMatrix optional input 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs optional vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param minRepDistance minimum distance between the corners of the rejected candidate and the * reprojected marker in order to consider it as a correspondence. * @param errorCorrectionRate rate of allowed erroneous bits respect to the error correction * capability of the used dictionary. -1 ignores the error correction step. * @param checkAllOrders Consider the four posible corner orders in the rejectedCorners array. * If it set to false, only the provided corner order is considered (default true). * @param recoveredIdxs Optional array to returns the indexes of the recovered candidates in the * original rejectedCorners array. * @param parameters marker detection parameters * * This function tries to find markers that were not detected in the basic detecMarkers function. * First, based on the current detected marker and the board layout, the function interpolates * the position of the missing markers. Then it tries to find correspondence between the reprojected * markers and the rejected candidates based on the minRepDistance and errorCorrectionRate * parameters. * If camera parameters and distortion coefficients are provided, missing markers are reprojected * using projectPoint function. If not, missing marker projections are interpolated using global * homography, and all the marker corners in the board must have the same Z coordinate. */ CV_EXPORTS void refineDetectedMarkers( InputArray image, const Board &board, InputOutputArrayOfArrays detectedCorners, InputOutputArray detectedIds, InputOutputArray rejectedCorners, InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray(), float minRepDistance = 10.f, float errorCorrectionRate = 3.f, bool checkAllOrders = true, OutputArray recoveredIdxs = noArray(), DetectorParameters parameters = DetectorParameters()); /** * @brief Draw detected markers in image * * @param image input/output image. It must have 1 or 3 channels. The number of channels is not * altered. * @param corners positions of marker corners on input image. * (e.g std::vector > ). For N detected markers, the dimensions of * this array should be Nx4. The order of the corners should be clockwise. * @param ids vector of identifiers for markers in markersCorners . * Optional, if not provided, ids are not painted. * @param borderColor color of marker borders. Rest of colors (text color and first corner color) * are calculated based on this one to improve visualization. * * Given an array of detected marker corners and its corresponding ids, this functions draws * the markers in the image. The marker borders are painted and the markers identifiers if provided. * Useful for debugging purposes. */ CV_EXPORTS void drawDetectedMarkers(InputOutputArray image, InputArrayOfArrays corners, InputArray ids = noArray(), Scalar borderColor = Scalar(0, 255, 0)); /** * @brief Draw coordinate system axis from pose estimation * * @param image input/output image. It must have 1 or 3 channels. The number of channels is not * altered. * @param cameraMatrix input 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvec rotation vector of the coordinate system that will be drawn. (@sa Rodrigues). * @param tvec translation vector of the coordinate system that will be drawn. * @param length length of the painted axis in the same unit than tvec (usually in meters) * * Given the pose estimation of a marker or board, this function draws the axis of the world * coordinate system, i.e. the system centered on the marker/board. Useful for debugging purposes. */ CV_EXPORTS void drawAxis(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, InputArray rvec, InputArray tvec, float length); /** * @brief Draw a canonical marker image * * @param dictionary dictionary of markers indicating the type of markers * @param id identifier of the marker that will be returned. It has to be a valid id * in the specified dictionary. * @param sidePixels size of the image in pixels * @param img output image with the marker * @param borderBits width of the marker border. * * This function returns a marker image in its canonical form (i.e. ready to be printed) */ CV_EXPORTS void drawMarker(Dictionary dictionary, int id, int sidePixels, OutputArray img, int borderBits = 1); /** * @brief Draw a planar board * * @param board layout of the board that will be drawn. The board should be planar, * z coordinate is ignored * @param outSize size of the output image in pixels. * @param img output image with the board. The size of this image will be outSize * and the board will be on the center, keeping the board proportions. * @param marginSize minimum margins (in pixels) of the board in the output image * @param borderBits width of the marker borders. * * This function return the image of a planar board, ready to be printed. It assumes * the Board layout specified is planar by ignoring the z coordinates of the object points. */ CV_EXPORTS void drawPlanarBoard(const Board &board, Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1); /** * @brief Calibrate a camera using aruco markers * * @param corners vector of detected marker corners in all frames. * The corners should have the same format returned by detectMarkers (@sa detectMarkers). * @param ids list of identifiers for each marker in corners * @param counter number of markers in each frame so that corners and ids can be split * @param board Marker Board layout * @param imageSize Size of the image used only to initialize the intrinsic camera matrix. * @param cameraMatrix Output 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . If CV\_CALIB\_USE\_INTRINSIC\_GUESS * and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be * initialized before calling the function. * @param distCoeffs Output vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each board view * (e.g. std::vector>). That is, each k-th rotation vector together with the corresponding * k-th translation vector (see the next output parameter description) brings the board pattern * from the model coordinate space (in which object points are specified) to the world coordinate * space, that is, a real position of the board pattern in the k-th pattern view (k=0.. *M* -1). * @param tvecs Output vector of translation vectors estimated for each pattern view. * @param flags flags Different flags for the calibration process (@sa calibrateCamera) * @param criteria Termination criteria for the iterative optimization algorithm. * * This function calibrates a camera using an Aruco Board. The function receives a list of * detected markers from several views of the Board. The process is similar to the chessboard * calibration in calibrateCamera(). The function returns the final re-projection error. */ CV_EXPORTS double calibrateCameraAruco( InputArrayOfArrays corners, InputArray ids, InputArray counter, const Board &board, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs = noArray(), OutputArrayOfArrays tvecs = noArray(), int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON)); //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/bgsegm.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_BGSEGM_HPP__ #define __OPENCV_BGSEGM_HPP__ #include "opencv2/video.hpp" #ifdef __cplusplus /** @defgroup bgsegm Improved Background-Foreground Segmentation Methods */ namespace cv { namespace bgsegm { //! @addtogroup bgsegm //! @{ /** @brief Gaussian Mixture-based Background/Foreground Segmentation Algorithm. The class implements the algorithm described in @cite KB2001 . */ class CV_EXPORTS_W BackgroundSubtractorMOG : public BackgroundSubtractor { public: CV_WRAP virtual int getHistory() const = 0; CV_WRAP virtual void setHistory(int nframes) = 0; CV_WRAP virtual int getNMixtures() const = 0; CV_WRAP virtual void setNMixtures(int nmix) = 0; CV_WRAP virtual double getBackgroundRatio() const = 0; CV_WRAP virtual void setBackgroundRatio(double backgroundRatio) = 0; CV_WRAP virtual double getNoiseSigma() const = 0; CV_WRAP virtual void setNoiseSigma(double noiseSigma) = 0; }; /** @brief Creates mixture-of-gaussian background subtractor @param history Length of the history. @param nmixtures Number of Gaussian mixtures. @param backgroundRatio Background ratio. @param noiseSigma Noise strength (standard deviation of the brightness or each color channel). 0 means some automatic value. */ CV_EXPORTS_W Ptr createBackgroundSubtractorMOG(int history=200, int nmixtures=5, double backgroundRatio=0.7, double noiseSigma=0); /** @brief Background Subtractor module based on the algorithm given in @cite Gold2012 . Takes a series of images and returns a sequence of mask (8UC1) images of the same size, where 255 indicates Foreground and 0 represents Background. This class implements an algorithm described in "Visual Tracking of Human Visitors under Variable-Lighting Conditions for a Responsive Audio Art Installation," A. Godbehere, A. Matsukawa, K. Goldberg, American Control Conference, Montreal, June 2012. */ class CV_EXPORTS_W BackgroundSubtractorGMG : public BackgroundSubtractor { public: /** @brief Returns total number of distinct colors to maintain in histogram. */ CV_WRAP virtual int getMaxFeatures() const = 0; /** @brief Sets total number of distinct colors to maintain in histogram. */ CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; /** @brief Returns the learning rate of the algorithm. It lies between 0.0 and 1.0. It determines how quickly features are "forgotten" from histograms. */ CV_WRAP virtual double getDefaultLearningRate() const = 0; /** @brief Sets the learning rate of the algorithm. */ CV_WRAP virtual void setDefaultLearningRate(double lr) = 0; /** @brief Returns the number of frames used to initialize background model. */ CV_WRAP virtual int getNumFrames() const = 0; /** @brief Sets the number of frames used to initialize background model. */ CV_WRAP virtual void setNumFrames(int nframes) = 0; /** @brief Returns the parameter used for quantization of color-space. It is the number of discrete levels in each channel to be used in histograms. */ CV_WRAP virtual int getQuantizationLevels() const = 0; /** @brief Sets the parameter used for quantization of color-space */ CV_WRAP virtual void setQuantizationLevels(int nlevels) = 0; /** @brief Returns the prior probability that each individual pixel is a background pixel. */ CV_WRAP virtual double getBackgroundPrior() const = 0; /** @brief Sets the prior probability that each individual pixel is a background pixel. */ CV_WRAP virtual void setBackgroundPrior(double bgprior) = 0; /** @brief Returns the kernel radius used for morphological operations */ CV_WRAP virtual int getSmoothingRadius() const = 0; /** @brief Sets the kernel radius used for morphological operations */ CV_WRAP virtual void setSmoothingRadius(int radius) = 0; /** @brief Returns the value of decision threshold. Decision value is the value above which pixel is determined to be FG. */ CV_WRAP virtual double getDecisionThreshold() const = 0; /** @brief Sets the value of decision threshold. */ CV_WRAP virtual void setDecisionThreshold(double thresh) = 0; /** @brief Returns the status of background model update */ CV_WRAP virtual bool getUpdateBackgroundModel() const = 0; /** @brief Sets the status of background model update */ CV_WRAP virtual void setUpdateBackgroundModel(bool update) = 0; /** @brief Returns the minimum value taken on by pixels in image sequence. Usually 0. */ CV_WRAP virtual double getMinVal() const = 0; /** @brief Sets the minimum value taken on by pixels in image sequence. */ CV_WRAP virtual void setMinVal(double val) = 0; /** @brief Returns the maximum value taken on by pixels in image sequence. e.g. 1.0 or 255. */ CV_WRAP virtual double getMaxVal() const = 0; /** @brief Sets the maximum value taken on by pixels in image sequence. */ CV_WRAP virtual void setMaxVal(double val) = 0; }; /** @brief Creates a GMG Background Subtractor @param initializationFrames number of frames used to initialize the background models. @param decisionThreshold Threshold value, above which it is marked foreground, else background. */ CV_EXPORTS_W Ptr createBackgroundSubtractorGMG(int initializationFrames=120, double decisionThreshold=0.8); //! @} } } #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/bioinspired/bioinspired.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/bioinspired.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/bioinspired/retina.hpp ================================================ /*#****************************************************************************** ** IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. ** ** By downloading, copying, installing or using the software you agree to this license. ** If you do not agree to this license, do not download, install, ** copy or use the software. ** ** ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) ** ** Creation - enhancement process 2007-2015 ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France ** ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). ** Refer to the following research paper for more information: ** Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book: ** Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. ** ** The retina filter includes the research contributions of phd/research collegues from which code has been redrawn by the author : ** _take a look at the retinacolor.hpp module to discover Brice Chaix de Lavarene color mosaicing/demosaicing and the reference paper: ** ====> B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007 ** _take a look at imagelogpolprojection.hpp to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. ** ====> more informations in the above cited Jeanny Heraults's book. ** ** License Agreement ** For Open Source Computer Vision Library ** ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** ** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2015, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. ** ** * Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and/or other materials provided with the distribution. ** ** * The name of the copyright holders may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** This software is provided by the copyright holders and contributors "as is" and ** any express or implied warranties, including, but not limited to, the implied ** warranties of merchantability and fitness for a particular purpose are disclaimed. ** In no event shall the Intel Corporation or contributors be liable for any direct, ** indirect, incidental, special, exemplary, or consequential damages ** (including, but not limited to, procurement of substitute goods or services; ** loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. *******************************************************************************/ #ifndef __OPENCV_BIOINSPIRED_RETINA_HPP__ #define __OPENCV_BIOINSPIRED_RETINA_HPP__ /** @file @date Jul 19, 2011 @author Alexandre Benoit */ #include "opencv2/core.hpp" // for all OpenCV core functionalities access, including cv::Exception support namespace cv{ namespace bioinspired{ //! @addtogroup bioinspired //! @{ enum { RETINA_COLOR_RANDOM, //!< each pixel position is either R, G or B in a random choice RETINA_COLOR_DIAGONAL,//!< color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR... RETINA_COLOR_BAYER//!< standard bayer sampling }; /** @brief retina model parameters structure For better clarity, check explenations on the comments of methods : setupOPLandIPLParvoChannel and setupIPLMagnoChannel Here is the default configuration file of the retina module. It gives results such as the first retina output shown on the top of this page. @code{xml} 1 1 7.5e-01 9.0e-01 5.3e-01 0.01 0.5 7. 7.5e-01 1 0. 0. 7. 2.0e+00 9.5e-01 0. 7. @endcode Here is the 'realistic" setup used to obtain the second retina output shown on the top of this page. @code{xml} 1 1 8.9e-01 9.0e-01 5.3e-01 0.3 0.5 7. 8.9e-01 1 0. 0. 7. 2.0e+00 9.5e-01 0. 7. @endcode */ struct RetinaParameters{ //! Outer Plexiform Layer (OPL) and Inner Plexiform Layer Parvocellular (IplParvo) parameters struct OPLandIplParvoParameters{ OPLandIplParvoParameters():colorMode(true), normaliseOutput(true), photoreceptorsLocalAdaptationSensitivity(0.75f), photoreceptorsTemporalConstant(0.9f), photoreceptorsSpatialConstant(0.53f), horizontalCellsGain(0.01f), hcellsTemporalConstant(0.5f), hcellsSpatialConstant(7.f), ganglionCellsSensitivity(0.75f) { } // default setup bool colorMode, normaliseOutput; float photoreceptorsLocalAdaptationSensitivity, photoreceptorsTemporalConstant, photoreceptorsSpatialConstant, horizontalCellsGain, hcellsTemporalConstant, hcellsSpatialConstant, ganglionCellsSensitivity; }; //! Inner Plexiform Layer Magnocellular channel (IplMagno) struct IplMagnoParameters{ IplMagnoParameters(): normaliseOutput(true), parasolCells_beta(0.f), parasolCells_tau(0.f), parasolCells_k(7.f), amacrinCellsTemporalCutFrequency(2.0f), V0CompressionParameter(0.95f), localAdaptintegration_tau(0.f), localAdaptintegration_k(7.f) { } // default setup bool normaliseOutput; float parasolCells_beta, parasolCells_tau, parasolCells_k, amacrinCellsTemporalCutFrequency, V0CompressionParameter, localAdaptintegration_tau, localAdaptintegration_k; }; OPLandIplParvoParameters OPLandIplParvo; IplMagnoParameters IplMagno; }; /** @brief class which allows the Gipsa/Listic Labs model to be used with OpenCV. This retina model allows spatio-temporal image processing (applied on still images, video sequences). As a summary, these are the retina model properties: - It applies a spectral whithening (mid-frequency details enhancement) - high frequency spatio-temporal noise reduction - low frequency luminance to be reduced (luminance range compression) - local logarithmic luminance compression allows details to be enhanced in low light conditions USE : this model can be used basically for spatio-temporal video effects but also for : _using the getParvo method output matrix : texture analysiswith enhanced signal to noise ratio and enhanced details robust against input images luminance ranges _using the getMagno method output matrix : motion analysis also with the previously cited properties for more information, reer to the following papers : Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. The retina filter includes the research contributions of phd/research collegues from which code has been redrawn by the author : take a look at the retinacolor.hpp module to discover Brice Chaix de Lavarene color mosaicing/demosaicing and the reference paper: B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007 take a look at imagelogpolprojection.hpp to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. more informations in the above cited Jeanny Heraults's book. */ class CV_EXPORTS_W Retina : public Algorithm { public: /** @brief Retreive retina input buffer size @return the retina input buffer size */ CV_WRAP virtual Size getInputSize()=0; /** @brief Retreive retina output buffer size that can be different from the input if a spatial log transformation is applied @return the retina output buffer size */ CV_WRAP virtual Size getOutputSize()=0; /** @brief Try to open an XML retina parameters file to adjust current retina instance setup - if the xml file does not exist, then default setup is applied - warning, Exceptions are thrown if read XML file is not valid @param retinaParameterFile the parameters filename @param applyDefaultSetupOnFailure set to true if an error must be thrown on error You can retreive the current parameers structure using method Retina::getParameters and update it before running method Retina::setup */ CV_WRAP virtual void setup(String retinaParameterFile="", const bool applyDefaultSetupOnFailure=true)=0; /** @overload @param fs the open Filestorage which contains retina parameters @param applyDefaultSetupOnFailure set to true if an error must be thrown on error */ virtual void setup(cv::FileStorage &fs, const bool applyDefaultSetupOnFailure=true)=0; /** @overload @param newParameters a parameters structures updated with the new target configuration. */ virtual void setup(RetinaParameters newParameters)=0; /** @return the current parameters setup */ virtual RetinaParameters getParameters()=0; /** @brief Outputs a string showing the used parameters setup @return a string which contains formated parameters information */ CV_WRAP virtual const String printSetup()=0; /** @brief Write xml/yml formated parameters information @param fs the filename of the xml file that will be open and writen with formatted parameters information */ CV_WRAP virtual void write( String fs ) const=0; /** @overload */ virtual void write( FileStorage& fs ) const=0; /** @brief Setup the OPL and IPL parvo channels (see biologocal model) OPL is referred as Outer Plexiform Layer of the retina, it allows the spatio-temporal filtering which withens the spectrum and reduces spatio-temporal noise while attenuating global luminance (low frequency energy) IPL parvo is the OPL next processing stage, it refers to a part of the Inner Plexiform layer of the retina, it allows high contours sensitivity in foveal vision. See reference papers for more informations. for more informations, please have a look at the paper Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 @param colorMode specifies if (true) color is processed of not (false) to then processing gray level image @param normaliseOutput specifies if (true) output is rescaled between 0 and 255 of not (false) @param photoreceptorsLocalAdaptationSensitivity the photoreceptors sensitivity renage is 0-1 (more log compression effect when value increases) @param photoreceptorsTemporalConstant the time constant of the first order low pass filter of the photoreceptors, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 1 frame @param photoreceptorsSpatialConstant the spatial constant of the first order low pass filter of the photoreceptors, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 1 pixel @param horizontalCellsGain gain of the horizontal cells network, if 0, then the mean value of the output is zero, if the parameter is near 1, then, the luminance is not filtered and is still reachable at the output, typicall value is 0 @param HcellsTemporalConstant the time constant of the first order low pass filter of the horizontal cells, use it to cut low temporal frequencies (local luminance variations), unit is frames, typical value is 1 frame, as the photoreceptors @param HcellsSpatialConstant the spatial constant of the first order low pass filter of the horizontal cells, use it to cut low spatial frequencies (local luminance), unit is pixels, typical value is 5 pixel, this value is also used for local contrast computing when computing the local contrast adaptation at the ganglion cells level (Inner Plexiform Layer parvocellular channel model) @param ganglionCellsSensitivity the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.7 */ CV_WRAP virtual void setupOPLandIPLParvoChannel(const bool colorMode=true, const bool normaliseOutput = true, const float photoreceptorsLocalAdaptationSensitivity=0.7f, const float photoreceptorsTemporalConstant=0.5f, const float photoreceptorsSpatialConstant=0.53f, const float horizontalCellsGain=0.f, const float HcellsTemporalConstant=1.f, const float HcellsSpatialConstant=7.f, const float ganglionCellsSensitivity=0.7f)=0; /** @brief Set parameters values for the Inner Plexiform Layer (IPL) magnocellular channel this channel processes signals output from OPL processing stage in peripheral vision, it allows motion information enhancement. It is decorrelated from the details channel. See reference papers for more details. @param normaliseOutput specifies if (true) output is rescaled between 0 and 255 of not (false) @param parasolCells_beta the low pass filter gain used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), typical value is 0 @param parasolCells_tau the low pass filter time constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is frame, typical value is 0 (immediate response) @param parasolCells_k the low pass filter spatial constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is pixels, typical value is 5 @param amacrinCellsTemporalCutFrequency the time constant of the first order high pass fiter of the magnocellular way (motion information channel), unit is frames, typical value is 1.2 @param V0CompressionParameter the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.95 @param localAdaptintegration_tau specifies the temporal constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation @param localAdaptintegration_k specifies the spatial constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation */ CV_WRAP virtual void setupIPLMagnoChannel(const bool normaliseOutput = true, const float parasolCells_beta=0.f, const float parasolCells_tau=0.f, const float parasolCells_k=7.f, const float amacrinCellsTemporalCutFrequency=1.2f, const float V0CompressionParameter=0.95f, const float localAdaptintegration_tau=0.f, const float localAdaptintegration_k=7.f)=0; /** @brief Method which allows retina to be applied on an input image, after run, encapsulated retina module is ready to deliver its outputs using dedicated acccessors, see getParvo and getMagno methods @param inputImage the input Mat image to be processed, can be gray level or BGR coded in any format (from 8bit to 16bits) */ CV_WRAP virtual void run(InputArray inputImage)=0; /** @brief Method which processes an image in the aim to correct its luminance correct backlight problems, enhance details in shadows. This method is designed to perform High Dynamic Range image tone mapping (compress \>8bit/pixel images to 8bit/pixel). This is a simplified version of the Retina Parvocellular model (simplified version of the run/getParvo methods call) since it does not include the spatio-temporal filter modelling the Outer Plexiform Layer of the retina that performs spectral whitening and many other stuff. However, it works great for tone mapping and in a faster way. Check the demos and experiments section to see examples and the way to perform tone mapping using the original retina model and the method. @param inputImage the input image to process (should be coded in float format : CV_32F, CV_32FC1, CV_32F_C3, CV_32F_C4, the 4th channel won't be considered). @param outputToneMappedImage the output 8bit/channel tone mapped image (CV_8U or CV_8UC3 format). */ CV_WRAP virtual void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage)=0; /** @brief Accessor of the details channel of the retina (models foveal vision). Warning, getParvoRAW methods return buffers that are not rescaled within range [0;255] while the non RAW method allows a normalized matrix to be retrieved. @param retinaOutput_parvo the output buffer (reallocated if necessary), format can be : - a Mat, this output is rescaled for standard 8bits image processing use in OpenCV - RAW methods actually return a 1D matrix (encoding is R1, R2, ... Rn, G1, G2, ..., Gn, B1, B2, ...Bn), this output is the original retina filter model output, without any quantification or rescaling. @see getParvoRAW */ CV_WRAP virtual void getParvo(OutputArray retinaOutput_parvo)=0; /** @brief Accessor of the details channel of the retina (models foveal vision). @see getParvo */ CV_WRAP virtual void getParvoRAW(OutputArray retinaOutput_parvo)=0; /** @brief Accessor of the motion channel of the retina (models peripheral vision). Warning, getMagnoRAW methods return buffers that are not rescaled within range [0;255] while the non RAW method allows a normalized matrix to be retrieved. @param retinaOutput_magno the output buffer (reallocated if necessary), format can be : - a Mat, this output is rescaled for standard 8bits image processing use in OpenCV - RAW methods actually return a 1D matrix (encoding is M1, M2,... Mn), this output is the original retina filter model output, without any quantification or rescaling. @see getMagnoRAW */ CV_WRAP virtual void getMagno(OutputArray retinaOutput_magno)=0; /** @brief Accessor of the motion channel of the retina (models peripheral vision). @see getMagno */ CV_WRAP virtual void getMagnoRAW(OutputArray retinaOutput_magno)=0; /** @overload */ CV_WRAP virtual const Mat getMagnoRAW() const=0; /** @overload */ CV_WRAP virtual const Mat getParvoRAW() const=0; /** @brief Activate color saturation as the final step of the color demultiplexing process -\> this saturation is a sigmoide function applied to each channel of the demultiplexed image. @param saturateColors boolean that activates color saturation (if true) or desactivate (if false) @param colorSaturationValue the saturation factor : a simple factor applied on the chrominance buffers */ CV_WRAP virtual void setColorSaturation(const bool saturateColors=true, const float colorSaturationValue=4.0f)=0; /** @brief Clears all retina buffers (equivalent to opening the eyes after a long period of eye close ;o) whatchout the temporal transition occuring just after this method call. */ CV_WRAP virtual void clearBuffers()=0; /** @brief Activate/desactivate the Magnocellular pathway processing (motion information extraction), by default, it is activated @param activate true if Magnocellular output should be activated, false if not... if activated, the Magnocellular output can be retrieved using the **getMagno** methods */ CV_WRAP virtual void activateMovingContoursProcessing(const bool activate)=0; /** @brief Activate/desactivate the Parvocellular pathway processing (contours information extraction), by default, it is activated @param activate true if Parvocellular (contours information extraction) output should be activated, false if not... if activated, the Parvocellular output can be retrieved using the Retina::getParvo methods */ CV_WRAP virtual void activateContoursProcessing(const bool activate)=0; }; //! @relates bioinspired::Retina //! @{ /** @overload */ CV_EXPORTS_W Ptr createRetina(Size inputSize); /** @brief Constructors from standardized interfaces : retreive a smart pointer to a Retina instance @param inputSize the input frame size @param colorMode the chosen processing mode : with or without color processing @param colorSamplingMethod specifies which kind of color sampling will be used : - cv::bioinspired::RETINA_COLOR_RANDOM: each pixel position is either R, G or B in a random choice - cv::bioinspired::RETINA_COLOR_DIAGONAL: color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR... - cv::bioinspired::RETINA_COLOR_BAYER: standard bayer sampling @param useRetinaLogSampling activate retina log sampling, if true, the 2 following parameters can be used @param reductionFactor only usefull if param useRetinaLogSampling=true, specifies the reduction factor of the output frame (as the center (fovea) is high resolution and corners can be underscaled, then a reduction of the output is allowed without precision leak @param samplingStrenght only usefull if param useRetinaLogSampling=true, specifies the strenght of the log scale that is applied */ CV_EXPORTS_W Ptr createRetina(Size inputSize, const bool colorMode, int colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const float reductionFactor=1.0f, const float samplingStrenght=10.0f); #ifdef HAVE_OPENCV_OCL Ptr createRetina_OCL(Size inputSize); Ptr createRetina_OCL(Size inputSize, const bool colorMode, int colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const float reductionFactor=1.0f, const float samplingStrenght=10.0f); #endif //! @} //! @} } } #endif /* __OPENCV_BIOINSPIRED_RETINA_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/bioinspired/retinafasttonemapping.hpp ================================================ /*#****************************************************************************** ** IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. ** ** By downloading, copying, installing or using the software you agree to this license. ** If you do not agree to this license, do not download, install, ** copy or use the software. ** ** ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) ** ** Creation - enhancement process 2007-2013 ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France ** ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). ** Refer to the following research paper for more information: ** Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book: ** Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. ** ** ** ** ** ** This class is based on image processing tools of the author and already used within the Retina class (this is the same code as method retina::applyFastToneMapping, but in an independent class, it is ligth from a memory requirement point of view). It implements an adaptation of the efficient tone mapping algorithm propose by David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: ** -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 ** ** ** License Agreement ** For Open Source Computer Vision Library ** ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** ** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. ** ** * Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and/or other materials provided with the distribution. ** ** * The name of the copyright holders may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** This software is provided by the copyright holders and contributors "as is" and ** any express or implied warranties, including, but not limited to, the implied ** warranties of merchantability and fitness for a particular purpose are disclaimed. ** In no event shall the Intel Corporation or contributors be liable for any direct, ** indirect, incidental, special, exemplary, or consequential damages ** (including, but not limited to, procurement of substitute goods or services; ** loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. *******************************************************************************/ #ifndef __OPENCV_BIOINSPIRED_RETINAFASTTONEMAPPING_HPP__ #define __OPENCV_BIOINSPIRED_RETINAFASTTONEMAPPING_HPP__ /** @file @date May 26, 2013 @author Alexandre Benoit */ #include "opencv2/core.hpp" // for all OpenCV core functionalities access, including cv::Exception support namespace cv{ namespace bioinspired{ //! @addtogroup bioinspired //! @{ /** @brief a wrapper class which allows the tone mapping algorithm of Meylan&al(2007) to be used with OpenCV. This algorithm is already implemented in thre Retina class (retina::applyFastToneMapping) but used it does not require all the retina model to be allocated. This allows a light memory use for low memory devices (smartphones, etc. As a summary, these are the model properties: - 2 stages of local luminance adaptation with a different local neighborhood for each. - first stage models the retina photorecetors local luminance adaptation - second stage models th ganglion cells local information adaptation - compared to the initial publication, this class uses spatio-temporal low pass filters instead of spatial only filters. this can help noise robustness and temporal stability for video sequence use cases. for more information, read to the following papers : Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 regarding spatio-temporal filter and the bigger retina model : Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. */ class CV_EXPORTS_W RetinaFastToneMapping : public Algorithm { public: /** @brief applies a luminance correction (initially High Dynamic Range (HDR) tone mapping) using only the 2 local adaptation stages of the retina parvocellular channel : photoreceptors level and ganlion cells level. Spatio temporal filtering is applied but limited to temporal smoothing and eventually high frequencies attenuation. This is a lighter method than the one available using the regular retina::run method. It is then faster but it does not include complete temporal filtering nor retina spectral whitening. Then, it can have a more limited effect on images with a very high dynamic range. This is an adptation of the original still image HDR tone mapping algorithm of David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 @param inputImage the input image to process RGB or gray levels @param outputToneMappedImage the output tone mapped image */ CV_WRAP virtual void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage)=0; /** @brief updates tone mapping behaviors by adjusing the local luminance computation area @param photoreceptorsNeighborhoodRadius the first stage local adaptation area @param ganglioncellsNeighborhoodRadius the second stage local adaptation area @param meanLuminanceModulatorK the factor applied to modulate the meanLuminance information (default is 1, see reference paper) */ CV_WRAP virtual void setup(const float photoreceptorsNeighborhoodRadius=3.f, const float ganglioncellsNeighborhoodRadius=1.f, const float meanLuminanceModulatorK=1.f)=0; }; //! @relates bioinspired::RetinaFastToneMapping CV_EXPORTS_W Ptr createRetinaFastToneMapping(Size inputSize); //! @} } } #endif /* __OPENCV_BIOINSPIRED_RETINAFASTTONEMAPPING_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/bioinspired/transientareassegmentationmodule.hpp ================================================ /*#****************************************************************************** ** IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. ** ** By downloading, copying, installing or using the software you agree to this license. ** If you do not agree to this license, do not download, install, ** copy or use the software. ** ** ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. ** TransientAreasSegmentationModule Use: extract areas that present spatio-temporal changes. ** => It should be used at the output of the cv::bioinspired::Retina::getMagnoRAW() output that enhances spatio-temporal changes ** ** Maintainers : Listic lab (code author current affiliation & applications) ** ** Creation - enhancement process 2007-2015 ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France ** ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). ** Refer to the following research paper for more information: ** Strat, S.T.; Benoit, A.; Lambert, P., "Retina enhanced bag of words descriptors for video classification," Signal Processing Conference (EUSIPCO), 2014 Proceedings of the 22nd European , vol., no., pp.1307,1311, 1-5 Sept. 2014 (http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6952461&isnumber=6951911) ** Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book: ** Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. ** ** ** License Agreement ** For Open Source Computer Vision Library ** ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** ** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2015, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. ** ** * Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and/or other materials provided with the distribution. ** ** * The name of the copyright holders may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** This software is provided by the copyright holders and contributors "as is" and ** any express or implied warranties, including, but not limited to, the implied ** warranties of merchantability and fitness for a particular purpose are disclaimed. ** In no event shall the Intel Corporation or contributors be liable for any direct, ** indirect, incidental, special, exemplary, or consequential damages ** (including, but not limited to, procurement of substitute goods or services; ** loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. *******************************************************************************/ #ifndef SEGMENTATIONMODULE_HPP_ #define SEGMENTATIONMODULE_HPP_ /** @file @date 2007-2013 @author Alexandre BENOIT, benoit.alexandre.vision@gmail.com */ #include "opencv2/core.hpp" // for all OpenCV core functionalities access, including cv::Exception support namespace cv { namespace bioinspired { //! @addtogroup bioinspired //! @{ /** @brief parameter structure that stores the transient events detector setup parameters */ struct SegmentationParameters{ // CV_EXPORTS_W_MAP to export to python native dictionnaries // default structure instance construction with default values SegmentationParameters(): thresholdON(100), thresholdOFF(100), localEnergy_temporalConstant(0.5), localEnergy_spatialConstant(5), neighborhoodEnergy_temporalConstant(1), neighborhoodEnergy_spatialConstant(15), contextEnergy_temporalConstant(1), contextEnergy_spatialConstant(75){}; // all properties list float thresholdON; float thresholdOFF; //! the time constant of the first order low pass filter, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 0.5 frame float localEnergy_temporalConstant; //! the spatial constant of the first order low pass filter, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 5 pixel float localEnergy_spatialConstant; //! local neighborhood energy filtering parameters : the aim is to get information about the energy neighborhood to perform a center surround energy analysis float neighborhoodEnergy_temporalConstant; float neighborhoodEnergy_spatialConstant; //! context neighborhood energy filtering parameters : the aim is to get information about the energy on a wide neighborhood area to filtered out local effects float contextEnergy_temporalConstant; float contextEnergy_spatialConstant; }; /** @brief class which provides a transient/moving areas segmentation module perform a locally adapted segmentation by using the retina magno input data Based on Alexandre BENOIT thesis: "Le système visuel humain au secours de la vision par ordinateur" 3 spatio temporal filters are used: - a first one which filters the noise and local variations of the input motion energy - a second (more powerfull low pass spatial filter) which gives the neighborhood motion energy the segmentation consists in the comparison of these both outputs, if the local motion energy is higher to the neighborhood otion energy, then the area is considered as moving and is segmented - a stronger third low pass filter helps decision by providing a smooth information about the "motion context" in a wider area */ class CV_EXPORTS_W TransientAreasSegmentationModule: public Algorithm { public: /** @brief return the sze of the manage input and output images */ CV_WRAP virtual Size getSize()=0; /** @brief try to open an XML segmentation parameters file to adjust current segmentation instance setup - if the xml file does not exist, then default setup is applied - warning, Exceptions are thrown if read XML file is not valid @param segmentationParameterFile : the parameters filename @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error */ CV_WRAP virtual void setup(String segmentationParameterFile="", const bool applyDefaultSetupOnFailure=true)=0; /** @brief try to open an XML segmentation parameters file to adjust current segmentation instance setup - if the xml file does not exist, then default setup is applied - warning, Exceptions are thrown if read XML file is not valid @param fs : the open Filestorage which contains segmentation parameters @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error */ virtual void setup(cv::FileStorage &fs, const bool applyDefaultSetupOnFailure=true)=0; /** @brief try to open an XML segmentation parameters file to adjust current segmentation instance setup - if the xml file does not exist, then default setup is applied - warning, Exceptions are thrown if read XML file is not valid @param newParameters : a parameters structures updated with the new target configuration */ virtual void setup(SegmentationParameters newParameters)=0; /** @brief return the current parameters setup */ virtual SegmentationParameters getParameters()=0; /** @brief parameters setup display method @return a string which contains formatted parameters information */ CV_WRAP virtual const String printSetup()=0; /** @brief write xml/yml formated parameters information @param fs : the filename of the xml file that will be open and writen with formatted parameters information */ CV_WRAP virtual void write( String fs ) const=0; /** @brief write xml/yml formated parameters information @param fs : a cv::Filestorage object ready to be filled */ virtual void write( cv::FileStorage& fs ) const=0; /** @brief main processing method, get result using methods getSegmentationPicture() @param inputToSegment : the image to process, it must match the instance buffer size ! @param channelIndex : the channel to process in case of multichannel images */ CV_WRAP virtual void run(InputArray inputToSegment, const int channelIndex=0)=0; /** @brief access function @return the last segmentation result: a boolean picture which is resampled between 0 and 255 for a display purpose */ CV_WRAP virtual void getSegmentationPicture(OutputArray transientAreas)=0; /** @brief cleans all the buffers of the instance */ CV_WRAP virtual void clearAllBuffers()=0; }; /** @brief allocator @param inputSize : size of the images input to segment (output will be the same size) @relates bioinspired::TransientAreasSegmentationModule */ CV_EXPORTS_W Ptr createTransientAreasSegmentationModule(Size inputSize); //! @} }} // namespaces end : cv and bioinspired #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/bioinspired.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_BIOINSPIRED_HPP__ #define __OPENCV_BIOINSPIRED_HPP__ #include "opencv2/core.hpp" #include "opencv2/bioinspired/retina.hpp" #include "opencv2/bioinspired/retinafasttonemapping.hpp" #include "opencv2/bioinspired/transientareassegmentationmodule.hpp" /** @defgroup bioinspired Biologically inspired vision models and derivated tools The module provides biological visual systems models (human visual system and others). It also provides derivated objects that take advantage of those bio-inspired models. @ref bioinspired_retina */ #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/calib3d/calib3d.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/calib3d.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/calib3d/calib3d_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CALIB3D_C_H__ #define __OPENCV_CALIB3D_C_H__ #include "opencv2/core/core_c.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup calib3d_c @{ */ /****************************************************************************************\ * Camera Calibration, Pose Estimation and Stereo * \****************************************************************************************/ typedef struct CvPOSITObject CvPOSITObject; /* Allocates and initializes CvPOSITObject structure before doing cvPOSIT */ CVAPI(CvPOSITObject*) cvCreatePOSITObject( CvPoint3D32f* points, int point_count ); /* Runs POSIT (POSe from ITeration) algorithm for determining 3d position of an object given its model and projection in a weak-perspective case */ CVAPI(void) cvPOSIT( CvPOSITObject* posit_object, CvPoint2D32f* image_points, double focal_length, CvTermCriteria criteria, float* rotation_matrix, float* translation_vector); /* Releases CvPOSITObject structure */ CVAPI(void) cvReleasePOSITObject( CvPOSITObject** posit_object ); /* updates the number of RANSAC iterations */ CVAPI(int) cvRANSACUpdateNumIters( double p, double err_prob, int model_points, int max_iters ); CVAPI(void) cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst ); /* Calculates fundamental matrix given a set of corresponding points */ #define CV_FM_7POINT 1 #define CV_FM_8POINT 2 #define CV_LMEDS 4 #define CV_RANSAC 8 #define CV_FM_LMEDS_ONLY CV_LMEDS #define CV_FM_RANSAC_ONLY CV_RANSAC #define CV_FM_LMEDS CV_LMEDS #define CV_FM_RANSAC CV_RANSAC enum { CV_ITERATIVE = 0, CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" CV_P3P = 2, // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem" CV_DLS = 3 // Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP" }; CVAPI(int) cvFindFundamentalMat( const CvMat* points1, const CvMat* points2, CvMat* fundamental_matrix, int method CV_DEFAULT(CV_FM_RANSAC), double param1 CV_DEFAULT(3.), double param2 CV_DEFAULT(0.99), CvMat* status CV_DEFAULT(NULL) ); /* For each input point on one of images computes parameters of the corresponding epipolar line on the other image */ CVAPI(void) cvComputeCorrespondEpilines( const CvMat* points, int which_image, const CvMat* fundamental_matrix, CvMat* correspondent_lines ); /* Triangulation functions */ CVAPI(void) cvTriangulatePoints(CvMat* projMatr1, CvMat* projMatr2, CvMat* projPoints1, CvMat* projPoints2, CvMat* points4D); CVAPI(void) cvCorrectMatches(CvMat* F, CvMat* points1, CvMat* points2, CvMat* new_points1, CvMat* new_points2); /* Computes the optimal new camera matrix according to the free scaling parameter alpha: alpha=0 - only valid pixels will be retained in the undistorted image alpha=1 - all the source image pixels will be retained in the undistorted image */ CVAPI(void) cvGetOptimalNewCameraMatrix( const CvMat* camera_matrix, const CvMat* dist_coeffs, CvSize image_size, double alpha, CvMat* new_camera_matrix, CvSize new_imag_size CV_DEFAULT(cvSize(0,0)), CvRect* valid_pixel_ROI CV_DEFAULT(0), int center_principal_point CV_DEFAULT(0)); /* Converts rotation vector to rotation matrix or vice versa */ CVAPI(int) cvRodrigues2( const CvMat* src, CvMat* dst, CvMat* jacobian CV_DEFAULT(0) ); /* Finds perspective transformation between the object plane and image (view) plane */ CVAPI(int) cvFindHomography( const CvMat* src_points, const CvMat* dst_points, CvMat* homography, int method CV_DEFAULT(0), double ransacReprojThreshold CV_DEFAULT(3), CvMat* mask CV_DEFAULT(0), int maxIters CV_DEFAULT(2000), double confidence CV_DEFAULT(0.995)); /* Computes RQ decomposition for 3x3 matrices */ CVAPI(void) cvRQDecomp3x3( const CvMat *matrixM, CvMat *matrixR, CvMat *matrixQ, CvMat *matrixQx CV_DEFAULT(NULL), CvMat *matrixQy CV_DEFAULT(NULL), CvMat *matrixQz CV_DEFAULT(NULL), CvPoint3D64f *eulerAngles CV_DEFAULT(NULL)); /* Computes projection matrix decomposition */ CVAPI(void) cvDecomposeProjectionMatrix( const CvMat *projMatr, CvMat *calibMatr, CvMat *rotMatr, CvMat *posVect, CvMat *rotMatrX CV_DEFAULT(NULL), CvMat *rotMatrY CV_DEFAULT(NULL), CvMat *rotMatrZ CV_DEFAULT(NULL), CvPoint3D64f *eulerAngles CV_DEFAULT(NULL)); /* Computes d(AB)/dA and d(AB)/dB */ CVAPI(void) cvCalcMatMulDeriv( const CvMat* A, const CvMat* B, CvMat* dABdA, CvMat* dABdB ); /* Computes r3 = rodrigues(rodrigues(r2)*rodrigues(r1)), t3 = rodrigues(r2)*t1 + t2 and the respective derivatives */ CVAPI(void) cvComposeRT( const CvMat* _rvec1, const CvMat* _tvec1, const CvMat* _rvec2, const CvMat* _tvec2, CvMat* _rvec3, CvMat* _tvec3, CvMat* dr3dr1 CV_DEFAULT(0), CvMat* dr3dt1 CV_DEFAULT(0), CvMat* dr3dr2 CV_DEFAULT(0), CvMat* dr3dt2 CV_DEFAULT(0), CvMat* dt3dr1 CV_DEFAULT(0), CvMat* dt3dt1 CV_DEFAULT(0), CvMat* dt3dr2 CV_DEFAULT(0), CvMat* dt3dt2 CV_DEFAULT(0) ); /* Projects object points to the view plane using the specified extrinsic and intrinsic camera parameters */ CVAPI(void) cvProjectPoints2( const CvMat* object_points, const CvMat* rotation_vector, const CvMat* translation_vector, const CvMat* camera_matrix, const CvMat* distortion_coeffs, CvMat* image_points, CvMat* dpdrot CV_DEFAULT(NULL), CvMat* dpdt CV_DEFAULT(NULL), CvMat* dpdf CV_DEFAULT(NULL), CvMat* dpdc CV_DEFAULT(NULL), CvMat* dpddist CV_DEFAULT(NULL), double aspect_ratio CV_DEFAULT(0)); /* Finds extrinsic camera parameters from a few known corresponding point pairs and intrinsic parameters */ CVAPI(void) cvFindExtrinsicCameraParams2( const CvMat* object_points, const CvMat* image_points, const CvMat* camera_matrix, const CvMat* distortion_coeffs, CvMat* rotation_vector, CvMat* translation_vector, int use_extrinsic_guess CV_DEFAULT(0) ); /* Computes initial estimate of the intrinsic camera parameters in case of planar calibration target (e.g. chessboard) */ CVAPI(void) cvInitIntrinsicParams2D( const CvMat* object_points, const CvMat* image_points, const CvMat* npoints, CvSize image_size, CvMat* camera_matrix, double aspect_ratio CV_DEFAULT(1.) ); #define CV_CALIB_CB_ADAPTIVE_THRESH 1 #define CV_CALIB_CB_NORMALIZE_IMAGE 2 #define CV_CALIB_CB_FILTER_QUADS 4 #define CV_CALIB_CB_FAST_CHECK 8 // Performs a fast check if a chessboard is in the input image. This is a workaround to // a problem of cvFindChessboardCorners being slow on images with no chessboard // - src: input image // - size: chessboard size // Returns 1 if a chessboard can be in this image and findChessboardCorners should be called, // 0 if there is no chessboard, -1 in case of error CVAPI(int) cvCheckChessboard(IplImage* src, CvSize size); /* Detects corners on a chessboard calibration pattern */ CVAPI(int) cvFindChessboardCorners( const void* image, CvSize pattern_size, CvPoint2D32f* corners, int* corner_count CV_DEFAULT(NULL), int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE) ); /* Draws individual chessboard corners or the whole chessboard detected */ CVAPI(void) cvDrawChessboardCorners( CvArr* image, CvSize pattern_size, CvPoint2D32f* corners, int count, int pattern_was_found ); #define CV_CALIB_USE_INTRINSIC_GUESS 1 #define CV_CALIB_FIX_ASPECT_RATIO 2 #define CV_CALIB_FIX_PRINCIPAL_POINT 4 #define CV_CALIB_ZERO_TANGENT_DIST 8 #define CV_CALIB_FIX_FOCAL_LENGTH 16 #define CV_CALIB_FIX_K1 32 #define CV_CALIB_FIX_K2 64 #define CV_CALIB_FIX_K3 128 #define CV_CALIB_FIX_K4 2048 #define CV_CALIB_FIX_K5 4096 #define CV_CALIB_FIX_K6 8192 #define CV_CALIB_RATIONAL_MODEL 16384 #define CV_CALIB_THIN_PRISM_MODEL 32768 #define CV_CALIB_FIX_S1_S2_S3_S4 65536 #define CV_CALIB_TILTED_MODEL 262144 #define CV_CALIB_FIX_TAUX_TAUY 524288 /* Finds intrinsic and extrinsic camera parameters from a few views of known calibration pattern */ CVAPI(double) cvCalibrateCamera2( const CvMat* object_points, const CvMat* image_points, const CvMat* point_counts, CvSize image_size, CvMat* camera_matrix, CvMat* distortion_coeffs, CvMat* rotation_vectors CV_DEFAULT(NULL), CvMat* translation_vectors CV_DEFAULT(NULL), int flags CV_DEFAULT(0), CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,DBL_EPSILON)) ); /* Computes various useful characteristics of the camera from the data computed by cvCalibrateCamera2 */ CVAPI(void) cvCalibrationMatrixValues( const CvMat *camera_matrix, CvSize image_size, double aperture_width CV_DEFAULT(0), double aperture_height CV_DEFAULT(0), double *fovx CV_DEFAULT(NULL), double *fovy CV_DEFAULT(NULL), double *focal_length CV_DEFAULT(NULL), CvPoint2D64f *principal_point CV_DEFAULT(NULL), double *pixel_aspect_ratio CV_DEFAULT(NULL)); #define CV_CALIB_FIX_INTRINSIC 256 #define CV_CALIB_SAME_FOCAL_LENGTH 512 /* Computes the transformation from one camera coordinate system to another one from a few correspondent views of the same calibration target. Optionally, calibrates both cameras */ CVAPI(double) cvStereoCalibrate( const CvMat* object_points, const CvMat* image_points1, const CvMat* image_points2, const CvMat* npoints, CvMat* camera_matrix1, CvMat* dist_coeffs1, CvMat* camera_matrix2, CvMat* dist_coeffs2, CvSize image_size, CvMat* R, CvMat* T, CvMat* E CV_DEFAULT(0), CvMat* F CV_DEFAULT(0), int flags CV_DEFAULT(CV_CALIB_FIX_INTRINSIC), CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,1e-6)) ); #define CV_CALIB_ZERO_DISPARITY 1024 /* Computes 3D rotations (+ optional shift) for each camera coordinate system to make both views parallel (=> to make all the epipolar lines horizontal or vertical) */ CVAPI(void) cvStereoRectify( const CvMat* camera_matrix1, const CvMat* camera_matrix2, const CvMat* dist_coeffs1, const CvMat* dist_coeffs2, CvSize image_size, const CvMat* R, const CvMat* T, CvMat* R1, CvMat* R2, CvMat* P1, CvMat* P2, CvMat* Q CV_DEFAULT(0), int flags CV_DEFAULT(CV_CALIB_ZERO_DISPARITY), double alpha CV_DEFAULT(-1), CvSize new_image_size CV_DEFAULT(cvSize(0,0)), CvRect* valid_pix_ROI1 CV_DEFAULT(0), CvRect* valid_pix_ROI2 CV_DEFAULT(0)); /* Computes rectification transformations for uncalibrated pair of images using a set of point correspondences */ CVAPI(int) cvStereoRectifyUncalibrated( const CvMat* points1, const CvMat* points2, const CvMat* F, CvSize img_size, CvMat* H1, CvMat* H2, double threshold CV_DEFAULT(5)); /* stereo correspondence parameters and functions */ #define CV_STEREO_BM_NORMALIZED_RESPONSE 0 #define CV_STEREO_BM_XSOBEL 1 /* Block matching algorithm structure */ typedef struct CvStereoBMState { // pre-filtering (normalization of input images) int preFilterType; // =CV_STEREO_BM_NORMALIZED_RESPONSE now int preFilterSize; // averaging window size: ~5x5..21x21 int preFilterCap; // the output of pre-filtering is clipped by [-preFilterCap,preFilterCap] // correspondence using Sum of Absolute Difference (SAD) int SADWindowSize; // ~5x5..21x21 int minDisparity; // minimum disparity (can be negative) int numberOfDisparities; // maximum disparity - minimum disparity (> 0) // post-filtering int textureThreshold; // the disparity is only computed for pixels // with textured enough neighborhood int uniquenessRatio; // accept the computed disparity d* only if // SAD(d) >= SAD(d*)*(1 + uniquenessRatio/100.) // for any d != d*+/-1 within the search range. int speckleWindowSize; // disparity variation window int speckleRange; // acceptable range of variation in window int trySmallerWindows; // if 1, the results may be more accurate, // at the expense of slower processing CvRect roi1, roi2; int disp12MaxDiff; // temporary buffers CvMat* preFilteredImg0; CvMat* preFilteredImg1; CvMat* slidingSumBuf; CvMat* cost; CvMat* disp; } CvStereoBMState; #define CV_STEREO_BM_BASIC 0 #define CV_STEREO_BM_FISH_EYE 1 #define CV_STEREO_BM_NARROW 2 CVAPI(CvStereoBMState*) cvCreateStereoBMState(int preset CV_DEFAULT(CV_STEREO_BM_BASIC), int numberOfDisparities CV_DEFAULT(0)); CVAPI(void) cvReleaseStereoBMState( CvStereoBMState** state ); CVAPI(void) cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right, CvArr* disparity, CvStereoBMState* state ); CVAPI(CvRect) cvGetValidDisparityROI( CvRect roi1, CvRect roi2, int minDisparity, int numberOfDisparities, int SADWindowSize ); CVAPI(void) cvValidateDisparity( CvArr* disparity, const CvArr* cost, int minDisparity, int numberOfDisparities, int disp12MaxDiff CV_DEFAULT(1) ); /* Reprojects the computed disparity image to the 3D space using the specified 4x4 matrix */ CVAPI(void) cvReprojectImageTo3D( const CvArr* disparityImage, CvArr* _3dImage, const CvMat* Q, int handleMissingValues CV_DEFAULT(0) ); /** @} calib3d_c */ #ifdef __cplusplus } // extern "C" ////////////////////////////////////////////////////////////////////////////////////////// class CV_EXPORTS CvLevMarq { public: CvLevMarq(); CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), bool completeSymmFlag=false ); ~CvLevMarq(); void init( int nparams, int nerrs, CvTermCriteria criteria= cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), bool completeSymmFlag=false ); bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); void clear(); void step(); enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; cv::Ptr mask; cv::Ptr prevParam; cv::Ptr param; cv::Ptr J; cv::Ptr err; cv::Ptr JtJ; cv::Ptr JtJN; cv::Ptr JtErr; cv::Ptr JtJV; cv::Ptr JtJW; double prevErrNorm, errNorm; int lambdaLg10; CvTermCriteria criteria; int state; int iters; bool completeSymmFlag; int solveMethod; }; #endif #endif /* __OPENCV_CALIB3D_C_H__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/calib3d.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CALIB3D_HPP__ #define __OPENCV_CALIB3D_HPP__ #include "opencv2/core.hpp" #include "opencv2/features2d.hpp" #include "opencv2/core/affine.hpp" /** @defgroup calib3d Camera Calibration and 3D Reconstruction The functions in this section use a so-called pinhole camera model. In this model, a scene view is formed by projecting 3D points into the image plane using a perspective transformation. \f[s \; m' = A [R|t] M'\f] or \f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \begin{bmatrix} r_{11} & r_{12} & r_{13} & t_1 \\ r_{21} & r_{22} & r_{23} & t_2 \\ r_{31} & r_{32} & r_{33} & t_3 \end{bmatrix} \begin{bmatrix} X \\ Y \\ Z \\ 1 \end{bmatrix}\f] where: - \f$(X, Y, Z)\f$ are the coordinates of a 3D point in the world coordinate space - \f$(u, v)\f$ are the coordinates of the projection point in pixels - \f$A\f$ is a camera matrix, or a matrix of intrinsic parameters - \f$(cx, cy)\f$ is a principal point that is usually at the image center - \f$fx, fy\f$ are the focal lengths expressed in pixel units. Thus, if an image from the camera is scaled by a factor, all of these parameters should be scaled (multiplied/divided, respectively) by the same factor. The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can be re-used as long as the focal length is fixed (in case of zoom lens). The joint rotation-translation matrix \f$[R|t]\f$ is called a matrix of extrinsic parameters. It is used to describe the camera motion around a static scene, or vice versa, rigid motion of an object in front of a still camera. That is, \f$[R|t]\f$ translates coordinates of a point \f$(X, Y, Z)\f$ to a coordinate system, fixed with respect to the camera. The transformation above is equivalent to the following (when \f$z \ne 0\f$ ): \f[\begin{array}{l} \vecthree{x}{y}{z} = R \vecthree{X}{Y}{Z} + t \\ x' = x/z \\ y' = y/z \\ u = f_x*x' + c_x \\ v = f_y*y' + c_y \end{array}\f] Real lenses usually have some distortion, mostly radial distortion and slight tangential distortion. So, the above model is extended as: \f[\begin{array}{l} \vecthree{x}{y}{z} = R \vecthree{X}{Y}{Z} + t \\ x' = x/z \\ y' = y/z \\ x'' = x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\ y'' = y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ \text{where} \quad r^2 = x'^2 + y'^2 \\ u = f_x*x'' + c_x \\ v = f_y*y'' + c_y \end{array}\f] \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$ are radial distortion coefficients. \f$p_1\f$ and \f$p_2\f$ are tangential distortion coefficients. \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$, are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV. In some cases the image sensor may be tilted in order to focus an oblique plane in front of the camera (Scheimpfug condition). This can be useful for particle image velocimetry (PIV) or triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and \f$y''\f$. This distortion can be modelled in the following way, see e.g. @cite Louhichi07. \f[\begin{array}{l} s\vecthree{x'''}{y'''}{1} = \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)} {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} {0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\ u = f_x*x''' + c_x \\ v = f_y*y''' + c_y \end{array}\f] where the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter \f$\tau_x\f$ and \f$\tau_y\f$, respectively, \f[ R(\tau_x, \tau_y) = \vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)} \vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} = \vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)} {0}{\cos(\tau_x)}{\sin(\tau_x)} {\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}. \f] In the functions below the coefficients are passed or returned as \f[(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f] vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$ . The distortion coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera parameters. And they remain the same regardless of the captured image resolution. If, for example, a camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$, \f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately. The functions below use the above model to do the following: - Project 3D points to the image plane given intrinsic and extrinsic parameters. - Compute extrinsic parameters given intrinsic parameters, a few 3D points, and their projections. - Estimate intrinsic and extrinsic camera parameters from several views of a known calibration pattern (every view is described by several 3D-2D point correspondences). - Estimate the relative position and orientation of the stereo camera "heads" and compute the *rectification* transformation that makes the camera optical axes parallel. @note - A calibration sample for 3 cameras in horizontal position can be found at opencv_source_code/samples/cpp/3calibration.cpp - A calibration sample based on a sequence of images can be found at opencv_source_code/samples/cpp/calibration.cpp - A calibration sample in order to do 3D reconstruction can be found at opencv_source_code/samples/cpp/build3dmodel.cpp - A calibration sample of an artificially generated camera and chessboard patterns can be found at opencv_source_code/samples/cpp/calibration_artificial.cpp - A calibration example on stereo calibration can be found at opencv_source_code/samples/cpp/stereo_calib.cpp - A calibration example on stereo matching can be found at opencv_source_code/samples/cpp/stereo_match.cpp - (Python) A camera calibration sample can be found at opencv_source_code/samples/python/calibrate.py @{ @defgroup calib3d_fisheye Fisheye camera model Definitions: Let P be a point in 3D of coordinates X in the world reference frame (stored in the matrix X) The coordinate vector of P in the camera reference frame is: \f[Xc = R X + T\f] where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om); call x, y and z the 3 coordinates of Xc: \f[x = Xc_1 \\ y = Xc_2 \\ z = Xc_3\f] The pinehole projection coordinates of P is [a; b] where \f[a = x / z \ and \ b = y / z \\ r^2 = a^2 + b^2 \\ \theta = atan(r)\f] Fisheye distortion: \f[\theta_d = \theta (1 + k_1 \theta^2 + k_2 \theta^4 + k_3 \theta^6 + k_4 \theta^8)\f] The distorted point coordinates are [x'; y'] where \f[x' = (\theta_d / r) x \\ y' = (\theta_d / r) y \f] Finally, conversion into pixel coordinates: The final pixel coordinates vector [u; v] where: \f[u = f_x (x' + \alpha y') + c_x \\ v = f_y yy + c_y\f] @defgroup calib3d_c C API @} */ namespace cv { //! @addtogroup calib3d //! @{ //! type of the robust estimation algorithm enum { LMEDS = 4, //!< least-median algorithm RANSAC = 8, //!< RANSAC algorithm RHO = 16 //!< RHO algorithm }; enum { SOLVEPNP_ITERATIVE = 0, SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete SOLVEPNP_DLS = 3, //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct SOLVEPNP_UPNP = 4 //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive }; enum { CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2, CALIB_CB_FILTER_QUADS = 4, CALIB_CB_FAST_CHECK = 8 }; enum { CALIB_CB_SYMMETRIC_GRID = 1, CALIB_CB_ASYMMETRIC_GRID = 2, CALIB_CB_CLUSTERING = 4 }; enum { CALIB_USE_INTRINSIC_GUESS = 0x00001, CALIB_FIX_ASPECT_RATIO = 0x00002, CALIB_FIX_PRINCIPAL_POINT = 0x00004, CALIB_ZERO_TANGENT_DIST = 0x00008, CALIB_FIX_FOCAL_LENGTH = 0x00010, CALIB_FIX_K1 = 0x00020, CALIB_FIX_K2 = 0x00040, CALIB_FIX_K3 = 0x00080, CALIB_FIX_K4 = 0x00800, CALIB_FIX_K5 = 0x01000, CALIB_FIX_K6 = 0x02000, CALIB_RATIONAL_MODEL = 0x04000, CALIB_THIN_PRISM_MODEL = 0x08000, CALIB_FIX_S1_S2_S3_S4 = 0x10000, CALIB_TILTED_MODEL = 0x40000, CALIB_FIX_TAUX_TAUY = 0x80000, // only for stereo CALIB_FIX_INTRINSIC = 0x00100, CALIB_SAME_FOCAL_LENGTH = 0x00200, // for stereo rectification CALIB_ZERO_DISPARITY = 0x00400, CALIB_USE_LU = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise }; //! the algorithm for finding fundamental matrix enum { FM_7POINT = 1, //!< 7-point algorithm FM_8POINT = 2, //!< 8-point algorithm FM_LMEDS = 4, //!< least-median algorithm FM_RANSAC = 8 //!< RANSAC algorithm }; /** @brief Converts a rotation matrix to a rotation vector or vice versa. @param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). @param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively. @param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial derivatives of the output array components with respect to the input array components. \f[\begin{array}{l} \theta \leftarrow norm(r) \\ r \leftarrow r/ \theta \\ R = \cos{\theta} I + (1- \cos{\theta} ) r r^T + \sin{\theta} \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} \end{array}\f] Inverse transformation can be also done easily, since \f[\sin ( \theta ) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} = \frac{R - R^T}{2}\f] A rotation vector is a convenient and most compact representation of a rotation matrix (since any rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry optimization procedures like calibrateCamera, stereoCalibrate, or solvePnP . */ CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() ); /** @brief Finds a perspective transformation between two planes. @param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2 or vector\ . @param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or a vector\ . @param method Method used to computed a homography matrix. The following methods are possible: - **0** - a regular method using all the points - **RANSAC** - RANSAC-based robust method - **LMEDS** - Least-Median robust method - **RHO** - PROSAC-based robust method @param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier (used in the RANSAC and RHO methods only). That is, if \f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} * \texttt{srcPoints} _i) \| > \texttt{ransacReprojThreshold}\f] then the point \f$i\f$ is considered an outlier. If srcPoints and dstPoints are measured in pixels, it usually makes sense to set this parameter somewhere in the range of 1 to 10. @param mask Optional output mask set by a robust method ( RANSAC or LMEDS ). Note that the input mask values are ignored. @param maxIters The maximum number of RANSAC iterations, 2000 is the maximum it can be. @param confidence Confidence level, between 0 and 1. The functions find and return the perspective transformation \f$H\f$ between the source and the destination planes: \f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] so that the back-projection error \f[\sum _i \left ( x'_i- \frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2+ \left ( y'_i- \frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2\f] is minimized. If the parameter method is set to the default value 0, the function uses all the point pairs to compute an initial homography estimate with a simple least-squares scheme. However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective transformation (that is, there are some outliers), this initial estimate will be poor. In this case, you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different random subsets of the corresponding point pairs (of four pairs each), estimate the homography matrix using this subset and a simple least-square algorithm, and then compute the quality/goodness of the computed homography (which is the number of inliers for RANSAC or the median re-projection error for LMeDs). The best subset is then used to produce the initial estimate of the homography matrix and the mask of inliers/outliers. Regardless of the method, robust or not, the computed homography matrix is refined further (using inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the re-projection error even more. The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to distinguish inliers from outliers. The method LMeDS does not need any threshold but it works correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the noise is rather small, use the default method (method=0). The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is determined up to a scale. Thus, it is normalized so that \f$h_{33}=1\f$. Note that whenever an H matrix cannot be estimated, an empty one will be returned. @sa getAffineTransform, getPerspectiveTransform, estimateRigidTransform, warpPerspective, perspectiveTransform @note - A example on calculating a homography for image matching can be found at opencv_source_code/samples/cpp/video_homography.cpp */ CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints, int method = 0, double ransacReprojThreshold = 3, OutputArray mask=noArray(), const int maxIters = 2000, const double confidence = 0.995); /** @overload */ CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints, OutputArray mask, int method = 0, double ransacReprojThreshold = 3 ); /** @brief Computes an RQ decomposition of 3x3 matrices. @param src 3x3 input matrix. @param mtxR Output 3x3 upper-triangular matrix. @param mtxQ Output 3x3 orthogonal matrix. @param Qx Optional output 3x3 rotation matrix around x-axis. @param Qy Optional output 3x3 rotation matrix around y-axis. @param Qz Optional output 3x3 rotation matrix around z-axis. The function computes a RQ decomposition using the given rotations. This function is used in decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera and a rotation matrix. It optionally returns three rotation matrices, one for each axis, and the three Euler angles in degrees (as the return value) that could be used in OpenGL. Note, there is always more than one sequence of rotations about the three principle axes that results in the same orientation of an object, eg. see @cite Slabaugh . Returned tree rotation matrices and corresponding three Euler angules are only one of the possible solutions. */ CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, OutputArray Qx = noArray(), OutputArray Qy = noArray(), OutputArray Qz = noArray()); /** @brief Decomposes a projection matrix into a rotation matrix and a camera matrix. @param projMatrix 3x4 input projection matrix P. @param cameraMatrix Output 3x3 camera matrix K. @param rotMatrix Output 3x3 external rotation matrix R. @param transVect Output 4x1 translation vector T. @param rotMatrixX Optional 3x3 rotation matrix around x-axis. @param rotMatrixY Optional 3x3 rotation matrix around y-axis. @param rotMatrixZ Optional 3x3 rotation matrix around z-axis. @param eulerAngles Optional three-element vector containing three Euler angles of rotation in degrees. The function computes a decomposition of a projection matrix into a calibration and a rotation matrix and the position of a camera. It optionally returns three rotation matrices, one for each axis, and three Euler angles that could be used in OpenGL. Note, there is always more than one sequence of rotations about the three principle axes that results in the same orientation of an object, eg. see @cite Slabaugh . Returned tree rotation matrices and corresponding three Euler angules are only one of the possible solutions. The function is based on RQDecomp3x3 . */ CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix, OutputArray rotMatrix, OutputArray transVect, OutputArray rotMatrixX = noArray(), OutputArray rotMatrixY = noArray(), OutputArray rotMatrixZ = noArray(), OutputArray eulerAngles =noArray() ); /** @brief Computes partial derivatives of the matrix product for each multiplied matrix. @param A First multiplied matrix. @param B Second multiplied matrix. @param dABdA First output derivative matrix d(A\*B)/dA of size \f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ . @param dABdB Second output derivative matrix d(A\*B)/dB of size \f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ . The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to the elements of each of the two input matrices. The function is used to compute the Jacobian matrices in stereoCalibrate but can also be used in any other similar optimization function. */ CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB ); /** @brief Combines two rotation-and-shift transformations. @param rvec1 First rotation vector. @param tvec1 First translation vector. @param rvec2 Second rotation vector. @param tvec2 Second translation vector. @param rvec3 Output rotation vector of the superposition. @param tvec3 Output translation vector of the superposition. @param dr3dr1 @param dr3dt1 @param dr3dr2 @param dr3dt2 @param dt3dr1 @param dt3dt1 @param dt3dr2 @param dt3dt2 Optional output derivatives of rvec3 or tvec3 with regard to rvec1, rvec2, tvec1 and tvec2, respectively. The functions compute: \f[\begin{array}{l} \texttt{rvec3} = \mathrm{rodrigues} ^{-1} \left ( \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \mathrm{rodrigues} ( \texttt{rvec1} ) \right ) \\ \texttt{tvec3} = \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \texttt{tvec1} + \texttt{tvec2} \end{array} ,\f] where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and \f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See Rodrigues for details. Also, the functions can compute the derivatives of the output vectors with regards to the input vectors (see matMulDeriv ). The functions are used inside stereoCalibrate but can also be used in your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a function that contains a matrix multiplication. */ CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1, InputArray rvec2, InputArray tvec2, OutputArray rvec3, OutputArray tvec3, OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(), OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(), OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(), OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() ); /** @brief Projects 3D points to an image plane. @param objectPoints Array of object points, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel (or vector\ ), where N is the number of points in the view. @param rvec Rotation vector. See Rodrigues for details. @param tvec Translation vector. @param cameraMatrix Camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is empty, the zero distortion coefficients are assumed. @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or vector\ . @param jacobian Optional output 2Nx(10+\) jacobian matrix of derivatives of image points with respect to components of the rotation vector, translation vector, focal lengths, coordinates of the principal point and the distortion coefficients. In the old interface different components of the jacobian are returned via different output parameters. @param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the function assumes that the aspect ratio (*fx/fy*) is fixed and correspondingly adjusts the jacobian matrix. The function computes projections of 3D points to the image plane given intrinsic and extrinsic camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of image points coordinates (as functions of all the input parameters) with respect to the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global optimization in calibrateCamera, solvePnP, and stereoCalibrate . The function itself can also be used to compute a re-projection error given the current intrinsic and extrinsic parameters. @note By setting rvec=tvec=(0,0,0) or by setting cameraMatrix to a 3x3 identity matrix, or by passing zero distortion coefficients, you can get various useful partial cases of the function. This means that you can compute the distorted coordinates for a sparse set of points or apply a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup. */ CV_EXPORTS_W void projectPoints( InputArray objectPoints, InputArray rvec, InputArray tvec, InputArray cameraMatrix, InputArray distCoeffs, OutputArray imagePoints, OutputArray jacobian = noArray(), double aspectRatio = 0 ); /** @brief Finds an object pose from 3D-2D point correspondences. @param objectPoints Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. @param imagePoints Array of corresponding image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, where N is the number of points. vector\ can be also passed here. @param cameraMatrix Input camera matrix \f$A = \vecthreethree{fx}{0}{cx}{0}{fy}{cy}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param rvec Output rotation vector (see Rodrigues ) that, together with tvec , brings points from the model coordinate system to the camera coordinate system. @param tvec Output translation vector. @param useExtrinsicGuess Parameter used for SOLVEPNP_ITERATIVE. If true (1), the function uses the provided rvec and tvec values as initial approximations of the rotation and translation vectors, respectively, and further optimizes them. @param flags Method for solving a PnP problem: - **SOLVEPNP_ITERATIVE** Iterative method is based on Levenberg-Marquardt optimization. In this case the function finds such a pose that minimizes reprojection error, that is the sum of squared distances between the observed projections imagePoints and the projected (using projectPoints ) objectPoints . - **SOLVEPNP_P3P** Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang "Complete Solution Classification for the Perspective-Three-Point Problem". In this case the function requires exactly four object and image points. - **SOLVEPNP_EPNP** Method has been introduced by F.Moreno-Noguer, V.Lepetit and P.Fua in the paper "EPnP: Efficient Perspective-n-Point Camera Pose Estimation". - **SOLVEPNP_DLS** Method is based on the paper of Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP". - **SOLVEPNP_UPNP** Method is based on the paper of A.Penate-Sanchez, J.Andrade-Cetto, F.Moreno-Noguer. "Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation". In this case the function also estimates the parameters \f$f_x\f$ and \f$f_y\f$ assuming that both have the same value. Then the cameraMatrix is updated with the estimated focal length. The function estimates the object pose given a set of object points, their corresponding image projections, as well as the camera matrix and the distortion coefficients. @note - An example of how to use solvePnP for planar augmented reality can be found at opencv_source_code/samples/python/plane_ar.py - If you are using Python: - Numpy array slices won't work as input because solvePnP requires contiguous arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of modules/calib3d/src/solvepnp.cpp version 2.4.9) - The P3P algorithm requires image points to be in an array of shape (N,1,2) due to its calling of cv::undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) which requires 2-channel information. - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) */ CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE ); /** @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme. @param objectPoints Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. @param imagePoints Array of corresponding image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, where N is the number of points. vector\ can be also passed here. @param cameraMatrix Input camera matrix \f$A = \vecthreethree{fx}{0}{cx}{0}{fy}{cy}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param rvec Output rotation vector (see Rodrigues ) that, together with tvec , brings points from the model coordinate system to the camera coordinate system. @param tvec Output translation vector. @param useExtrinsicGuess Parameter used for SOLVEPNP_ITERATIVE. If true (1), the function uses the provided rvec and tvec values as initial approximations of the rotation and translation vectors, respectively, and further optimizes them. @param iterationsCount Number of iterations. @param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value is the maximum allowed distance between the observed and computed point projections to consider it an inlier. @param confidence The probability that the algorithm produces a useful result. @param inliers Output vector that contains indices of inliers in objectPoints and imagePoints . @param flags Method for solving a PnP problem (see solvePnP ). The function estimates an object pose given a set of object points, their corresponding image projections, as well as the camera matrix and the distortion coefficients. This function finds such a pose that minimizes reprojection error, that is, the sum of squared distances between the observed projections imagePoints and the projected (using projectPoints ) objectPoints. The use of RANSAC makes the function resistant to outliers. @note - An example of how to use solvePNPRansac for object detection can be found at opencv_source_code/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/ */ CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8.0, double confidence = 0.99, OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE ); /** @brief Finds an initial camera matrix from 3D-2D point correspondences. @param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern coordinate space. In the old interface all the per-view vectors are concatenated. See calibrateCamera for details. @param imagePoints Vector of vectors of the projections of the calibration pattern points. In the old interface all the per-view vectors are concatenated. @param imageSize Image size in pixels used to initialize the principal point. @param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently. Otherwise, \f$f_x = f_y * \texttt{aspectRatio}\f$ . The function estimates and returns an initial camera matrix for the camera calibration process. Currently, the function only supports planar calibration patterns, which are patterns where each object point has z-coordinate =0. */ CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, double aspectRatio = 1.0 ); /** @brief Finds the positions of internal corners of the chessboard. @param image Source chessboard view. It must be an 8-bit grayscale or color image. @param patternSize Number of inner corners per a chessboard row and column ( patternSize = cvSize(points_per_row,points_per_colum) = cvSize(columns,rows) ). @param corners Output array of detected corners. @param flags Various operation flags that can be zero or a combination of the following values: - **CV_CALIB_CB_ADAPTIVE_THRESH** Use adaptive thresholding to convert the image to black and white, rather than a fixed threshold level (computed from the average image brightness). - **CV_CALIB_CB_NORMALIZE_IMAGE** Normalize the image gamma with equalizeHist before applying fixed or adaptive thresholding. - **CV_CALIB_CB_FILTER_QUADS** Use additional criteria (like contour area, perimeter, square-like shape) to filter out false quads extracted at the contour retrieval stage. - **CALIB_CB_FAST_CHECK** Run a fast check on the image that looks for chessboard corners, and shortcut the call if none is found. This can drastically speed up the call in the degenerate condition when no chessboard is observed. The function attempts to determine whether the input image is a view of the chessboard pattern and locate the internal chessboard corners. The function returns a non-zero value if all of the corners are found and they are placed in a certain order (row by row, left to right in every row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example, a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black squares touch each other. The detected coordinates are approximate, and to determine their positions more accurately, the function calls cornerSubPix. You also may use the function cornerSubPix with different parameters if returned coordinates are not accurate enough. Sample usage of detecting and drawing chessboard corners: : @code Size patternsize(8,6); //interior number of corners Mat gray = ....; //source image vector corners; //this will be filled by the detected corners //CALIB_CB_FAST_CHECK saves a lot of time on images //that do not contain any chessboard corners bool patternfound = findChessboardCorners(gray, patternsize, corners, CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE + CALIB_CB_FAST_CHECK); if(patternfound) cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); drawChessboardCorners(img, patternsize, Mat(corners), patternfound); @endcode @note The function requires white space (like a square-thick border, the wider the better) around the board to make the detection more robust in various environments. Otherwise, if there is no border and the background is dark, the outer black squares cannot be segmented properly and so the square grouping and ordering algorithm fails. */ CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE ); //! finds subpixel-accurate positions of the chessboard corners CV_EXPORTS bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size ); /** @brief Renders the detected chessboard corners. @param image Destination image. It must be an 8-bit color image. @param patternSize Number of inner corners per a chessboard row and column (patternSize = cv::Size(points_per_row,points_per_column)). @param corners Array of detected corners, the output of findChessboardCorners. @param patternWasFound Parameter indicating whether the complete board was found or not. The return value of findChessboardCorners should be passed here. The function draws individual chessboard corners detected either as red circles if the board was not found, or as colored corners connected with lines if the board was found. */ CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize, InputArray corners, bool patternWasFound ); /** @brief Finds centers in the grid of circles. @param image grid view of input circles; it must be an 8-bit grayscale or color image. @param patternSize number of circles per row and column ( patternSize = Size(points_per_row, points_per_colum) ). @param centers output array of detected centers. @param flags various operation flags that can be one of the following values: - **CALIB_CB_SYMMETRIC_GRID** uses symmetric pattern of circles. - **CALIB_CB_ASYMMETRIC_GRID** uses asymmetric pattern of circles. - **CALIB_CB_CLUSTERING** uses a special algorithm for grid detection. It is more robust to perspective distortions but much more sensitive to background clutter. @param blobDetector feature detector that finds blobs like dark circles on light background. The function attempts to determine whether the input image contains a grid of circles. If it is, the function locates centers of the circles. The function returns a non-zero value if all of the centers have been found and they have been placed in a certain order (row by row, left to right in every row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0. Sample usage of detecting and drawing the centers of circles: : @code Size patternsize(7,7); //number of centers Mat gray = ....; //source image vector centers; //this will be filled by the detected centers bool patternfound = findCirclesGrid(gray, patternsize, centers); drawChessboardCorners(img, patternsize, Mat(centers), patternfound); @endcode @note The function requires white space (like a square-thick border, the wider the better) around the board to make the detection more robust in various environments. */ CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID, const Ptr &blobDetector = SimpleBlobDetector::create()); /** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern. @param objectPoints In the new interface it is a vector of vectors of calibration pattern points in the calibration pattern coordinate space (e.g. std::vector>). The outer vector contains as many elements as the number of the pattern views. If the same calibration pattern is shown in each view and it is fully visible, all the vectors will be the same. Although, it is possible to use partially occluded patterns, or even different patterns in different views. Then, the vectors will be different. The points are 3D, but since they are in a pattern coordinate system, then, if the rig is planar, it may make sense to put the model to a XY coordinate plane so that Z-coordinate of each input object point is 0. In the old interface all the vectors of object points from different views are concatenated together. @param imagePoints In the new interface it is a vector of vectors of the projections of calibration pattern points (e.g. std::vector>). imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to objectPoints[i].size() for each i. In the old interface all the vectors of object points from different views are concatenated together. @param imageSize Size of the image used only to initialize the intrinsic camera matrix. @param cameraMatrix Output 3x3 floating-point camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . If CV\_CALIB\_USE\_INTRINSIC\_GUESS and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be initialized before calling the function. @param distCoeffs Output vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. @param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each pattern view (e.g. std::vector>). That is, each k-th rotation vector together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern from the model coordinate space (in which object points are specified) to the world coordinate space, that is, a real position of the calibration pattern in the k-th pattern view (k=0.. *M* -1). @param tvecs Output vector of translation vectors estimated for each pattern view. @param flags Different flags that may be zero or a combination of the following values: - **CV_CALIB_USE_INTRINSIC_GUESS** cameraMatrix contains valid initial values of fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image center ( imageSize is used), and focal distances are computed in a least-squares fashion. Note, that if intrinsic parameters are known, there is no need to use this function just to estimate extrinsic parameters. Use solvePnP instead. - **CV_CALIB_FIX_PRINCIPAL_POINT** The principal point is not changed during the global optimization. It stays at the center or at a different location specified when CV_CALIB_USE_INTRINSIC_GUESS is set too. - **CV_CALIB_FIX_ASPECT_RATIO** The functions considers only fy as a free parameter. The ratio fx/fy stays the same as in the input cameraMatrix . When CV_CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are ignored, only their ratio is computed and used further. - **CV_CALIB_ZERO_TANGENT_DIST** Tangential distortion coefficients \f$(p_1, p_2)\f$ are set to zeros and stay zero. - **CV_CALIB_FIX_K1,...,CV_CALIB_FIX_K6** The corresponding radial distortion coefficient is not changed during the optimization. If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. - **CV_CALIB_RATIONAL_MODEL** Coefficients k4, k5, and k6 are enabled. To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function use the rational model and return 8 coefficients. If the flag is not set, the function computes and returns only 5 distortion coefficients. - **CALIB_THIN_PRISM_MODEL** Coefficients s1, s2, s3 and s4 are enabled. To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function use the thin prism model and return 12 coefficients. If the flag is not set, the function computes and returns only 5 distortion coefficients. - **CALIB_FIX_S1_S2_S3_S4** The thin prism distortion coefficients are not changed during the optimization. If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. - **CALIB_TILTED_MODEL** Coefficients tauX and tauY are enabled. To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function use the tilted sensor model and return 14 coefficients. If the flag is not set, the function computes and returns only 5 distortion coefficients. - **CALIB_FIX_TAUX_TAUY** The coefficients of the tilted sensor model are not changed during the optimization. If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. @param criteria Termination criteria for the iterative optimization algorithm. The function estimates the intrinsic camera parameters and extrinsic parameters for each of the views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object points and their corresponding 2D projections in each view must be specified. That may be achieved by using an object with a known geometry and easily detectable feature points. Such an object is called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as a calibration rig (see findChessboardCorners ). Currently, initialization of intrinsic parameters (when CV_CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also be used as long as initial cameraMatrix is provided. The algorithm performs the following steps: - Compute the initial intrinsic parameters (the option only available for planar calibration patterns) or read them from the input parameters. The distortion coefficients are all set to zeros initially unless some of CV_CALIB_FIX_K? are specified. - Estimate the initial camera pose as if the intrinsic parameters have been already known. This is done using solvePnP . - Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error, that is, the total sum of squared distances between the observed feature points imagePoints and the projected (using the current estimates for camera parameters and the poses) object points objectPoints. See projectPoints for details. The function returns the final re-projection error. @note If you use a non-square (=non-NxN) grid and findChessboardCorners for calibration, and calibrateCamera returns bad values (zero distortion coefficients, an image center very far from (w/2-0.5,h/2-0.5), and/or large differences between \f$f_x\f$ and \f$f_y\f$ (ratios of 10:1 or more)), then you have probably used patternSize=cvSize(rows,cols) instead of using patternSize=cvSize(cols,rows) in findChessboardCorners . @sa findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort */ CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, TermCriteria criteria = TermCriteria( TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); /** @brief Computes useful camera characteristics from the camera matrix. @param cameraMatrix Input camera matrix that can be estimated by calibrateCamera or stereoCalibrate . @param imageSize Input image size in pixels. @param apertureWidth Physical width in mm of the sensor. @param apertureHeight Physical height in mm of the sensor. @param fovx Output field of view in degrees along the horizontal sensor axis. @param fovy Output field of view in degrees along the vertical sensor axis. @param focalLength Focal length of the lens in mm. @param principalPoint Principal point in mm. @param aspectRatio \f$f_y/f_x\f$ The function computes various useful camera characteristics from the previously estimated camera matrix. @note Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for the chessboard pitch (it can thus be any value). */ CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, CV_OUT double& fovx, CV_OUT double& fovy, CV_OUT double& focalLength, CV_OUT Point2d& principalPoint, CV_OUT double& aspectRatio ); /** @brief Calibrates the stereo camera. @param objectPoints Vector of vectors of the calibration pattern points. @param imagePoints1 Vector of vectors of the projections of the calibration pattern points, observed by the first camera. @param imagePoints2 Vector of vectors of the projections of the calibration pattern points, observed by the second camera. @param cameraMatrix1 Input/output first camera matrix: \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If any of CV_CALIB_USE_INTRINSIC_GUESS , CV_CALIB_FIX_ASPECT_RATIO , CV_CALIB_FIX_INTRINSIC , or CV_CALIB_FIX_FOCAL_LENGTH are specified, some or all of the matrix components must be initialized. See the flags description for details. @param distCoeffs1 Input/output vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. The output vector length depends on the flags. @param cameraMatrix2 Input/output second camera matrix. The parameter is similar to cameraMatrix1 @param distCoeffs2 Input/output lens distortion coefficients for the second camera. The parameter is similar to distCoeffs1 . @param imageSize Size of the image used only to initialize intrinsic camera matrix. @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems. @param T Output translation vector between the coordinate systems of the cameras. @param E Output essential matrix. @param F Output fundamental matrix. @param flags Different flags that may be zero or a combination of the following values: - **CV_CALIB_FIX_INTRINSIC** Fix cameraMatrix? and distCoeffs? so that only R, T, E , and F matrices are estimated. - **CV_CALIB_USE_INTRINSIC_GUESS** Optimize some or all of the intrinsic parameters according to the specified flags. Initial values are provided by the user. - **CV_CALIB_FIX_PRINCIPAL_POINT** Fix the principal points during the optimization. - **CV_CALIB_FIX_FOCAL_LENGTH** Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ . - **CV_CALIB_FIX_ASPECT_RATIO** Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$ . - **CV_CALIB_SAME_FOCAL_LENGTH** Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ . - **CV_CALIB_ZERO_TANGENT_DIST** Set tangential distortion coefficients for each camera to zeros and fix there. - **CV_CALIB_FIX_K1,...,CV_CALIB_FIX_K6** Do not change the corresponding radial distortion coefficient during the optimization. If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. - **CV_CALIB_RATIONAL_MODEL** Enable coefficients k4, k5, and k6. To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function use the rational model and return 8 coefficients. If the flag is not set, the function computes and returns only 5 distortion coefficients. - **CALIB_THIN_PRISM_MODEL** Coefficients s1, s2, s3 and s4 are enabled. To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function use the thin prism model and return 12 coefficients. If the flag is not set, the function computes and returns only 5 distortion coefficients. - **CALIB_FIX_S1_S2_S3_S4** The thin prism distortion coefficients are not changed during the optimization. If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. - **CALIB_TILTED_MODEL** Coefficients tauX and tauY are enabled. To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function use the tilted sensor model and return 14 coefficients. If the flag is not set, the function computes and returns only 5 distortion coefficients. - **CALIB_FIX_TAUX_TAUY** The coefficients of the tilted sensor model are not changed during the optimization. If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. @param criteria Termination criteria for the iterative optimization algorithm. The function estimates transformation between two cameras making a stereo pair. If you have a stereo camera where the relative position and orientation of two cameras is fixed, and if you computed poses of an object relative to the first camera and to the second camera, (R1, T1) and (R2, T2), respectively (this can be done with solvePnP ), then those poses definitely relate to each other. This means that, given ( \f$R_1\f$,\f$T_1\f$ ), it should be possible to compute ( \f$R_2\f$,\f$T_2\f$ ). You only need to know the position and orientation of the second camera relative to the first camera. This is what the described function does. It computes ( \f$R\f$,\f$T\f$ ) so that: \f[R_2=R*R_1 T_2=R*T_1 + T,\f] Optionally, it computes the essential matrix E: \f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} *R\f] where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ . And the function can also compute the fundamental matrix F: \f[F = cameraMatrix2^{-T} E cameraMatrix1^{-1}\f] Besides the stereo-related information, the function can also perform a full calibration of each of two cameras. However, due to the high dimensionality of the parameter space and noise in the input data, the function can diverge from the correct solution. If the intrinsic parameters can be estimated with high accuracy for each of the cameras individually (for example, using calibrateCamera ), you are recommended to do so and then pass CV_CALIB_FIX_INTRINSIC flag to the function along with the computed intrinsic parameters. Otherwise, if all the parameters are estimated at once, it makes sense to restrict some parameters, for example, pass CV_CALIB_SAME_FOCAL_LENGTH and CV_CALIB_ZERO_TANGENT_DIST flags, which is usually a reasonable assumption. Similarly to calibrateCamera , the function minimizes the total re-projection error for all the points in all the available views from both cameras. The function returns the final value of the re-projection error. */ CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F, int flags = CALIB_FIX_INTRINSIC, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); /** @brief Computes rectification transforms for each head of a calibrated stereo camera. @param cameraMatrix1 First camera matrix. @param distCoeffs1 First camera distortion parameters. @param cameraMatrix2 Second camera matrix. @param distCoeffs2 Second camera distortion parameters. @param imageSize Size of the image used for stereo calibration. @param R Rotation matrix between the coordinate systems of the first and the second cameras. @param T Translation vector between coordinate systems of the cameras. @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera. @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see reprojectImageTo3D ). @param flags Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY . If the flag is set, the function makes the principal points of each camera have the same pixel coordinates in the rectified views. And if the flag is not set, the function may still shift the images in the horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the useful image area. @param alpha Free scaling parameter. If it is -1 or absent, the function performs the default scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified images are zoomed and shifted so that only valid pixels are visible (no black areas after rectification). alpha=1 means that the rectified image is decimated and shifted so that all the pixels from the original images from the cameras are retained in the rectified images (no source image pixels are lost). Obviously, any intermediate value yields an intermediate result between those two extreme cases. @param newImageSize New image resolution after rectification. The same size should be passed to initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) is passed (default), it is set to the original imageSize . Setting it to larger value can help you preserve details in the original image, especially when there is a big radial distortion. @param validPixROI1 Optional output rectangles inside the rectified images where all the pixels are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller (see the picture below). @param validPixROI2 Optional output rectangles inside the rectified images where all the pixels are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller (see the picture below). The function computes the rotation matrices for each camera that (virtually) make both camera image planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies the dense stereo correspondence problem. The function takes the matrices computed by stereoCalibrate as input. As output, it provides two rotation matrices and also two projection matrices in the new coordinates. The function distinguishes the following two cases: - **Horizontal stereo**: the first and the second camera views are shifted relative to each other mainly along the x axis (with possible small vertical shift). In the rectified images, the corresponding epipolar lines in the left and right cameras are horizontal and have the same y-coordinate. P1 and P2 look like: \f[\texttt{P1} = \begin{bmatrix} f & 0 & cx_1 & 0 \\ 0 & f & cy & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix}\f] \f[\texttt{P2} = \begin{bmatrix} f & 0 & cx_2 & T_x*f \\ 0 & f & cy & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix} ,\f] where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if CV_CALIB_ZERO_DISPARITY is set. - **Vertical stereo**: the first and the second camera views are shifted relative to each other mainly in vertical direction (and probably a bit in the horizontal direction too). The epipolar lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like: \f[\texttt{P1} = \begin{bmatrix} f & 0 & cx & 0 \\ 0 & f & cy_1 & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix}\f] \f[\texttt{P2} = \begin{bmatrix} f & 0 & cx & 0 \\ 0 & f & cy_2 & T_y*f \\ 0 & 0 & 1 & 0 \end{bmatrix} ,\f] where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if CALIB_ZERO_DISPARITY is set. As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera matrices. The matrices, together with R1 and R2 , can then be passed to initUndistortRectifyMap to initialize the rectification map for each camera. See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through the corresponding image regions. This means that the images are well rectified, which is what most stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that their interiors are all valid pixels. ![image](pics/stereo_undistort.jpg) */ CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, Size imageSize, InputArray R, InputArray T, OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags = CALIB_ZERO_DISPARITY, double alpha = -1, Size newImageSize = Size(), CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 ); /** @brief Computes a rectification transform for an uncalibrated stereo camera. @param points1 Array of feature points in the first image. @param points2 The corresponding points in the second image. The same formats as in findFundamentalMat are supported. @param F Input fundamental matrix. It can be computed from the same set of point pairs using findFundamentalMat . @param imgSize Size of the image. @param H1 Output rectification homography matrix for the first image. @param H2 Output rectification homography matrix for the second image. @param threshold Optional threshold used to filter out the outliers. If the parameter is greater than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points for which \f$|\texttt{points2[i]}^T*\texttt{F}*\texttt{points1[i]}|>\texttt{threshold}\f$ ) are rejected prior to computing the homographies. Otherwise,all the points are considered inliers. The function computes the rectification transformations without knowing intrinsic parameters of the cameras and their relative position in the space, which explains the suffix "uncalibrated". Another related difference from stereoRectify is that the function outputs not the rectification transformations in the object (3D) space, but the planar perspective transformations encoded by the homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 . @note While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, it would be better to correct it before computing the fundamental matrix and calling this function. For example, distortion coefficients can be estimated for each head of stereo camera separately by using calibrateCamera . Then, the images can be corrected using undistort , or just the point coordinates can be corrected with undistortPoints . */ CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2, InputArray F, Size imgSize, OutputArray H1, OutputArray H2, double threshold = 5 ); //! computes the rectification transformations for 3-head camera, where all the heads are on the same line. CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, InputArray cameraMatrix3, InputArray distCoeffs3, InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3, Size imageSize, InputArray R12, InputArray T12, InputArray R13, InputArray T13, OutputArray R1, OutputArray R2, OutputArray R3, OutputArray P1, OutputArray P2, OutputArray P3, OutputArray Q, double alpha, Size newImgSize, CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); /** @brief Returns the new camera matrix based on the free scaling parameter. @param cameraMatrix Input camera matrix. @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param imageSize Original image size. @param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are valid) and 1 (when all the source image pixels are retained in the undistorted image). See stereoRectify for details. @param newImgSize Image size after rectification. By default,it is set to imageSize . @param validPixROI Optional output rectangle that outlines all-good-pixels region in the undistorted image. See roi1, roi2 description in stereoRectify . @param centerPrincipalPoint Optional flag that indicates whether in the new camera matrix the principal point should be at the image center or not. By default, the principal point is chosen to best fit a subset of the source image (determined by alpha) to the corrected image. @return new_camera_matrix Output new camera matrix. The function computes and returns the optimal new camera matrix based on the free scaling parameter. By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original image pixels if there is valuable information in the corners alpha=1 , or get something in between. When alpha\>0 , the undistortion result is likely to have some black pixels corresponding to "virtual" pixels outside of the captured distorted image. The original camera matrix, distortion coefficients, the computed new camera matrix, and newImageSize should be passed to initUndistortRectifyMap to produce the maps for remap . */ CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, double alpha, Size newImgSize = Size(), CV_OUT Rect* validPixROI = 0, bool centerPrincipalPoint = false); /** @brief Converts points from Euclidean to homogeneous space. @param src Input vector of N-dimensional points. @param dst Output vector of N+1-dimensional points. The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1). */ CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst ); /** @brief Converts points from homogeneous to Euclidean space. @param src Input vector of N-dimensional points. @param dst Output vector of N-1-dimensional points. The function converts points homogeneous to Euclidean space using perspective projection. That is, each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the output point coordinates will be (0,0,0,...). */ CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst ); /** @brief Converts points to/from homogeneous coordinates. @param src Input array or vector of 2D, 3D, or 4D points. @param dst Output vector of 2D, 3D, or 4D points. The function converts 2D or 3D points from/to homogeneous coordinates by calling either convertPointsToHomogeneous or convertPointsFromHomogeneous. @note The function is obsolete. Use one of the previous two functions instead. */ CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst ); /** @brief Calculates a fundamental matrix from the corresponding points in two images. @param points1 Array of N points from the first image. The point coordinates should be floating-point (single or double precision). @param points2 Array of the second image points of the same size and format as points1 . @param method Method for computing a fundamental matrix. - **CV_FM_7POINT** for a 7-point algorithm. \f$N = 7\f$ - **CV_FM_8POINT** for an 8-point algorithm. \f$N \ge 8\f$ - **CV_FM_RANSAC** for the RANSAC algorithm. \f$N \ge 8\f$ - **CV_FM_LMEDS** for the LMedS algorithm. \f$N \ge 8\f$ @param param1 Parameter used for RANSAC. It is the maximum distance from a point to an epipolar line in pixels, beyond which the point is considered an outlier and is not used for computing the final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the point localization, image resolution, and the image noise. @param param2 Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of confidence (probability) that the estimated matrix is correct. @param mask The epipolar geometry is described by the following equation: \f[[p_2; 1]^T F [p_1; 1] = 0\f] where \f$F\f$ is a fundamental matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the second images, respectively. The function calculates the fundamental matrix using one of four methods listed above and returns the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3 matrices sequentially). The calculated fundamental matrix may be passed further to computeCorrespondEpilines that finds the epipolar lines corresponding to the specified points. It can also be passed to stereoRectifyUncalibrated to compute the rectification transformation. : @code // Example. Estimation of fundamental matrix using the RANSAC algorithm int point_count = 100; vector points1(point_count); vector points2(point_count); // initialize the points here ... for( int i = 0; i < point_count; i++ ) { points1[i] = ...; points2[i] = ...; } Mat fundamental_matrix = findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99); @endcode */ CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, int method = FM_RANSAC, double param1 = 3., double param2 = 0.99, OutputArray mask = noArray() ); /** @overload */ CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2, OutputArray mask, int method = FM_RANSAC, double param1 = 3., double param2 = 0.99 ); /** @brief Calculates an essential matrix from the corresponding points in two images. @param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should be floating-point (single or double precision). @param points2 Array of the second image points of the same size and format as points1 . @param cameraMatrix Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . Note that this function assumes that points1 and points2 are feature points from cameras with the same camera matrix. @param method Method for computing a fundamental matrix. - **RANSAC** for the RANSAC algorithm. - **MEDS** for the LMedS algorithm. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar line in pixels, beyond which the point is considered an outlier and is not used for computing the final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the point localization, image resolution, and the image noise. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of confidence (probability) that the estimated matrix is correct. @param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . @cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: \f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the second images, respectively. The result of this function may be passed further to decomposeEssentialMat or recoverPose to recover the relative pose between cameras. */ CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, InputArray cameraMatrix, int method = RANSAC, double prob = 0.999, double threshold = 1.0, OutputArray mask = noArray() ); /** @overload @param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should be floating-point (single or double precision). @param points2 Array of the second image points of the same size and format as points1 . @param focal focal length of the camera. Note that this function assumes that points1 and points2 are feature points from cameras with same focal length and principle point. @param pp principle point of the camera. @param method Method for computing a fundamental matrix. - **RANSAC** for the RANSAC algorithm. - **LMEDS** for the LMedS algorithm. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar line in pixels, beyond which the point is considered an outlier and is not used for computing the final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the point localization, image resolution, and the image noise. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of confidence (probability) that the estimated matrix is correct. @param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. This function differs from the one above that it computes camera matrix from focal length and principal point: \f[K = \begin{bmatrix} f & 0 & x_{pp} \\ 0 & f & y_{pp} \\ 0 & 0 & 1 \end{bmatrix}\f] */ CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, double focal = 1.0, Point2d pp = Point2d(0, 0), int method = RANSAC, double prob = 0.999, double threshold = 1.0, OutputArray mask = noArray() ); /** @brief Decompose an essential matrix to possible rotations and translation. @param E The input essential matrix. @param R1 One possible rotation matrix. @param R2 Another possible rotation matrix. @param t One possible translation. This function decompose an essential matrix E using svd decomposition @cite HartleyZ00 . Generally 4 possible poses exists for a given E. They are \f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$. By decomposing E, you can only get the direction of the translation, so the function returns unit t. */ CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t ); /** @brief Recover relative camera rotation and translation from an estimated essential matrix and the corresponding points in two images, using cheirality check. Returns the number of inliers which pass the check. @param E The input essential matrix. @param points1 Array of N 2D points from the first image. The point coordinates should be floating-point (single or double precision). @param points2 Array of the second image points of the same size and format as points1 . @param cameraMatrix Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . Note that this function assumes that points1 and points2 are feature points from cameras with the same camera matrix. @param R Recovered relative rotation. @param t Recoverd relative translation. @param mask Input/output mask for inliers in points1 and points2. : If it is not empty, then it marks inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to recover pose. In the output mask only inliers which pass the cheirality check. This function decomposes an essential matrix using decomposeEssentialMat and then verifies possible pose hypotheses by doing cheirality check. The cheirality check basically means that the triangulated 3D points should have positive depth. Some details can be found in @cite Nister03 . This function can be used to process output E and mask from findEssentialMat. In this scenario, points1 and points2 are the same input for findEssentialMat. : @code // Example. Estimation of fundamental matrix using the RANSAC algorithm int point_count = 100; vector points1(point_count); vector points2(point_count); // initialize the points here ... for( int i = 0; i < point_count; i++ ) { points1[i] = ...; points2[i] = ...; } // cametra matrix with both focal lengths = 1, and principal point = (0, 0) Mat cameraMatrix = Mat::eye(3, 3, CV_64F); Mat E, R, t, mask; E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask); recoverPose(E, points1, points2, cameraMatrix, R, t, mask); @endcode */ CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, InputArray cameraMatrix, OutputArray R, OutputArray t, InputOutputArray mask = noArray() ); /** @overload @param E The input essential matrix. @param points1 Array of N 2D points from the first image. The point coordinates should be floating-point (single or double precision). @param points2 Array of the second image points of the same size and format as points1 . @param R Recovered relative rotation. @param t Recoverd relative translation. @param focal Focal length of the camera. Note that this function assumes that points1 and points2 are feature points from cameras with same focal length and principle point. @param pp Principle point of the camera. @param mask Input/output mask for inliers in points1 and points2. : If it is not empty, then it marks inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to recover pose. In the output mask only inliers which pass the cheirality check. This function differs from the one above that it computes camera matrix from focal length and principal point: \f[K = \begin{bmatrix} f & 0 & x_{pp} \\ 0 & f & y_{pp} \\ 0 & 0 & 1 \end{bmatrix}\f] */ CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, OutputArray R, OutputArray t, double focal = 1.0, Point2d pp = Point2d(0, 0), InputOutputArray mask = noArray() ); /** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image. @param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or vector\ . @param whichImage Index of the image (1 or 2) that contains the points . @param F Fundamental matrix that can be estimated using findFundamentalMat or stereoRectify . @param lines Output vector of the epipolar lines corresponding to the points in the other image. Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ . For every point in one of the two images of a stereo pair, the function finds the equation of the corresponding epipolar line in the other image. From the fundamental matrix definition (see findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as: \f[l^{(2)}_i = F p^{(1)}_i\f] And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as: \f[l^{(1)}_i = F^T p^{(2)}_i\f] Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ . */ CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage, InputArray F, OutputArray lines ); /** @brief Reconstructs points by triangulation. @param projMatr1 3x4 projection matrix of the first camera. @param projMatr2 3x4 projection matrix of the second camera. @param projPoints1 2xN array of feature points in the first image. In case of c++ version it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. @param projPoints2 2xN array of corresponding points in the second image. In case of c++ version it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. @param points4D 4xN array of reconstructed points in homogeneous coordinates. The function reconstructs 3-dimensional points (in homogeneous coordinates) by using their observations with a stereo camera. Projections matrices can be obtained from stereoRectify. @note Keep in mind that all input data should be of float type in order for this function to work. @sa reprojectImageTo3D */ CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2, InputArray projPoints1, InputArray projPoints2, OutputArray points4D ); /** @brief Refines coordinates of corresponding points. @param F 3x3 fundamental matrix. @param points1 1xN array containing the first set of points. @param points2 1xN array containing the second set of points. @param newPoints1 The optimized points1. @param newPoints2 The optimized points2. The function implements the Optimal Triangulation Method (see Multiple View Geometry for details). For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint \f$newPoints2^T * F * newPoints1 = 0\f$ . */ CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2, OutputArray newPoints1, OutputArray newPoints2 ); /** @brief Filters off small noise blobs (speckles) in the disparity map @param img The input 16-bit signed disparity image @param newVal The disparity value used to paint-off the speckles @param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not affected by the algorithm @param maxDiff Maximum difference between neighbor disparity pixels to put them into the same blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point disparity map, where disparity values are multiplied by 16, this scale factor should be taken into account when specifying this parameter value. @param buf The optional temporary buffer to avoid memory allocation within the function. */ CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff, InputOutputArray buf = noArray() ); //! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by cv::stereoRectify()) CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2, int minDisparity, int numberOfDisparities, int SADWindowSize ); //! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost, int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1 ); /** @brief Reprojects a disparity image to 3D space. @param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit floating-point disparity image. If 16-bit signed format is used, the values are assumed to have no fractional bits. @param _3dImage Output 3-channel floating-point image of the same size as disparity . Each element of _3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. @param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with stereoRectify. @param handleMissingValues Indicates, whether the function should handle missing values (i.e. points where the disparity was not computed). If handleMissingValues=true, then pixels with the minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed to 3D points with a very large Z value (currently set to 10000). @param ddepth The optional output array depth. If it is -1, the output image will have CV_32F depth. ddepth can also be set to CV_16S, CV_32S or CV_32F. The function transforms a single-channel disparity map to a 3-channel image representing a 3D surface. That is, for each pixel (x,y) andthe corresponding disparity d=disparity(x,y) , it computes: \f[\begin{array}{l} [X \; Y \; Z \; W]^T = \texttt{Q} *[x \; y \; \texttt{disparity} (x,y) \; 1]^T \\ \texttt{\_3dImage} (x,y) = (X/W, \; Y/W, \; Z/W) \end{array}\f] The matrix Q can be an arbitrary \f$4 \times 4\f$ matrix (for example, the one computed by stereoRectify). To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform . */ CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity, OutputArray _3dImage, InputArray Q, bool handleMissingValues = false, int ddepth = -1 ); /** @brief Calculates the Sampson Distance between two points. The function sampsonDistance calculates and returns the first order approximation of the geometric error as: \f[sd( \texttt{pt1} , \texttt{pt2} )= \frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2}{(\texttt{F} \cdot \texttt{pt1})(0) + (\texttt{F} \cdot \texttt{pt1})(1) + (\texttt{F}^t \cdot \texttt{pt2})(0) + (\texttt{F}^t \cdot \texttt{pt2})(1)}\f] The fundamental matrix may be calculated using the cv::findFundamentalMat function. See HZ 11.4.3 for details. @param pt1 first homogeneous 2d point @param pt2 second homogeneous 2d point @param F fundamental matrix */ CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F); /** @brief Computes an optimal affine transformation between two 3D point sets. @param src First input 3D point set. @param dst Second input 3D point set. @param out Output 3D affine transformation matrix \f$3 \times 4\f$ . @param inliers Output vector indicating which points are inliers. @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as an inlier. @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. The function estimates an optimal 3D affine transformation between two 3D point sets using the RANSAC algorithm. */ CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst, OutputArray out, OutputArray inliers, double ransacThreshold = 3, double confidence = 0.99); /** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s). @param H The input homography matrix between two images. @param K The input intrinsic camera calibration matrix. @param rotations Array of rotation matrices. @param translations Array of translation matrices. @param normals Array of plane normal matrices. This function extracts relative camera motion between two views observing a planar object from the homography H induced by the plane. The intrinsic camera matrix K must also be provided. The function may return up to four mathematical solution sets. At least two of the solutions may further be invalidated if point correspondences are available by applying positive depth constraint (all points must be in front of the camera). The decomposition method is described in detail in @cite Malis . */ CV_EXPORTS_W int decomposeHomographyMat(InputArray H, InputArray K, OutputArrayOfArrays rotations, OutputArrayOfArrays translations, OutputArrayOfArrays normals); /** @brief The base class for stereo correspondence algorithms. */ class CV_EXPORTS_W StereoMatcher : public Algorithm { public: enum { DISP_SHIFT = 4, DISP_SCALE = (1 << DISP_SHIFT) }; /** @brief Computes disparity map for the specified stereo pair @param left Left 8-bit single-channel image. @param right Right image of the same size and the same type as the left one. @param disparity Output disparity map. It has the same size as the input images. Some algorithms, like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map. */ CV_WRAP virtual void compute( InputArray left, InputArray right, OutputArray disparity ) = 0; CV_WRAP virtual int getMinDisparity() const = 0; CV_WRAP virtual void setMinDisparity(int minDisparity) = 0; CV_WRAP virtual int getNumDisparities() const = 0; CV_WRAP virtual void setNumDisparities(int numDisparities) = 0; CV_WRAP virtual int getBlockSize() const = 0; CV_WRAP virtual void setBlockSize(int blockSize) = 0; CV_WRAP virtual int getSpeckleWindowSize() const = 0; CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0; CV_WRAP virtual int getSpeckleRange() const = 0; CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0; CV_WRAP virtual int getDisp12MaxDiff() const = 0; CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0; }; /** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and contributed to OpenCV by K. Konolige. */ class CV_EXPORTS_W StereoBM : public StereoMatcher { public: enum { PREFILTER_NORMALIZED_RESPONSE = 0, PREFILTER_XSOBEL = 1 }; CV_WRAP virtual int getPreFilterType() const = 0; CV_WRAP virtual void setPreFilterType(int preFilterType) = 0; CV_WRAP virtual int getPreFilterSize() const = 0; CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0; CV_WRAP virtual int getPreFilterCap() const = 0; CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; CV_WRAP virtual int getTextureThreshold() const = 0; CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0; CV_WRAP virtual int getUniquenessRatio() const = 0; CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; CV_WRAP virtual int getSmallerBlockSize() const = 0; CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0; CV_WRAP virtual Rect getROI1() const = 0; CV_WRAP virtual void setROI1(Rect roi1) = 0; CV_WRAP virtual Rect getROI2() const = 0; CV_WRAP virtual void setROI2(Rect roi2) = 0; /** @brief Creates StereoBM object @param numDisparities the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to numDisparities. The search range can then be shifted by changing the minimum disparity. @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence. The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for a specific stereo pair. */ CV_WRAP static Ptr create(int numDisparities = 0, int blockSize = 21); }; /** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original one as follows: - By default, the algorithm is single-pass, which means that you consider only 5 directions instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the algorithm but beware that it may consume a lot of memory. - The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the blocks to single pixels. - Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well. - Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering). @note - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found at opencv_source_code/samples/python/stereo_match.py */ class CV_EXPORTS_W StereoSGBM : public StereoMatcher { public: enum { MODE_SGBM = 0, MODE_HH = 1, MODE_SGBM_3WAY = 2 }; CV_WRAP virtual int getPreFilterCap() const = 0; CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; CV_WRAP virtual int getUniquenessRatio() const = 0; CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; CV_WRAP virtual int getP1() const = 0; CV_WRAP virtual void setP1(int P1) = 0; CV_WRAP virtual int getP2() const = 0; CV_WRAP virtual void setP2(int P2) = 0; CV_WRAP virtual int getMode() const = 0; CV_WRAP virtual void setMode(int mode) = 0; /** @brief Creates StereoSGBM object @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than zero. In the current implementation, this parameter must be divisible by 16. @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be somewhere in the 3..11 range. @param P1 The first parameter controlling the disparity smoothness. See below. @param P2 The second parameter controlling the disparity smoothness. The larger the values are, the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good P1 and P2 values are shown (like 8\*number_of_image_channels\*SADWindowSize\*SADWindowSize and 32\*number_of_image_channels\*SADWindowSize\*SADWindowSize , respectively). @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right disparity check. Set it to a non-positive value to disable the check. @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. The result values are passed to the Birchfield-Tomasi pixel cost function. @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function value should "win" the second best value to consider the found match correct. Normally, a value within the 5-15 range is good enough. @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the 50-200 range. @param speckleRange Maximum disparity variation within each connected component. If you do speckle filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. Normally, 1 or 2 is good enough. @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and huge for HD-size pictures. By default, it is set to false . The first constructor initializes StereoSGBM with all the default parameters. So, you only have to set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter to a custom value. */ CV_WRAP static Ptr create(int minDisparity, int numDisparities, int blockSize, int P1 = 0, int P2 = 0, int disp12MaxDiff = 0, int preFilterCap = 0, int uniquenessRatio = 0, int speckleWindowSize = 0, int speckleRange = 0, int mode = StereoSGBM::MODE_SGBM); }; //! @} calib3d /** @brief The methods in this namespace use a so-called fisheye camera model. @ingroup calib3d_fisheye */ namespace fisheye { //! @addtogroup calib3d_fisheye //! @{ enum{ CALIB_USE_INTRINSIC_GUESS = 1, CALIB_RECOMPUTE_EXTRINSIC = 2, CALIB_CHECK_COND = 4, CALIB_FIX_SKEW = 8, CALIB_FIX_K1 = 16, CALIB_FIX_K2 = 32, CALIB_FIX_K3 = 64, CALIB_FIX_K4 = 128, CALIB_FIX_INTRINSIC = 256 }; /** @brief Projects points using fisheye model @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\ ), where N is the number of points in the view. @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or vector\. @param affine @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$. @param alpha The skew coefficient. @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect to components of the focal lengths, coordinates of the principal point, distortion coefficients, rotation vector, translation vector, and the skew. In the old interface different components of the jacobian are returned via different output parameters. The function computes projections of 3D points to the image plane given intrinsic and extrinsic camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of image points coordinates (as functions of all the input parameters) with respect to the particular parameters, intrinsic and/or extrinsic. */ CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine, InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); /** @overload */ CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); /** @brief Distorts 2D points using fisheye model. @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is the number of points in the view. @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$. @param alpha The skew coefficient. @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . */ CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0); /** @brief Undistorts 2D points using fisheye model @param distorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is the number of points in the view. @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 1-channel or 1x1 3-channel @param P New camera matrix (3x3) or new projection matrix (3x4) @param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . */ CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted, InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray()); /** @brief Computes undistortion and rectification maps for image transform by cv::remap(). If D is empty zero distortion is used, if R or P is empty identity matrixes are used. @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 1-channel or 1x1 3-channel @param P New camera matrix (3x3) or new projection matrix (3x4) @param size Undistorted image size. @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See convertMaps() for details. @param map1 The first output map. @param map2 The second output map. */ CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P, const cv::Size& size, int m1type, OutputArray map1, OutputArray map2); /** @brief Transforms an image to compensate for fisheye lens distortion. @param distorted image with fisheye lens distortion. @param undistorted Output image with compensated fisheye lens distortion. @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$. @param Knew Camera matrix of the distorted image. By default, it is the identity matrix but you may additionally scale and shift the result by using a different matrix. @param new_size The function transforms an image to compensate radial and tangential lens distortion. The function is simply a combination of fisheye::initUndistortRectifyMap (with unity R ) and remap (with bilinear interpolation). See the former function for details of the transformation being performed. See below the results of undistortImage. - a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3, k_4, k_5, k_6) of distortion were optimized under calibration) - b\) result of fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2, k_3, k_4) of fisheye distortion were optimized under calibration) - c\) original image was captured with fisheye lens Pictures a) and b) almost the same. But if we consider points of image located far from the center of image, we can notice that on image a) these points are distorted. ![image](pics/fisheye_undistorted.jpg) */ CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted, InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size()); /** @brief Estimates new camera matrix for undistortion or rectification. @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param image_size @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 1-channel or 1x1 3-channel @param P New camera matrix (3x3) or new projection matrix (3x4) @param balance Sets the new focal length in range between the min focal length and the max focal length. Balance is in range of [0, 1]. @param new_size @param fov_scale Divisor for new focal length. */ CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R, OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0); /** @brief Performs camera calibaration @param objectPoints vector of vectors of calibration pattern points in the calibration pattern coordinate space. @param imagePoints vector of vectors of the projections of calibration pattern points. imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to objectPoints[i].size() for each i. @param image_size Size of the image used only to initialize the intrinsic camera matrix. @param K Output 3x3 floating-point camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . If fisheye::CALIB_USE_INTRINSIC_GUESS/ is specified, some or all of fx, fy, cx, cy must be initialized before calling the function. @param D Output vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$. @param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each pattern view. That is, each k-th rotation vector together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern from the model coordinate space (in which object points are specified) to the world coordinate space, that is, a real position of the calibration pattern in the k-th pattern view (k=0.. *M* -1). @param tvecs Output vector of translation vectors estimated for each pattern view. @param flags Different flags that may be zero or a combination of the following values: - **fisheye::CALIB_USE_INTRINSIC_GUESS** cameraMatrix contains valid initial values of fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image center ( imageSize is used), and focal distances are computed in a least-squares fashion. - **fisheye::CALIB_RECOMPUTE_EXTRINSIC** Extrinsic will be recomputed after each iteration of intrinsic optimization. - **fisheye::CALIB_CHECK_COND** The functions will check validity of condition number. - **fisheye::CALIB_FIX_SKEW** Skew coefficient (alpha) is set to zero and stay zero. - **fisheye::CALIB_FIX_K1..4** Selected distortion coefficients are set to zeros and stay zero. @param criteria Termination criteria for the iterative optimization algorithm. */ CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size, InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); /** @brief Stereo rectification for fisheye camera model @param K1 First camera matrix. @param D1 First camera distortion parameters. @param K2 Second camera matrix. @param D2 Second camera distortion parameters. @param imageSize Size of the image used for stereo calibration. @param R Rotation matrix between the coordinate systems of the first and the second cameras. @param tvec Translation vector between coordinate systems of the cameras. @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera. @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see reprojectImageTo3D ). @param flags Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY . If the flag is set, the function makes the principal points of each camera have the same pixel coordinates in the rectified views. And if the flag is not set, the function may still shift the images in the horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the useful image area. @param newImageSize New image resolution after rectification. The same size should be passed to initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) is passed (default), it is set to the original imageSize . Setting it to larger value can help you preserve details in the original image, especially when there is a big radial distortion. @param balance Sets the new focal length in range between the min focal length and the max focal length. Balance is in range of [0, 1]. @param fov_scale Divisor for new focal length. */ CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec, OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(), double balance = 0.0, double fov_scale = 1.0); /** @brief Performs stereo calibration @param objectPoints Vector of vectors of the calibration pattern points. @param imagePoints1 Vector of vectors of the projections of the calibration pattern points, observed by the first camera. @param imagePoints2 Vector of vectors of the projections of the calibration pattern points, observed by the second camera. @param K1 Input/output first camera matrix: \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If any of fisheye::CALIB_USE_INTRINSIC_GUESS , fisheye::CV_CALIB_FIX_INTRINSIC are specified, some or all of the matrix components must be initialized. @param D1 Input/output vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$ of 4 elements. @param K2 Input/output second camera matrix. The parameter is similar to K1 . @param D2 Input/output lens distortion coefficients for the second camera. The parameter is similar to D1 . @param imageSize Size of the image used only to initialize intrinsic camera matrix. @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems. @param T Output translation vector between the coordinate systems of the cameras. @param flags Different flags that may be zero or a combination of the following values: - **fisheye::CV_CALIB_FIX_INTRINSIC** Fix K1, K2? and D1, D2? so that only R, T matrices are estimated. - **fisheye::CALIB_USE_INTRINSIC_GUESS** K1, K2 contains valid initial values of fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image center (imageSize is used), and focal distances are computed in a least-squares fashion. - **fisheye::CALIB_RECOMPUTE_EXTRINSIC** Extrinsic will be recomputed after each iteration of intrinsic optimization. - **fisheye::CALIB_CHECK_COND** The functions will check validity of condition number. - **fisheye::CALIB_FIX_SKEW** Skew coefficient (alpha) is set to zero and stay zero. - **fisheye::CALIB_FIX_K1..4** Selected distortion coefficients are set to zeros and stay zero. @param criteria Termination criteria for the iterative optimization algorithm. */ CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); //! @} calib3d_fisheye } } // cv #ifndef DISABLE_OPENCV_24_COMPATIBILITY #include "opencv2/calib3d/calib3d_c.h" #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/ccalib/multicalib.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Baisheng Lai (laibaisheng@gmail.com), Zhejiang University, // all rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_MULTICAMERACALIBRATION_HPP__ #define __OPENCV_MULTICAMERACALIBRATION_HPP__ #include "opencv2/ccalib/randpattern.hpp" #include "opencv2/ccalib/omnidir.hpp" #include #include namespace cv { namespace multicalib { //! @addtogroup ccalib //! @{ #define HEAD -1 #define INVALID -2 /** @brief Class for multiple camera calibration that supports pinhole camera and omnidirection camera. For omnidirectional camera model, please refer to omnidir.hpp in ccalib module. It first calibrate each camera individually, then a bundle adjustment like optimization is applied to refine extrinsic parameters. So far, it only support "random" pattern for calibration, see randomPattern.hpp in ccalib module for details. Images that are used should be named by "cameraIdx-timestamp.*", several images with the same timestamp means that they are the same pattern that are photographed. cameraIdx should start from 0. For more details, please refer to paper B. Li, L. Heng, K. Kevin and M. Pollefeys, "A Multiple-Camera System Calibration Toolbox Using A Feature Descriptor-Based Calibration Pattern", in IROS 2013. */ class CV_EXPORTS MultiCameraCalibration { public: enum { PINHOLE, OMNIDIRECTIONAL //FISHEYE }; // an edge connects a camera and pattern struct edge { int cameraVertex; // vertex index for camera in this edge int photoVertex; // vertex index for pattern in this edge int photoIndex; // photo index among photos for this camera Mat transform; // transform from pattern to camera edge(int cv, int pv, int pi, Mat trans) { cameraVertex = cv; photoVertex = pv; photoIndex = pi; transform = trans; } }; struct vertex { Mat pose; // relative pose to the first camera. For camera vertex, it is the // transform from the first camera to this camera, for pattern vertex, // it is the transform from pattern to the first camera int timestamp; // timestamp of photo, only available for photo vertex vertex(Mat po, int ts) { pose = po; timestamp = ts; } vertex() { pose = Mat::eye(4, 4, CV_32F); timestamp = -1; } }; /* @brief Constructor @param cameraType camera type, PINHOLE or OMNIDIRECTIONAL @param nCameras number of cameras @fileName filename of string list that are used for calibration, the file is generated by imagelist_creator from OpenCv samples. The first one in the list is the pattern filename. @patternWidth the physical width of pattern, in user defined unit. @patternHeight the physical height of pattern, in user defined unit. @showExtration whether show extracted features and feature filtering. @nMiniMatches minimal number of matched features for a frame. @flags Calibration flags @criteria optimization stopping criteria. @detector feature detector that detect feature points in pattern and images. @descriptor feature descriptor. @matcher feature matcher. */ MultiCameraCalibration(int cameraType, int nCameras, const std::string& fileName, float patternWidth, float patternHeight, int verbose = 0, int showExtration = 0, int nMiniMatches = 20, int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 200, 1e-7), Ptr detector = AKAZE::create(AKAZE::DESCRIPTOR_MLDB, 0, 3, 0.006f), Ptr descriptor = AKAZE::create(AKAZE::DESCRIPTOR_MLDB,0, 3, 0.006f), Ptr matcher = DescriptorMatcher::create("BruteForce-L1")); /* @brief load images */ void loadImages(); /* @brief initialize multiple camera calibration. It calibrates each camera individually. */ void initialize(); /* @brief optimization extrinsic parameters */ double optimizeExtrinsics(); /* @brief run multi-camera camera calibration, it runs loadImage(), initialize() and optimizeExtrinsics() */ double run(); /* @brief write camera parameters to file. */ void writeParameters(const std::string& filename); private: std::vector readStringList(); int getPhotoVertex(int timestamp); void graphTraverse(const Mat& G, int begin, std::vector& order, std::vector& pre); void findRowNonZero(const Mat& row, Mat& idx); void computeJacobianExtrinsic(const Mat& extrinsicParams, Mat& JTJ_inv, Mat& JTE); void computePhotoCameraJacobian(const Mat& rvecPhoto, const Mat& tvecPhoto, const Mat& rvecCamera, const Mat& tvecCamera, Mat& rvecTran, Mat& tvecTran, const Mat& objectPoints, const Mat& imagePoints, const Mat& K, const Mat& distort, const Mat& xi, Mat& jacobianPhoto, Mat& jacobianCamera, Mat& E); void compose_motion(InputArray _om1, InputArray _T1, InputArray _om2, InputArray _T2, Mat& om3, Mat& T3, Mat& dom3dom1, Mat& dom3dT1, Mat& dom3dom2, Mat& dom3dT2, Mat& dT3dom1, Mat& dT3dT1, Mat& dT3dom2, Mat& dT3dT2); void JRodriguesMatlab(const Mat& src, Mat& dst); void dAB(InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB); double computeProjectError(Mat& parameters); void vector2parameters(const Mat& parameters, std::vector& rvecVertex, std::vector& tvecVertexs); void parameters2vector(const std::vector& rvecVertex, const std::vector& tvecVertex, Mat& parameters); int _camType; //PINHOLE, FISHEYE or OMNIDIRECTIONAL int _nCamera; int _nMiniMatches; int _flags; int _verbose; double _error; float _patternWidth, _patternHeight; TermCriteria _criteria; std::string _filename; int _showExtraction; Ptr _detector; Ptr _descriptor; Ptr _matcher; std::vector _edgeList; std::vector _vertexList; std::vector > _objectPointsForEachCamera; std::vector > _imagePointsForEachCamera; std::vector _cameraMatrix; std::vector _distortCoeffs; std::vector _xi; std::vector > _omEachCamera, _tEachCamera; }; //! @} }} // namespace multicalib, cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/ccalib/omnidir.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Baisheng Lai (laibaisheng@gmail.com), Zhejiang University, // all rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #include #include #ifndef __OPENCV_OMNIDIR_HPP__ #define __OPENCV_OMNIDIR_HPP__ namespace cv { namespace omnidir { //! @addtogroup ccalib //! @{ enum { CALIB_USE_GUESS = 1, CALIB_FIX_SKEW = 2, CALIB_FIX_K1 = 4, CALIB_FIX_K2 = 8, CALIB_FIX_P1 = 16, CALIB_FIX_P2 = 32, CALIB_FIX_XI = 64, CALIB_FIX_GAMMA = 128, CALIB_FIX_CENTER = 256 }; enum{ RECTIFY_PERSPECTIVE = 1, RECTIFY_CYLINDRICAL = 2, RECTIFY_LONGLATI = 3, RECTIFY_STEREOGRAPHIC = 4 }; enum{ XYZRGB = 1, XYZ = 2 }; /** * This module was accepted as a GSoC 2015 project for OpenCV, authored by * Baisheng Lai, mentored by Bo Li. */ /** @brief Projects points for omnidirectional camera using CMei's model @param objectPoints Object points in world coordinate, vector of vector of Vec3f or Mat of 1xN/Nx1 3-channel of type CV_32F and N is the number of points. 64F is also acceptable. @param imagePoints Output array of image points, vector of vector of Vec2f or 1xN/Nx1 2-channel of type CV_32F. 64F is also acceptable. @param rvec vector of rotation between world coordinate and camera coordinate, i.e., om @param tvec vector of translation between pattern coordinate and camera coordinate @param K Camera matrix \f$K = \vecthreethree{f_x}{s}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2)\f$. @param xi The parameter xi for CMei's model @param jacobian Optional output 2Nx16 of type CV_64F jacobian matrix, contains the derivatives of image pixel points wrt parameters including \f$om, T, f_x, f_y, s, c_x, c_y, xi, k_1, k_2, p_1, p_2\f$. This matrix will be used in calibration by optimization. The function projects object 3D points of world coordinate to image pixels, parameter by intrinsic and extrinsic parameters. Also, it optionally compute a by-product: the jacobian matrix containing contains the derivatives of image pixel points wrt intrinsic and extrinsic parameters. */ CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, InputArray K, double xi, InputArray D, OutputArray jacobian = noArray()); /** @brief Undistort 2D image points for omnidirectional camera using CMei's model @param distorted Array of distorted image points, vector of Vec2f or 1xN/Nx1 2-channel Mat of type CV_32F, 64F depth is also acceptable @param K Camera matrix \f$K = \vecthreethree{f_x}{s}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Distortion coefficients \f$(k_1, k_2, p_1, p_2)\f$. @param xi The parameter xi for CMei's model @param R Rotation trainsform between the original and object space : 3x3 1-channel, or vector: 3x1/1x3 1-channel or 1x1 3-channel @param undistorted array of normalized object points, vector of Vec2f/Vec2d or 1xN/Nx1 2-channel Mat with the same depth of distorted points. */ CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted, InputArray K, InputArray D, InputArray xi, InputArray R); /** @brief Computes undistortion and rectification maps for omnidirectional camera image transform by a rotation R. It output two maps that are used for cv::remap(). If D is empty then zero distortion is used, if R or P is empty then identity matrices are used. @param K Camera matrix \f$K = \vecthreethree{f_x}{s}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$, with depth CV_32F or CV_64F @param D Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2)\f$, with depth CV_32F or CV_64F @param xi The parameter xi for CMei's model @param R Rotation transform between the original and object space : 3x3 1-channel, or vector: 3x1/1x3, with depth CV_32F or CV_64F @param P New camera matrix (3x3) or new projection matrix (3x4) @param size Undistorted image size. @param mltype Type of the first output map that can be CV_32FC1 or CV_16SC2 . See convertMaps() for details. @param map1 The first output map. @param map2 The second output map. @param flags Flags indicates the rectification type, RECTIFY_PERSPECTIVE, RECTIFY_CYLINDRICAL, RECTIFY_LONGLATI and RECTIFY_STEREOGRAPHIC are supported. */ CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray xi, InputArray R, InputArray P, const cv::Size& size, int mltype, OutputArray map1, OutputArray map2, int flags); /** @brief Undistort omnidirectional images to perspective images @param distorted The input omnidirectional image. @param undistorted The output undistorted image. @param K Camera matrix \f$K = \vecthreethree{f_x}{s}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$. @param D Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2)\f$. @param xi The parameter xi for CMei's model. @param flags Flags indicates the rectification type, RECTIFY_PERSPECTIVE, RECTIFY_CYLINDRICAL, RECTIFY_LONGLATI and RECTIFY_STEREOGRAPHIC @param Knew Camera matrix of the distorted image. If it is not assigned, it is just K. @param new_size The new image size. By default, it is the size of distorted. @param R Rotation matrix between the input and output images. By default, it is identity matrix. */ CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted, InputArray K, InputArray D, InputArray xi, int flags, InputArray Knew = cv::noArray(), const Size& new_size = Size(), InputArray R = Mat::eye(3, 3, CV_64F)); /** @brief Perform omnidirectional camera calibration, the default depth of outputs is CV_64F. @param objectPoints Vector of vector of Vec3f object points in world (pattern) coordinate. It also can be vector of Mat with size 1xN/Nx1 and type CV_32FC3. Data with depth of 64_F is also acceptable. @param imagePoints Vector of vector of Vec2f corresponding image points of objectPoints. It must be the same size and the same type with objectPoints. @param size Image size of calibration images. @param K Output calibrated camera matrix. @param xi Output parameter xi for CMei's model @param D Output distortion parameters \f$(k_1, k_2, p_1, p_2)\f$ @param rvecs Output rotations for each calibration images @param tvecs Output translation for each calibration images @param flags The flags that control calibrate @param criteria Termination criteria for optimization @param idx Indices of images that pass initialization, which are really used in calibration. So the size of rvecs is the same as idx.total(). */ CV_EXPORTS_W double calibrate(InputArray objectPoints, InputArray imagePoints, Size size, InputOutputArray K, InputOutputArray xi, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags, TermCriteria criteria, OutputArray idx=noArray()); /** @brief Stereo calibration for omnidirectional camera model. It computes the intrinsic parameters for two cameras and the extrinsic parameters between two cameras. The default depth of outputs is CV_64F. @param objectPoints Object points in world (pattern) coordinate. Its type is vector >. It also can be vector of Mat with size 1xN/Nx1 and type CV_32FC3. Data with depth of 64_F is also acceptable. @param imagePoints1 The corresponding image points of the first camera, with type vector >. It must be the same size and the same type as objectPoints. @param imagePoints2 The corresponding image points of the second camera, with type vector >. It must be the same size and the same type as objectPoints. @param imageSize1 Image size of calibration images of the first camera. @param imageSize2 Image size of calibration images of the second camera. @param K1 Output camera matrix for the first camera. @param xi1 Output parameter xi of Mei's model for the first camera @param D1 Output distortion parameters \f$(k_1, k_2, p_1, p_2)\f$ for the first camera @param K2 Output camera matrix for the first camera. @param xi2 Output parameter xi of CMei's model for the second camera @param D2 Output distortion parameters \f$(k_1, k_2, p_1, p_2)\f$ for the second camera @param rvec Output rotation between the first and second camera @param tvec Output translation between the first and second camera @param rvecsL Output rotation for each image of the first camera @param tvecsL Output translation for each image of the first camera @param flags The flags that control stereoCalibrate @param criteria Termination criteria for optimization @param idx Indices of image pairs that pass initialization, which are really used in calibration. So the size of rvecs is the same as idx.total(). @ */ CV_EXPORTS_W double stereoCalibrate(InputOutputArrayOfArrays objectPoints, InputOutputArrayOfArrays imagePoints1, InputOutputArrayOfArrays imagePoints2, const Size& imageSize1, const Size& imageSize2, InputOutputArray K1, InputOutputArray xi1, InputOutputArray D1, InputOutputArray K2, InputOutputArray xi2, InputOutputArray D2, OutputArray rvec, OutputArray tvec, OutputArrayOfArrays rvecsL, OutputArrayOfArrays tvecsL, int flags, TermCriteria criteria, OutputArray idx=noArray()); /** @brief Stereo rectification for omnidirectional camera model. It computes the rectification rotations for two cameras @param R Rotation between the first and second camera @param T Translation between the first and second camera @param R1 Output 3x3 rotation matrix for the first camera @param R2 Output 3x3 rotation matrix for the second camera */ CV_EXPORTS_W void stereoRectify(InputArray R, InputArray T, OutputArray R1, OutputArray R2); /** @brief Stereo 3D reconstruction from a pair of images @param image1 The first input image @param image2 The second input image @param K1 Input camera matrix of the first camera @param D1 Input distortion parameters \f$(k_1, k_2, p_1, p_2)\f$ for the first camera @param xi1 Input parameter xi for the first camera for CMei's model @param K2 Input camera matrix of the second camera @param D2 Input distortion parameters \f$(k_1, k_2, p_1, p_2)\f$ for the second camera @param xi2 Input parameter xi for the second camera for CMei's model @param R Rotation between the first and second camera @param T Translation between the first and second camera @param flag Flag of rectification type, RECTIFY_PERSPECTIVE or RECTIFY_LONGLATI @param numDisparities The parameter 'numDisparities' in StereoSGBM, see StereoSGBM for details. @param SADWindowSize The parameter 'SADWindowSize' in StereoSGBM, see StereoSGBM for details. @param disparity Disparity map generated by stereo matching @param image1Rec Rectified image of the first image @param image2Rec rectified image of the second image @param newSize Image size of rectified image, see omnidir::undistortImage @param Knew New camera matrix of rectified image, see omnidir::undistortImage @param pointCloud Point cloud of 3D reconstruction, with type CV_64FC3 @param pointType Point cloud type, it can be XYZRGB or XYZ */ CV_EXPORTS_W void stereoReconstruct(InputArray image1, InputArray image2, InputArray K1, InputArray D1, InputArray xi1, InputArray K2, InputArray D2, InputArray xi2, InputArray R, InputArray T, int flag, int numDisparities, int SADWindowSize, OutputArray disparity, OutputArray image1Rec, OutputArray image2Rec, const Size& newSize = Size(), InputArray Knew = cv::noArray(), OutputArray pointCloud = cv::noArray(), int pointType = XYZRGB); namespace internal { void initializeCalibration(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size size, OutputArrayOfArrays omAll, OutputArrayOfArrays tAll, OutputArray K, double& xi, OutputArray idx = noArray()); void initializeStereoCalibration(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, const Size& size1, const Size& size2, OutputArray om, OutputArray T, OutputArrayOfArrays omL, OutputArrayOfArrays tL, OutputArray K1, OutputArray D1, OutputArray K2, OutputArray D2, double &xi1, double &xi2, int flags, OutputArray idx); void computeJacobian(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, InputArray parameters, Mat& JTJ_inv, Mat& JTE, int flags, double epsilon); void computeJacobianStereo(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputArray parameters, Mat& JTJ_inv, Mat& JTE, int flags, double epsilon); void encodeParameters(InputArray K, InputArrayOfArrays omAll, InputArrayOfArrays tAll, InputArray distoaration, double xi, OutputArray parameters); void encodeParametersStereo(InputArray K1, InputArray K2, InputArray om, InputArray T, InputArrayOfArrays omL, InputArrayOfArrays tL, InputArray D1, InputArray D2, double xi1, double xi2, OutputArray parameters); void decodeParameters(InputArray paramsters, OutputArray K, OutputArrayOfArrays omAll, OutputArrayOfArrays tAll, OutputArray distoration, double& xi); void decodeParametersStereo(InputArray parameters, OutputArray K1, OutputArray K2, OutputArray om, OutputArray T, OutputArrayOfArrays omL, OutputArrayOfArrays tL, OutputArray D1, OutputArray D2, double& xi1, double& xi2); void estimateUncertainties(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, InputArray parameters, Mat& errors, Vec2d& std_error, double& rms, int flags); void estimateUncertaintiesStereo(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputArray parameters, Mat& errors, Vec2d& std_error, double& rms, int flags); double computeMeanReproErr(InputArrayOfArrays imagePoints, InputArrayOfArrays proImagePoints); double computeMeanReproErr(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, InputArray K, InputArray D, double xi, InputArrayOfArrays omAll, InputArrayOfArrays tAll); double computeMeanReproErrStereo(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputArray K1, InputArray K2, InputArray D1, InputArray D2, double xi1, double xi2, InputArray om, InputArray T, InputArrayOfArrays omL, InputArrayOfArrays TL); void checkFixed(Mat &G, int flags, int n); void subMatrix(const Mat& src, Mat& dst, const std::vector& cols, const std::vector& rows); void flags2idx(int flags, std::vector& idx, int n); void flags2idxStereo(int flags, std::vector& idx, int n); void fillFixed(Mat&G, int flags, int n); void fillFixedStereo(Mat& G, int flags, int n); double findMedian(const Mat& row); Vec3d findMedian3(InputArray mat); void getInterset(InputArray idx1, InputArray idx2, OutputArray inter1, OutputArray inter2, OutputArray inter_ori); void compose_motion(InputArray _om1, InputArray _T1, InputArray _om2, InputArray _T2, Mat& om3, Mat& T3, Mat& dom3dom1, Mat& dom3dT1, Mat& dom3dom2, Mat& dom3dT2, Mat& dT3dom1, Mat& dT3dT1, Mat& dT3dom2, Mat& dT3dT2); //void JRodriguesMatlab(const Mat& src, Mat& dst); //void dAB(InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB); } // internal //! @} } // omnidir } //cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/ccalib/randpattern.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Baisheng Lai (laibaisheng@gmail.com), Zhejiang University, // all rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_RANDOMPATTERN_HPP__ #define __OPENCV_RANDOMPATTERN_HPP__ #include "opencv2/features2d.hpp" #include "opencv2/highgui.hpp" namespace cv { namespace randpattern { //! @addtogroup ccalib //! @{ /** @brief Class for finding features points and corresponding 3D in world coordinate of a "random" pattern, which can be to be used in calibration. It is useful when pattern is partly occluded or only a part of pattern can be observed in multiple cameras calibration. The pattern can be generated by RandomPatternGenerator class described in this file. Please refer to paper B. Li, L. Heng, K. Kevin and M. Pollefeys, "A Multiple-Camera System Calibration Toolbox Using A Feature Descriptor-Based Calibration Pattern", in IROS 2013. */ class CV_EXPORTS RandomPatternCornerFinder { public: /* @brief Construct RandomPatternCornerFinder object @param patternWidth the real width of "random" pattern in a user defined unit. @param patternHeight the real height of "random" pattern in a user defined unit. @param nMiniMatch number of minimal matches, otherwise that image is abandoned @depth depth of output objectPoints and imagePoints, set it to be CV_32F or CV_64F. @showExtraction whether show feature extraction, 0 for no and 1 for yes. @detector feature detector to detect feature points in pattern and images. @descriptor feature descriptor. @matcher feature matcher. */ RandomPatternCornerFinder(float patternWidth, float patternHeight, int nminiMatch = 20, int depth = CV_32F, int verbose = 0, int showExtraction = 0, Ptr detector = AKAZE::create(AKAZE::DESCRIPTOR_MLDB, 0, 3, 0.005f), Ptr descriptor = AKAZE::create(AKAZE::DESCRIPTOR_MLDB,0, 3, 0.005f), Ptr matcher = DescriptorMatcher::create("BruteForce-L1")); /* @brief Load pattern image and compute features for pattern @param patternImage image for "random" pattern generated by RandomPatternGenerator, run it first. */ void loadPattern(cv::Mat patternImage); /* @brief Compute matched object points and image points which are used for calibration The objectPoints (3D) and imagePoints (2D) are stored inside the class. Run getObjectPoints() and getImagePoints() to get them. @param inputImages vector of 8-bit grayscale images containing "random" pattern that are used for calibration. */ void computeObjectImagePoints(std::vector inputImages); //void computeObjectImagePoints2(std::vector inputImages); /* @brief Compute object and image points for a single image. It returns a vector that the first element stores the imagePoints and the second one stores the objectPoints. @param inputImage single input image for calibration */ std::vector computeObjectImagePointsForSingle(cv::Mat inputImage); /* @brief Get object(3D) points */ std::vector getObjectPoints(); /* @brief and image(2D) points */ std::vector getImagePoints(); private: std::vector _objectPonits, _imagePoints; float _patternWidth, _patternHeight; cv::Size _patternImageSize; int _nminiMatch; int _depth; int _verbose; Ptr _detector; Ptr _descriptor; Ptr _matcher; Mat _descriptorPattern; std::vector _keypointsPattern; Mat _patternImage; int _showExtraction; void keyPoints2MatchedLocation(const std::vector& imageKeypoints, const std::vector& patternKeypoints, const std::vector matchces, cv::Mat& matchedImagelocation, cv::Mat& matchedPatternLocation); void getFilteredLocation(cv::Mat& imageKeypoints, cv::Mat& patternKeypoints, const cv::Mat mask); void getObjectImagePoints(const cv::Mat& imageKeypoints, const cv::Mat& patternKeypoints); void crossCheckMatching( cv::Ptr& descriptorMatcher, const Mat& descriptors1, const Mat& descriptors2, std::vector& filteredMatches12, int knn=1 ); void drawCorrespondence(const Mat& image1, const std::vector keypoint1, const Mat& image2, const std::vector keypoint2, const std::vector matchces, const Mat& mask1, const Mat& mask2, const int step); }; /* @brief Class to generate "random" pattern image that are used for RandomPatternCornerFinder Please refer to paper B. Li, L. Heng, K. Kevin and M. Pollefeys, "A Multiple-Camera System Calibration Toolbox Using A Feature Descriptor-Based Calibration Pattern", in IROS 2013. */ class CV_EXPORTS RandomPatternGenerator { public: /* @brief Construct RandomPatternGenerator @param imageWidth image width of the generated pattern image @param imageHeight image height of the generated pattern image */ RandomPatternGenerator(int imageWidth, int imageHeight); /* @brief Generate pattern */ void generatePattern(); /* @brief Get pattern */ cv::Mat getPattern(); private: cv::Mat _pattern; int _imageWidth, _imageHeight; }; //! @} }} //namespace randpattern, cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/ccalib.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CCALIB_HPP__ #define __OPENCV_CCALIB_HPP__ #include #include #include #include #include /** @defgroup ccalib Custom Calibration Pattern for 3D reconstruction */ namespace cv{ namespace ccalib{ //! @addtogroup ccalib //! @{ class CV_EXPORTS CustomPattern : public Algorithm { public: CustomPattern(); virtual ~CustomPattern(); bool create(InputArray pattern, const Size2f boardSize, OutputArray output = noArray()); bool findPattern(InputArray image, OutputArray matched_features, OutputArray pattern_points, const double ratio = 0.7, const double proj_error = 8.0, const bool refine_position = false, OutputArray out = noArray(), OutputArray H = noArray(), OutputArray pattern_corners = noArray()); bool isInitialized(); void getPatternPoints(OutputArray original_points); /**< Returns a vector of the original points. */ double getPixelSize(); /**< Get the pixel size of the pattern */ bool setFeatureDetector(Ptr featureDetector); bool setDescriptorExtractor(Ptr extractor); bool setDescriptorMatcher(Ptr matcher); Ptr getFeatureDetector(); Ptr getDescriptorExtractor(); Ptr getDescriptorMatcher(); double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON)); /**< Calls the calirateCamera function with the same inputs. */ bool findRt(InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE); bool findRt(InputArray image, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE); /**< Uses solvePnP to find the rotation and translation of the pattern with respect to the camera frame. */ bool findRtRANSAC(InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8.0, int minInliersCount = 100, OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE); bool findRtRANSAC(InputArray image, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8.0, int minInliersCount = 100, OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE); /**< Uses solvePnPRansac() */ void drawOrientation(InputOutputArray image, InputArray tvec, InputArray rvec, InputArray cameraMatrix, InputArray distCoeffs, double axis_length = 3, int axis_width = 2); /**< pattern_corners -> projected over the image position of the edges of the pattern. */ private: Mat img_roi; std::vector obj_corners; double pxSize; bool initialized; Ptr detector; Ptr descriptorExtractor; Ptr descriptorMatcher; std::vector keypoints; std::vector points3d; Mat descriptor; bool init(Mat& image, const float pixel_size, OutputArray output = noArray()); bool findPatternPass(const Mat& image, std::vector& matched_features, std::vector& pattern_points, Mat& H, std::vector& scene_corners, const double pratio, const double proj_error, const bool refine_position = false, const Mat& mask = Mat(), OutputArray output = noArray()); void scaleFoundPoints(const double squareSize, const std::vector& corners, std::vector& pts3d); void check_matches(std::vector& matched, const std::vector& pattern, std::vector& good, std::vector& pattern_3d, const Mat& H); void keypoints2points(const std::vector& in, std::vector& out); void updateKeypointsPos(std::vector& in, const std::vector& new_pos); void refinePointsPos(const Mat& img, std::vector& p); void refineKeypointsPos(const Mat& img, std::vector& kp); }; //! @} }} // namespace ccalib, cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/affine.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_AFFINE3_HPP__ #define __OPENCV_CORE_AFFINE3_HPP__ #ifdef __cplusplus #include namespace cv { //! @addtogroup core //! @{ /** @brief Affine transform @todo document */ template class Affine3 { public: typedef T float_type; typedef Matx Mat3; typedef Matx Mat4; typedef Vec Vec3; Affine3(); //! Augmented affine matrix Affine3(const Mat4& affine); //! Rotation matrix Affine3(const Mat3& R, const Vec3& t = Vec3::all(0)); //! Rodrigues vector Affine3(const Vec3& rvec, const Vec3& t = Vec3::all(0)); //! Combines all contructors above. Supports 4x4, 4x3, 3x3, 1x3, 3x1 sizes of data matrix explicit Affine3(const Mat& data, const Vec3& t = Vec3::all(0)); //! From 16th element array explicit Affine3(const float_type* vals); //! Create identity transform static Affine3 Identity(); //! Rotation matrix void rotation(const Mat3& R); //! Rodrigues vector void rotation(const Vec3& rvec); //! Combines rotation methods above. Suports 3x3, 1x3, 3x1 sizes of data matrix; void rotation(const Mat& data); void linear(const Mat3& L); void translation(const Vec3& t); Mat3 rotation() const; Mat3 linear() const; Vec3 translation() const; //! Rodrigues vector Vec3 rvec() const; Affine3 inv(int method = cv::DECOMP_SVD) const; //! a.rotate(R) is equivalent to Affine(R, 0) * a; Affine3 rotate(const Mat3& R) const; //! a.rotate(rvec) is equivalent to Affine(rvec, 0) * a; Affine3 rotate(const Vec3& rvec) const; //! a.translate(t) is equivalent to Affine(E, t) * a; Affine3 translate(const Vec3& t) const; //! a.concatenate(affine) is equivalent to affine * a; Affine3 concatenate(const Affine3& affine) const; template operator Affine3() const; template Affine3 cast() const; Mat4 matrix; #if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H Affine3(const Eigen::Transform& affine); Affine3(const Eigen::Transform& affine); operator Eigen::Transform() const; operator Eigen::Transform() const; #endif }; template static Affine3 operator*(const Affine3& affine1, const Affine3& affine2); template static V operator*(const Affine3& affine, const V& vector); typedef Affine3 Affine3f; typedef Affine3 Affine3d; static Vec3f operator*(const Affine3f& affine, const Vec3f& vector); static Vec3d operator*(const Affine3d& affine, const Vec3d& vector); template class DataType< Affine3<_Tp> > { public: typedef Affine3<_Tp> value_type; typedef Affine3::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 16, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //! @} core } //! @cond IGNORED /////////////////////////////////////////////////////////////////////////////////// // Implementaiton template inline cv::Affine3::Affine3() : matrix(Mat4::eye()) {} template inline cv::Affine3::Affine3(const Mat4& affine) : matrix(affine) {} template inline cv::Affine3::Affine3(const Mat3& R, const Vec3& t) { rotation(R); translation(t); matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; matrix.val[15] = 1; } template inline cv::Affine3::Affine3(const Vec3& _rvec, const Vec3& t) { rotation(_rvec); translation(t); matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; matrix.val[15] = 1; } template inline cv::Affine3::Affine3(const cv::Mat& data, const Vec3& t) { CV_Assert(data.type() == cv::DataType::type); if (data.cols == 4 && data.rows == 4) { data.copyTo(matrix); return; } else if (data.cols == 4 && data.rows == 3) { rotation(data(Rect(0, 0, 3, 3))); translation(data(Rect(3, 0, 1, 3))); return; } rotation(data); translation(t); matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; matrix.val[15] = 1; } template inline cv::Affine3::Affine3(const float_type* vals) : matrix(vals) {} template inline cv::Affine3 cv::Affine3::Identity() { return Affine3(cv::Affine3::Mat4::eye()); } template inline void cv::Affine3::rotation(const Mat3& R) { linear(R); } template inline void cv::Affine3::rotation(const Vec3& _rvec) { double rx = _rvec[0], ry = _rvec[1], rz = _rvec[2]; double theta = std::sqrt(rx*rx + ry*ry + rz*rz); if (theta < DBL_EPSILON) rotation(Mat3::eye()); else { const double I[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; double c = std::cos(theta); double s = std::sin(theta); double c1 = 1. - c; double itheta = (theta != 0) ? 1./theta : 0.; rx *= itheta; ry *= itheta; rz *= itheta; double rrt[] = { rx*rx, rx*ry, rx*rz, rx*ry, ry*ry, ry*rz, rx*rz, ry*rz, rz*rz }; double _r_x_[] = { 0, -rz, ry, rz, 0, -rx, -ry, rx, 0 }; Mat3 R; // R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x] // where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0] for(int k = 0; k < 9; ++k) R.val[k] = static_cast(c*I[k] + c1*rrt[k] + s*_r_x_[k]); rotation(R); } } //Combines rotation methods above. Suports 3x3, 1x3, 3x1 sizes of data matrix; template inline void cv::Affine3::rotation(const cv::Mat& data) { CV_Assert(data.type() == cv::DataType::type); if (data.cols == 3 && data.rows == 3) { Mat3 R; data.copyTo(R); rotation(R); } else if ((data.cols == 3 && data.rows == 1) || (data.cols == 1 && data.rows == 3)) { Vec3 _rvec; data.reshape(1, 3).copyTo(_rvec); rotation(_rvec); } else CV_Assert(!"Input marix can be 3x3, 1x3 or 3x1"); } template inline void cv::Affine3::linear(const Mat3& L) { matrix.val[0] = L.val[0]; matrix.val[1] = L.val[1]; matrix.val[ 2] = L.val[2]; matrix.val[4] = L.val[3]; matrix.val[5] = L.val[4]; matrix.val[ 6] = L.val[5]; matrix.val[8] = L.val[6]; matrix.val[9] = L.val[7]; matrix.val[10] = L.val[8]; } template inline void cv::Affine3::translation(const Vec3& t) { matrix.val[3] = t[0]; matrix.val[7] = t[1]; matrix.val[11] = t[2]; } template inline typename cv::Affine3::Mat3 cv::Affine3::rotation() const { return linear(); } template inline typename cv::Affine3::Mat3 cv::Affine3::linear() const { typename cv::Affine3::Mat3 R; R.val[0] = matrix.val[0]; R.val[1] = matrix.val[1]; R.val[2] = matrix.val[ 2]; R.val[3] = matrix.val[4]; R.val[4] = matrix.val[5]; R.val[5] = matrix.val[ 6]; R.val[6] = matrix.val[8]; R.val[7] = matrix.val[9]; R.val[8] = matrix.val[10]; return R; } template inline typename cv::Affine3::Vec3 cv::Affine3::translation() const { return Vec3(matrix.val[3], matrix.val[7], matrix.val[11]); } template inline typename cv::Affine3::Vec3 cv::Affine3::rvec() const { cv::Vec3d w; cv::Matx33d u, vt, R = rotation(); cv::SVD::compute(R, w, u, vt, cv::SVD::FULL_UV + cv::SVD::MODIFY_A); R = u * vt; double rx = R.val[7] - R.val[5]; double ry = R.val[2] - R.val[6]; double rz = R.val[3] - R.val[1]; double s = std::sqrt((rx*rx + ry*ry + rz*rz)*0.25); double c = (R.val[0] + R.val[4] + R.val[8] - 1) * 0.5; c = c > 1.0 ? 1.0 : c < -1.0 ? -1.0 : c; double theta = acos(c); if( s < 1e-5 ) { if( c > 0 ) rx = ry = rz = 0; else { double t; t = (R.val[0] + 1) * 0.5; rx = std::sqrt(std::max(t, 0.0)); t = (R.val[4] + 1) * 0.5; ry = std::sqrt(std::max(t, 0.0)) * (R.val[1] < 0 ? -1.0 : 1.0); t = (R.val[8] + 1) * 0.5; rz = std::sqrt(std::max(t, 0.0)) * (R.val[2] < 0 ? -1.0 : 1.0); if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R.val[5] > 0) != (ry*rz > 0) ) rz = -rz; theta /= std::sqrt(rx*rx + ry*ry + rz*rz); rx *= theta; ry *= theta; rz *= theta; } } else { double vth = 1/(2*s); vth *= theta; rx *= vth; ry *= vth; rz *= vth; } return cv::Vec3d(rx, ry, rz); } template inline cv::Affine3 cv::Affine3::inv(int method) const { return matrix.inv(method); } template inline cv::Affine3 cv::Affine3::rotate(const Mat3& R) const { Mat3 Lc = linear(); Vec3 tc = translation(); Mat4 result; result.val[12] = result.val[13] = result.val[14] = 0; result.val[15] = 1; for(int j = 0; j < 3; ++j) { for(int i = 0; i < 3; ++i) { float_type value = 0; for(int k = 0; k < 3; ++k) value += R(j, k) * Lc(k, i); result(j, i) = value; } result(j, 3) = R.row(j).dot(tc.t()); } return result; } template inline cv::Affine3 cv::Affine3::rotate(const Vec3& _rvec) const { return rotate(Affine3f(_rvec).rotation()); } template inline cv::Affine3 cv::Affine3::translate(const Vec3& t) const { Mat4 m = matrix; m.val[ 3] += t[0]; m.val[ 7] += t[1]; m.val[11] += t[2]; return m; } template inline cv::Affine3 cv::Affine3::concatenate(const Affine3& affine) const { return (*this).rotate(affine.rotation()).translate(affine.translation()); } template template inline cv::Affine3::operator Affine3() const { return Affine3(matrix); } template template inline cv::Affine3 cv::Affine3::cast() const { return Affine3(matrix); } template inline cv::Affine3 cv::operator*(const cv::Affine3& affine1, const cv::Affine3& affine2) { return affine2.concatenate(affine1); } template inline V cv::operator*(const cv::Affine3& affine, const V& v) { const typename Affine3::Mat4& m = affine.matrix; V r; r.x = m.val[0] * v.x + m.val[1] * v.y + m.val[ 2] * v.z + m.val[ 3]; r.y = m.val[4] * v.x + m.val[5] * v.y + m.val[ 6] * v.z + m.val[ 7]; r.z = m.val[8] * v.x + m.val[9] * v.y + m.val[10] * v.z + m.val[11]; return r; } static inline cv::Vec3f cv::operator*(const cv::Affine3f& affine, const cv::Vec3f& v) { const cv::Matx44f& m = affine.matrix; cv::Vec3f r; r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; return r; } static inline cv::Vec3d cv::operator*(const cv::Affine3d& affine, const cv::Vec3d& v) { const cv::Matx44d& m = affine.matrix; cv::Vec3d r; r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; return r; } #if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H template inline cv::Affine3::Affine3(const Eigen::Transform& affine) { cv::Mat(4, 4, cv::DataType::type, affine.matrix().data()).copyTo(matrix); } template inline cv::Affine3::Affine3(const Eigen::Transform& affine) { Eigen::Transform a = affine; cv::Mat(4, 4, cv::DataType::type, a.matrix().data()).copyTo(matrix); } template inline cv::Affine3::operator Eigen::Transform() const { Eigen::Transform r; cv::Mat hdr(4, 4, cv::DataType::type, r.matrix().data()); cv::Mat(matrix, false).copyTo(hdr); return r; } template inline cv::Affine3::operator Eigen::Transform() const { return this->operator Eigen::Transform(); } #endif /* defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H */ //! @endcond #endif /* __cplusplus */ #endif /* __OPENCV_CORE_AFFINE3_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/base.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2014, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_BASE_HPP__ #define __OPENCV_CORE_BASE_HPP__ #ifndef __cplusplus # error base.hpp header must be compiled as C++ #endif #include #include #include "opencv2/core/cvdef.h" #include "opencv2/core/cvstd.hpp" namespace cv { //! @addtogroup core_utils //! @{ namespace Error { //! error codes enum Code { StsOk= 0, //!< everithing is ok StsBackTrace= -1, //!< pseudo error for back trace StsError= -2, //!< unknown /unspecified error StsInternal= -3, //!< internal error (bad state) StsNoMem= -4, //!< insufficient memory StsBadArg= -5, //!< function arg/param is bad StsBadFunc= -6, //!< unsupported function StsNoConv= -7, //!< iter. didn't converge StsAutoTrace= -8, //!< tracing HeaderIsNull= -9, //!< image header is NULL BadImageSize= -10, //!< image size is invalid BadOffset= -11, //!< offset is invalid BadDataPtr= -12, //!< BadStep= -13, //!< BadModelOrChSeq= -14, //!< BadNumChannels= -15, //!< BadNumChannel1U= -16, //!< BadDepth= -17, //!< BadAlphaChannel= -18, //!< BadOrder= -19, //!< BadOrigin= -20, //!< BadAlign= -21, //!< BadCallBack= -22, //!< BadTileSize= -23, //!< BadCOI= -24, //!< BadROISize= -25, //!< MaskIsTiled= -26, //!< StsNullPtr= -27, //!< null pointer StsVecLengthErr= -28, //!< incorrect vector length StsFilterStructContentErr= -29, //!< incorr. filter structure content StsKernelStructContentErr= -30, //!< incorr. transform kernel content StsFilterOffsetErr= -31, //!< incorrect filter ofset value StsBadSize= -201, //!< the input/output structure size is incorrect StsDivByZero= -202, //!< division by zero StsInplaceNotSupported= -203, //!< in-place operation is not supported StsObjectNotFound= -204, //!< request can't be completed StsUnmatchedFormats= -205, //!< formats of input/output arrays differ StsBadFlag= -206, //!< flag is wrong or not supported StsBadPoint= -207, //!< bad CvPoint StsBadMask= -208, //!< bad format of mask (neither 8uC1 nor 8sC1) StsUnmatchedSizes= -209, //!< sizes of input/output structures do not match StsUnsupportedFormat= -210, //!< the data format/type is not supported by the function StsOutOfRange= -211, //!< some of parameters are out of range StsParseError= -212, //!< invalid syntax/structure of the parsed file StsNotImplemented= -213, //!< the requested function/feature is not implemented StsBadMemBlock= -214, //!< an allocated block has been corrupted StsAssert= -215, //!< assertion failed GpuNotSupported= -216, GpuApiCallError= -217, OpenGlNotSupported= -218, OpenGlApiCallError= -219, OpenCLApiCallError= -220, OpenCLDoubleNotSupported= -221, OpenCLInitError= -222, OpenCLNoAMDBlasFft= -223 }; } //Error //! @} core_utils //! @addtogroup core_array //! @{ //! matrix decomposition types enum DecompTypes { /** Gaussian elimination with the optimal pivot element chosen. */ DECOMP_LU = 0, /** singular value decomposition (SVD) method; the system can be over-defined and/or the matrix src1 can be singular */ DECOMP_SVD = 1, /** eigenvalue decomposition; the matrix src1 must be symmetrical */ DECOMP_EIG = 2, /** Cholesky \f$LL^T\f$ factorization; the matrix src1 must be symmetrical and positively defined */ DECOMP_CHOLESKY = 3, /** QR factorization; the system can be over-defined and/or the matrix src1 can be singular */ DECOMP_QR = 4, /** while all the previous flags are mutually exclusive, this flag can be used together with any of the previous; it means that the normal equations \f$\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}\f$ are solved instead of the original system \f$\texttt{src1}\cdot\texttt{dst}=\texttt{src2}\f$ */ DECOMP_NORMAL = 16 }; /** norm types - For one array: \f[norm = \forkthree{\|\texttt{src1}\|_{L_{\infty}} = \max _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } { \| \texttt{src1} \| _{L_1} = \sum _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } { \| \texttt{src1} \| _{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) }\f] - Absolute norm for two arrays \f[norm = \forkthree{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} = \max _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } { \| \texttt{src1} - \texttt{src2} \| _{L_1} = \sum _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } { \| \texttt{src1} - \texttt{src2} \| _{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) }\f] - Relative norm for two arrays \f[norm = \forkthree{\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} }{\|\texttt{src2}\|_{L_{\infty}} }}{if \(\texttt{normType} = \texttt{NORM_RELATIVE_INF}\) } { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE_L1}\) } { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE_L2}\) }\f] As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ is calculated as follows \f{align*} \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 \f} and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is \f{align*} \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. \f} The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$. It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$. ![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) */ enum NormTypes { NORM_INF = 1, NORM_L1 = 2, NORM_L2 = 4, NORM_L2SQR = 5, NORM_HAMMING = 6, NORM_HAMMING2 = 7, NORM_TYPE_MASK = 7, NORM_RELATIVE = 8, //!< flag NORM_MINMAX = 32 //!< flag }; //! comparison types enum CmpTypes { CMP_EQ = 0, //!< src1 is equal to src2. CMP_GT = 1, //!< src1 is greater than src2. CMP_GE = 2, //!< src1 is greater than or equal to src2. CMP_LT = 3, //!< src1 is less than src2. CMP_LE = 4, //!< src1 is less than or equal to src2. CMP_NE = 5 //!< src1 is unequal to src2. }; //! generalized matrix multiplication flags enum GemmFlags { GEMM_1_T = 1, //!< transposes src1 GEMM_2_T = 2, //!< transposes src2 GEMM_3_T = 4 //!< transposes src3 }; enum DftFlags { /** performs an inverse 1D or 2D transform instead of the default forward transform. */ DFT_INVERSE = 1, /** scales the result: divide it by the number of array elements. Normally, it is combined with DFT_INVERSE. */ DFT_SCALE = 2, /** performs a forward or inverse transform of every individual row of the input matrix; this flag enables you to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself) to perform 3D and higher-dimensional transformations and so forth.*/ DFT_ROWS = 4, /** performs a forward transformation of 1D or 2D real array; the result, though being a complex array, has complex-conjugate symmetry (*CCS*, see the function description below for details), and such an array can be packed into a real array of the same size as input, which is the fastest option and which is what the function does by default; however, you may wish to get a full complex array (for simpler spectrum analysis, and so on) - pass the flag to enable the function to produce a full-size complex output array. */ DFT_COMPLEX_OUTPUT = 16, /** performs an inverse transformation of a 1D or 2D complex array; the result is normally a complex array of the same size, however, if the input array has conjugate-complex symmetry (for example, it is a result of forward transformation with DFT_COMPLEX_OUTPUT flag), the output is a real array; while the function itself does not check whether the input is symmetrical or not, you can pass the flag and then the function will assume the symmetry and produce the real output array (note that when the input is packed into a real array and inverse transformation is executed, the function treats the input as a packed complex-conjugate symmetrical array, and the output will also be a real array). */ DFT_REAL_OUTPUT = 32, /** performs an inverse 1D or 2D transform instead of the default forward transform. */ DCT_INVERSE = DFT_INVERSE, /** performs a forward or inverse transform of every individual row of the input matrix. This flag enables you to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself) to perform 3D and higher-dimensional transforms and so forth.*/ DCT_ROWS = DFT_ROWS }; //! Various border types, image boundaries are denoted with `|` //! @see borderInterpolate, copyMakeBorder enum BorderTypes { BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` BORDER_TRANSPARENT = 5, //!< `uvwxyz|absdefgh|ijklmno` BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 BORDER_ISOLATED = 16 //!< do not look outside of ROI }; //! @} core_array //! @addtogroup core_utils //! @{ //! @cond IGNORED //////////////// static assert ///////////////// #define CVAUX_CONCAT_EXP(a, b) a##b #define CVAUX_CONCAT(a, b) CVAUX_CONCAT_EXP(a,b) #if defined(__clang__) # ifndef __has_extension # define __has_extension __has_feature /* compatibility, for older versions of clang */ # endif # if __has_extension(cxx_static_assert) # define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) # elif __has_extension(c_static_assert) # define CV_StaticAssert(condition, reason) _Static_assert((condition), reason " " #condition) # endif #elif defined(__GNUC__) # if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) # define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) # endif #elif defined(_MSC_VER) # if _MSC_VER >= 1600 /* MSVC 10 */ # define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) # endif #endif #ifndef CV_StaticAssert # if !defined(__clang__) && defined(__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 302) # define CV_StaticAssert(condition, reason) ({ extern int __attribute__((error("CV_StaticAssert: " reason " " #condition))) CV_StaticAssert(); ((condition) ? 0 : CV_StaticAssert()); }) # else template struct CV_StaticAssert_failed; template <> struct CV_StaticAssert_failed { enum { val = 1 }; }; template struct CV_StaticAssert_test {}; # define CV_StaticAssert(condition, reason)\ typedef cv::CV_StaticAssert_test< sizeof(cv::CV_StaticAssert_failed< static_cast(condition) >) > CVAUX_CONCAT(CV_StaticAssert_failed_at_, __LINE__) # endif #endif // Suppress warning "-Wdeprecated-declarations" / C4996 #if defined(_MSC_VER) #define CV_DO_PRAGMA(x) __pragma(x) #elif defined(__GNUC__) #define CV_DO_PRAGMA(x) _Pragma (#x) #else #define CV_DO_PRAGMA(x) #endif #ifdef _MSC_VER #define CV_SUPPRESS_DEPRECATED_START \ CV_DO_PRAGMA(warning(push)) \ CV_DO_PRAGMA(warning(disable: 4996)) #define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(warning(pop)) #elif defined (__clang__) || ((__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 405)) #define CV_SUPPRESS_DEPRECATED_START \ CV_DO_PRAGMA(GCC diagnostic push) \ CV_DO_PRAGMA(GCC diagnostic ignored "-Wdeprecated-declarations") #define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(GCC diagnostic pop) #else #define CV_SUPPRESS_DEPRECATED_START #define CV_SUPPRESS_DEPRECATED_END #endif #define CV_UNUSED(name) (void)name //! @endcond /*! @brief Signals an error and raises the exception. By default the function prints information about the error to stderr, then it either stops if setBreakOnError() had been called before or raises the exception. It is possible to alternate error processing by using redirectError(). @param _code - error code (Error::Code) @param _err - error description @param _func - function name. Available only when the compiler supports getting it @param _file - source file name where the error has occured @param _line - line number in the source file where the error has occured @see CV_Error, CV_Error_, CV_ErrorNoReturn, CV_ErrorNoReturn_, CV_Assert, CV_DbgAssert */ CV_EXPORTS void error(int _code, const String& _err, const char* _func, const char* _file, int _line); #ifdef __GNUC__ # if defined __clang__ || defined __APPLE__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Winvalid-noreturn" # endif #endif /** same as cv::error, but does not return */ CV_INLINE CV_NORETURN void errorNoReturn(int _code, const String& _err, const char* _func, const char* _file, int _line) { error(_code, _err, _func, _file, _line); #ifdef __GNUC__ # if !defined __clang__ && !defined __APPLE__ // this suppresses this warning: "noreturn" function does return [enabled by default] __builtin_trap(); // or use infinite loop: for (;;) {} # endif #endif } #ifdef __GNUC__ # if defined __clang__ || defined __APPLE__ # pragma GCC diagnostic pop # endif #endif #if defined __GNUC__ #define CV_Func __func__ #elif defined _MSC_VER #define CV_Func __FUNCTION__ #else #define CV_Func "" #endif /** @brief Call the error handler. Currently, the error handler prints the error code and the error message to the standard error stream `stderr`. In the Debug configuration, it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed by the debugger. In the Release configuration, the exception is thrown. @param code one of Error::Code @param msg error message */ #define CV_Error( code, msg ) cv::error( code, msg, CV_Func, __FILE__, __LINE__ ) /** @brief Call the error handler. This macro can be used to construct an error message on-fly to include some dynamic information, for example: @code // note the extra parentheses around the formatted text message CV_Error_( CV_StsOutOfRange, ("the value at (%d, %d)=%g is out of range", badPt.x, badPt.y, badValue)); @endcode @param code one of Error::Code @param args printf-like formatted error message in parentheses */ #define CV_Error_( code, args ) cv::error( code, cv::format args, CV_Func, __FILE__, __LINE__ ) /** @brief Checks a condition at runtime and throws exception if it fails The macros CV_Assert (and CV_DbgAssert(expr)) evaluate the specified expression. If it is 0, the macros raise an error (see cv::error). The macro CV_Assert checks the condition in both Debug and Release configurations while CV_DbgAssert is only retained in the Debug configuration. */ #define CV_Assert( expr ) if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ) /** same as CV_Error(code,msg), but does not return */ #define CV_ErrorNoReturn( code, msg ) cv::errorNoReturn( code, msg, CV_Func, __FILE__, __LINE__ ) /** same as CV_Error_(code,args), but does not return */ #define CV_ErrorNoReturn_( code, args ) cv::errorNoReturn( code, cv::format args, CV_Func, __FILE__, __LINE__ ) /** replaced with CV_Assert(expr) in Debug configuration */ #ifdef _DEBUG # define CV_DbgAssert(expr) CV_Assert(expr) #else # define CV_DbgAssert(expr) #endif /* * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor * bit count of A exclusive XOR'ed with B */ struct CV_EXPORTS Hamming { enum { normType = NORM_HAMMING }; typedef unsigned char ValueType; typedef int ResultType; /** this will count the bits in a ^ b */ ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const; }; typedef Hamming HammingLUT; /////////////////////////////////// inline norms //////////////////////////////////// template inline _Tp cv_abs(_Tp x) { return std::abs(x); } inline int cv_abs(uchar x) { return x; } inline int cv_abs(schar x) { return std::abs(x); } inline int cv_abs(ushort x) { return x; } inline int cv_abs(short x) { return std::abs(x); } template static inline _AccTp normL2Sqr(const _Tp* a, int n) { _AccTp s = 0; int i=0; #if CV_ENABLE_UNROLLED for( ; i <= n - 4; i += 4 ) { _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3]; s += v0*v0 + v1*v1 + v2*v2 + v3*v3; } #endif for( ; i < n; i++ ) { _AccTp v = a[i]; s += v*v; } return s; } template static inline _AccTp normL1(const _Tp* a, int n) { _AccTp s = 0; int i = 0; #if CV_ENABLE_UNROLLED for(; i <= n - 4; i += 4 ) { s += (_AccTp)cv_abs(a[i]) + (_AccTp)cv_abs(a[i+1]) + (_AccTp)cv_abs(a[i+2]) + (_AccTp)cv_abs(a[i+3]); } #endif for( ; i < n; i++ ) s += cv_abs(a[i]); return s; } template static inline _AccTp normInf(const _Tp* a, int n) { _AccTp s = 0; for( int i = 0; i < n; i++ ) s = std::max(s, (_AccTp)cv_abs(a[i])); return s; } template static inline _AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n) { _AccTp s = 0; int i= 0; #if CV_ENABLE_UNROLLED for(; i <= n - 4; i += 4 ) { _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); s += v0*v0 + v1*v1 + v2*v2 + v3*v3; } #endif for( ; i < n; i++ ) { _AccTp v = _AccTp(a[i] - b[i]); s += v*v; } return s; } static inline float normL2Sqr(const float* a, const float* b, int n) { float s = 0.f; for( int i = 0; i < n; i++ ) { float v = a[i] - b[i]; s += v*v; } return s; } template static inline _AccTp normL1(const _Tp* a, const _Tp* b, int n) { _AccTp s = 0; int i= 0; #if CV_ENABLE_UNROLLED for(; i <= n - 4; i += 4 ) { _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3); } #endif for( ; i < n; i++ ) { _AccTp v = _AccTp(a[i] - b[i]); s += std::abs(v); } return s; } inline float normL1(const float* a, const float* b, int n) { float s = 0.f; for( int i = 0; i < n; i++ ) { s += std::abs(a[i] - b[i]); } return s; } inline int normL1(const uchar* a, const uchar* b, int n) { int s = 0; for( int i = 0; i < n; i++ ) { s += std::abs(a[i] - b[i]); } return s; } template static inline _AccTp normInf(const _Tp* a, const _Tp* b, int n) { _AccTp s = 0; for( int i = 0; i < n; i++ ) { _AccTp v0 = a[i] - b[i]; s = std::max(s, std::abs(v0)); } return s; } /** @brief Computes the cube root of an argument. The function cubeRoot computes \f$\sqrt[3]{\texttt{val}}\f$. Negative arguments are handled correctly. NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for single-precision data. @param val A function argument. */ CV_EXPORTS_W float cubeRoot(float val); /** @brief Calculates the angle of a 2D vector in degrees. The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees. @param x x-coordinate of the vector. @param y y-coordinate of the vector. */ CV_EXPORTS_W float fastAtan2(float y, float x); /** proxy for hal::LU */ CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); /** proxy for hal::LU */ CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); /** proxy for hal::Cholesky */ CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); /** proxy for hal::Cholesky */ CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); ////////////////// forward declarations for important OpenCV types ////////////////// //! @cond IGNORED template class Vec; template class Matx; template class Complex; template class Point_; template class Point3_; template class Size_; template class Rect_; template class Scalar_; class CV_EXPORTS RotatedRect; class CV_EXPORTS Range; class CV_EXPORTS TermCriteria; class CV_EXPORTS KeyPoint; class CV_EXPORTS DMatch; class CV_EXPORTS RNG; class CV_EXPORTS Mat; class CV_EXPORTS MatExpr; class CV_EXPORTS UMat; class CV_EXPORTS SparseMat; typedef Mat MatND; template class Mat_; template class SparseMat_; class CV_EXPORTS MatConstIterator; class CV_EXPORTS SparseMatIterator; class CV_EXPORTS SparseMatConstIterator; template class MatIterator_; template class MatConstIterator_; template class SparseMatIterator_; template class SparseMatConstIterator_; namespace ogl { class CV_EXPORTS Buffer; class CV_EXPORTS Texture2D; class CV_EXPORTS Arrays; } namespace cuda { class CV_EXPORTS GpuMat; class CV_EXPORTS HostMem; class CV_EXPORTS Stream; class CV_EXPORTS Event; } namespace cudev { template class GpuMat_; } namespace ipp { CV_EXPORTS int getIppFeatures(); CV_EXPORTS void setIppStatus(int status, const char * const funcname = NULL, const char * const filename = NULL, int line = 0); CV_EXPORTS int getIppStatus(); CV_EXPORTS String getIppErrorLocation(); CV_EXPORTS bool useIPP(); CV_EXPORTS void setUseIPP(bool flag); } // ipp //! @endcond //! @} core_utils } // cv #include "opencv2/core/neon_utils.hpp" #endif //__OPENCV_CORE_BASE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/bufferpool.hpp ================================================ // This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. #ifndef __OPENCV_CORE_BUFFER_POOL_HPP__ #define __OPENCV_CORE_BUFFER_POOL_HPP__ namespace cv { //! @addtogroup core //! @{ class BufferPoolController { protected: ~BufferPoolController() { } public: virtual size_t getReservedSize() const = 0; virtual size_t getMaxReservedSize() const = 0; virtual void setMaxReservedSize(size_t size) = 0; virtual void freeAllReservedBuffers() = 0; }; //! @} } #endif // __OPENCV_CORE_BUFFER_POOL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/core.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/core.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/core_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_C_H__ #define __OPENCV_CORE_C_H__ #include "opencv2/core/types_c.h" #ifdef __cplusplus # ifdef _MSC_VER /* disable warning C4190: 'function' has C-linkage specified, but returns UDT 'typename' which is incompatible with C It is OK to disable it because we only extend few plain structures with C++ construrtors for simpler interoperability with C++ API of the library */ # pragma warning(disable:4190) # elif defined __clang__ && __clang_major__ >= 3 # pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" # endif #endif #ifdef __cplusplus extern "C" { #endif /** @addtogroup core_c @{ */ /****************************************************************************************\ * Array allocation, deallocation, initialization and access to elements * \****************************************************************************************/ /** `malloc` wrapper. If there is no enough memory, the function (as well as other OpenCV functions that call cvAlloc) raises an error. */ CVAPI(void*) cvAlloc( size_t size ); /** `free` wrapper. Here and further all the memory releasing functions (that all call cvFree) take double pointer in order to to clear pointer to the data after releasing it. Passing pointer to NULL pointer is Ok: nothing happens in this case */ CVAPI(void) cvFree_( void* ptr ); #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) /** @brief Creates an image header but does not allocate the image data. @param size Image width and height @param depth Image depth (see cvCreateImage ) @param channels Number of channels (see cvCreateImage ) */ CVAPI(IplImage*) cvCreateImageHeader( CvSize size, int depth, int channels ); /** @brief Initializes an image header that was previously allocated. The returned IplImage\* points to the initialized header. @param image Image header to initialize @param size Image width and height @param depth Image depth (see cvCreateImage ) @param channels Number of channels (see cvCreateImage ) @param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL @param align Alignment for image rows, typically 4 or 8 bytes */ CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth, int channels, int origin CV_DEFAULT(0), int align CV_DEFAULT(4)); /** @brief Creates an image header and allocates the image data. This function call is equivalent to the following code: @code header = cvCreateImageHeader(size, depth, channels); cvCreateData(header); @endcode @param size Image width and height @param depth Bit depth of image elements. See IplImage for valid depths. @param channels Number of channels per pixel. See IplImage for details. This function only creates images with interleaved channels. */ CVAPI(IplImage*) cvCreateImage( CvSize size, int depth, int channels ); /** @brief Deallocates an image header. This call is an analogue of : @code if(image ) { iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI); *image = 0; } @endcode but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro). @param image Double pointer to the image header */ CVAPI(void) cvReleaseImageHeader( IplImage** image ); /** @brief Deallocates the image header and the image data. This call is a shortened form of : @code if(*image ) { cvReleaseData(*image); cvReleaseImageHeader(image); } @endcode @param image Double pointer to the image header */ CVAPI(void) cvReleaseImage( IplImage** image ); /** Creates a copy of IPL image (widthStep may differ) */ CVAPI(IplImage*) cvCloneImage( const IplImage* image ); /** @brief Sets the channel of interest in an IplImage. If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do *not* support the COI setting, so to process an individual image/matrix channel one may copy (via cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result back (via cvCopy or cvMerge) if needed. @param image A pointer to the image header @param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected, etc. Note that the channel indices become 1-based. */ CVAPI(void) cvSetImageCOI( IplImage* image, int coi ); /** @brief Returns the index of the channel of interest. Returns the channel of interest of in an IplImage. Returned values correspond to the coi in cvSetImageCOI. @param image A pointer to the image header */ CVAPI(int) cvGetImageCOI( const IplImage* image ); /** @brief Sets an image Region Of Interest (ROI) for a given rectangle. If the original image ROI was NULL and the rect is not the whole image, the ROI structure is allocated. Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the ROI, not the original image. @param image A pointer to the image header @param rect The ROI rectangle */ CVAPI(void) cvSetImageROI( IplImage* image, CvRect rect ); /** @brief Resets the image ROI to include the entire image and releases the ROI structure. This produces a similar result to the following, but in addition it releases the ROI structure. : @code cvSetImageROI(image, cvRect(0, 0, image->width, image->height )); cvSetImageCOI(image, 0); @endcode @param image A pointer to the image header */ CVAPI(void) cvResetImageROI( IplImage* image ); /** @brief Returns the image ROI. If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned. @param image A pointer to the image header */ CVAPI(CvRect) cvGetImageROI( const IplImage* image ); /** @brief Creates a matrix header but does not allocate the matrix data. The function allocates a new matrix header and returns a pointer to it. The matrix data can then be allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. @param rows Number of rows in the matrix @param cols Number of columns in the matrix @param type Type of the matrix elements, see cvCreateMat */ CVAPI(CvMat*) cvCreateMatHeader( int rows, int cols, int type ); #define CV_AUTOSTEP 0x7fffffff /** @brief Initializes a pre-allocated matrix header. This function is often used to process raw data with OpenCV matrix functions. For example, the following code computes the matrix product of two matrices, stored as ordinary arrays: @code double a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; double b[] = { 1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12 }; double c[9]; CvMat Ma, Mb, Mc ; cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a); cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b); cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c); cvMatMulAdd(&Ma, &Mb, 0, &Mc); // the c array now contains the product of a (3x4) and b (4x3) @endcode @param mat A pointer to the matrix header to be initialized @param rows Number of rows in the matrix @param cols Number of columns in the matrix @param type Type of the matrix elements, see cvCreateMat . @param data Optional: data pointer assigned to the matrix header @param step Optional: full row width in bytes of the assigned data. By default, the minimal possible step is used which assumes there are no gaps between subsequent rows of the matrix. */ CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, int type, void* data CV_DEFAULT(NULL), int step CV_DEFAULT(CV_AUTOSTEP) ); /** @brief Creates a matrix header and allocates the matrix data. The function call is equivalent to the following code: @code CvMat* mat = cvCreateMatHeader(rows, cols, type); cvCreateData(mat); @endcode @param rows Number of rows in the matrix @param cols Number of columns in the matrix @param type The type of the matrix elements in the form CV_\\C\ , where S=signed, U=unsigned, F=float. For example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ 32SC2 means the elements are 32-bit signed and there are 2 channels. */ CVAPI(CvMat*) cvCreateMat( int rows, int cols, int type ); /** @brief Deallocates a matrix. The function decrements the matrix data reference counter and deallocates matrix header. If the data reference counter is 0, it also deallocates the data. : @code if(*mat ) cvDecRefData(*mat); cvFree((void**)mat); @endcode @param mat Double pointer to the matrix */ CVAPI(void) cvReleaseMat( CvMat** mat ); /** @brief Decrements an array data reference counter. The function decrements the data reference counter in a CvMat or CvMatND if the reference counter pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current implementation the reference counter is not NULL only if the data was allocated using the cvCreateData function. The counter will be NULL in other cases such as: external data was assigned to the header using cvSetData, header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header. @param arr Pointer to an array header */ CV_INLINE void cvDecRefData( CvArr* arr ) { if( CV_IS_MAT( arr )) { CvMat* mat = (CvMat*)arr; mat->data.ptr = NULL; if( mat->refcount != NULL && --*mat->refcount == 0 ) cvFree( &mat->refcount ); mat->refcount = NULL; } else if( CV_IS_MATND( arr )) { CvMatND* mat = (CvMatND*)arr; mat->data.ptr = NULL; if( mat->refcount != NULL && --*mat->refcount == 0 ) cvFree( &mat->refcount ); mat->refcount = NULL; } } /** @brief Increments array data reference counter. The function increments CvMat or CvMatND data reference counter and returns the new counter value if the reference counter pointer is not NULL, otherwise it returns zero. @param arr Array header */ CV_INLINE int cvIncRefData( CvArr* arr ) { int refcount = 0; if( CV_IS_MAT( arr )) { CvMat* mat = (CvMat*)arr; if( mat->refcount != NULL ) refcount = ++*mat->refcount; } else if( CV_IS_MATND( arr )) { CvMatND* mat = (CvMatND*)arr; if( mat->refcount != NULL ) refcount = ++*mat->refcount; } return refcount; } /** Creates an exact copy of the input matrix (except, may be, step value) */ CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); /** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix. The function returns header, corresponding to a specified rectangle of the input array. In other words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is taken into account by the function so the sub-array of ROI is actually extracted. @param arr Input array @param submat Pointer to the resultant sub-array header @param rect Zero-based coordinates of the rectangle of interest */ CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ); #define cvGetSubArr cvGetSubRect /** @brief Returns array row or row span. The functions return the header, corresponding to a specified row/row span of the input array. cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1). @param arr Input array @param submat Pointer to the resulting sub-array header @param start_row Zero-based index of the starting row (inclusive) of the span @param end_row Zero-based index of the ending row (exclusive) of the span @param delta_row Index step in the row span. That is, the function extracts every delta_row -th row from start_row and up to (but not including) end_row . */ CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat, int start_row, int end_row, int delta_row CV_DEFAULT(1)); /** @overload @param arr Input array @param submat Pointer to the resulting sub-array header @param row Zero-based index of the selected row */ CV_INLINE CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ) { return cvGetRows( arr, submat, row, row + 1, 1 ); } /** @brief Returns one of more array columns. The functions return the header, corresponding to a specified column span of the input array. That is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for cvGetCols(arr, submat, col, col+1). @param arr Input array @param submat Pointer to the resulting sub-array header @param start_col Zero-based index of the starting column (inclusive) of the span @param end_col Zero-based index of the ending column (exclusive) of the span */ CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col ); /** @overload @param arr Input array @param submat Pointer to the resulting sub-array header @param col Zero-based index of the selected column */ CV_INLINE CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ) { return cvGetCols( arr, submat, col, col + 1 ); } /** @brief Returns one of array diagonals. The function returns the header, corresponding to a specified diagonal of the input array. @param arr Input array @param submat Pointer to the resulting sub-array header @param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1 corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so forth. */ CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat, int diag CV_DEFAULT(0)); /** low-level scalar <-> raw data conversion functions */ CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_12 CV_DEFAULT(0) ); CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar ); /** @brief Creates a new matrix header but does not allocate the matrix data. The function allocates a header for a multi-dimensional dense array. The array data can further be allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. @param dims Number of array dimensions @param sizes Array of dimension sizes @param type Type of array elements, see cvCreateMat */ CVAPI(CvMatND*) cvCreateMatNDHeader( int dims, const int* sizes, int type ); /** @brief Creates the header and allocates the data for a multi-dimensional dense array. This function call is equivalent to the following code: @code CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type); cvCreateData(mat); @endcode @param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be changed at build time). @param sizes Array of dimension sizes. @param type Type of array elements, see cvCreateMat . */ CVAPI(CvMatND*) cvCreateMatND( int dims, const int* sizes, int type ); /** @brief Initializes a pre-allocated multi-dimensional array header. @param mat A pointer to the array header to be initialized @param dims The number of array dimensions @param sizes An array of dimension sizes @param type Type of array elements, see cvCreateMat @param data Optional data pointer assigned to the matrix header */ CVAPI(CvMatND*) cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, int type, void* data CV_DEFAULT(NULL) ); /** @brief Deallocates a multi-dimensional array. The function decrements the array data reference counter and releases the array header. If the reference counter reaches 0, it also deallocates the data. : @code if(*mat ) cvDecRefData(*mat); cvFree((void**)mat); @endcode @param mat Double pointer to the array */ CV_INLINE void cvReleaseMatND( CvMatND** mat ) { cvReleaseMat( (CvMat**)mat ); } /** Creates a copy of CvMatND (except, may be, steps) */ CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); /** @brief Creates sparse array. The function allocates a multi-dimensional sparse array. Initially the array contain no elements, that is PtrND and other related functions will return 0 for every index. @param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is practically unlimited (up to \f$2^{16}\f$ ). @param sizes Array of dimension sizes @param type Type of array elements. The same as for CvMat */ CVAPI(CvSparseMat*) cvCreateSparseMat( int dims, const int* sizes, int type ); /** @brief Deallocates sparse array. The function releases the sparse array and clears the array pointer upon exit. @param mat Double pointer to the array */ CVAPI(void) cvReleaseSparseMat( CvSparseMat** mat ); /** Creates a copy of CvSparseMat (except, may be, zero items) */ CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); /** @brief Initializes sparse array elements iterator. The function initializes iterator of sparse array elements and returns pointer to the first element, or NULL if the array is empty. @param mat Input array @param mat_iterator Initialized iterator */ CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat, CvSparseMatIterator* mat_iterator ); /** @brief Returns the next sparse matrix element The function moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in the hash table. The sample below demonstrates how to iterate through the sparse matrix: @code // print all the non-zero sparse matrix elements and compute their sum double sum = 0; int i, dims = cvGetDims(sparsemat); CvSparseMatIterator it; CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it); for(; node != 0; node = cvGetNextSparseNode(&it)) { int* idx = CV_NODE_IDX(array, node); float val = *(float*)CV_NODE_VAL(array, node); printf("M"); for(i = 0; i < dims; i++ ) printf("[%d]", idx[i]); printf("=%g\n", val); sum += val; } printf("nTotal sum = %g\n", sum); @endcode @param mat_iterator Sparse array iterator */ CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) { if( mat_iterator->node->next ) return mat_iterator->node = mat_iterator->node->next; else { int idx; for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ ) { CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx]; if( node ) { mat_iterator->curidx = idx; return mat_iterator->node = node; } } return NULL; } } #define CV_MAX_ARR 10 /** matrix iterator: used for n-ary operations on dense arrays */ typedef struct CvNArrayIterator { int count; /**< number of arrays */ int dims; /**< number of dimensions to iterate */ CvSize size; /**< maximal common linear size: { width = size, height = 1 } */ uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */ int stack[CV_MAX_DIM]; /**< for internal use */ CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the matrices that are processed */ } CvNArrayIterator; #define CV_NO_DEPTH_CHECK 1 #define CV_NO_CN_CHECK 2 #define CV_NO_SIZE_CHECK 4 /** initializes iterator that traverses through several arrays simulteneously (the function together with cvNextArraySlice is used for N-ari element-wise operations) */ CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, const CvArr* mask, CvMatND* stubs, CvNArrayIterator* array_iterator, int flags CV_DEFAULT(0) ); /** returns zero value if iteration is finished, non-zero (slice length) otherwise */ CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator ); /** @brief Returns type of array elements. The function returns type of the array elements. In the case of IplImage the type is converted to CvMat-like representation. For example, if the image has been created as: @code IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); @endcode The code cvGetElemType(img) will return CV_8UC3. @param arr Input array */ CVAPI(int) cvGetElemType( const CvArr* arr ); /** @brief Return number of array dimensions The function returns the array dimensionality and the array of dimension sizes. In the case of IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the following code calculates total number of array elements: @code int sizes[CV_MAX_DIM]; int i, total = 1; int dims = cvGetDims(arr, size); for(i = 0; i < dims; i++ ) total *= sizes[i]; @endcode @param arr Input array @param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows (height) goes first, number of columns (width) next. */ CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) ); /** @brief Returns array size along the specified dimension. @param arr Input array @param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of columns; for images 0 means height, 1 means width) */ CVAPI(int) cvGetDimSize( const CvArr* arr, int index ); /** @brief Return pointer to a particular array element. The functions return a pointer to a specific array element. Number of array dimension should match to the number of indices passed to the function except for cvPtr1D function that can be used for sequential access to 1D, 2D or nD dense arrays. The functions can be used for sparse arrays as well - if the requested node does not exist they create it and set it to zero. All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet , cvSetND , cvSetRealND ) raise an error in case if the element index is out of range. @param arr Input array @param idx0 The first zero-based component of the element index @param type Optional output parameter: type of matrix elements */ CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL)); /** @overload */ CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) ); /** @overload */ CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type CV_DEFAULT(NULL)); /** @overload @param arr Input array @param idx Array of the element indices @param type Optional output parameter: type of matrix elements @param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already. @param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example) */ CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL), int create_node CV_DEFAULT(1), unsigned* precalc_hashval CV_DEFAULT(NULL)); /** @brief Return a specific array element. The functions return a specific array element. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions). @param arr Input array @param idx0 The first zero-based component of the element index */ CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 ); /** @overload */ CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 ); /** @overload */ CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); /** @overload @param arr Input array @param idx Array of the element indices */ CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx ); /** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array. Returns a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that Get?D functions can be used safely for both single-channel and multiple-channel arrays though they are a bit slower. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions). @param arr Input array. Must have a single channel. @param idx0 The first zero-based component of the element index */ CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 ); /** @overload */ CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); /** @overload */ CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); /** @overload @param arr Input array. Must have a single channel. @param idx Array of the element indices */ CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx ); /** @brief Change the particular array element. The functions assign the new value to a particular array element. In the case of a sparse array the functions create the node if it does not exist yet. @param arr Input array @param idx0 The first zero-based component of the element index @param value The assigned value */ CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value ); /** @overload */ CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); /** @overload */ CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); /** @overload @param arr Input array @param idx Array of the element indices @param value The assigned value */ CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value ); /** @brief Change a specific array element. The functions assign a new value to a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for both single-channel and multiple-channel arrays, though they are a bit slower. In the case of a sparse array the functions create the node if it does not yet exist. @param arr Input array @param idx0 The first zero-based component of the element index @param value The assigned value */ CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value ); /** @overload */ CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); /** @overload */ CVAPI(void) cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value ); /** @overload @param arr Input array @param idx Array of the element indices @param value The assigned value */ CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value ); /** clears element of ND dense array, in case of sparse arrays it deletes the specified node */ CVAPI(void) cvClearND( CvArr* arr, const int* idx ); /** @brief Returns matrix header for arbitrary array. The function returns a matrix header for the input array that can be a matrix - CvMat, an image - IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI and returns &header. Because COI is not supported by CvMat, it is returned separately. The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same code. Input array must have non-zero data pointer, otherwise the function will report an error. @note If the input array is IplImage with planar data layout and COI set, the function returns the pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures with planar data layout, even though OpenCV does not support such images. @param arr Input array @param header Pointer to CvMat structure used as a temporary buffer @param coi Optional output parameter for storing COI @param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions). The CvMatND array must be continuous. @sa cvGetImage, cvarrToMat. */ CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header, int* coi CV_DEFAULT(NULL), int allowND CV_DEFAULT(0)); /** @brief Returns image header for arbitrary array. The function returns the image header for the input array that can be a matrix (CvMat) or image (IplImage). In the case of an image the function simply returns the input pointer. In the case of CvMat it initializes an image_header structure with the parameters of the input matrix. Note that if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using this function, we will get different headers if the ROI is set in the original image. @param arr Input array @param image_header Pointer to IplImage structure used as a temporary buffer */ CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header ); /** @brief Changes the shape of a multi-dimensional array without copying the data. The function is an advanced version of cvReshape that can work with multi-dimensional arrays as well (though it can work with ordinary images and matrices) and change the number of dimensions. Below are the two samples from the cvReshape description rewritten using cvReshapeMatND: @code IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); IplImage gray_img_hdr, *gray_img; gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0); ... int size[] = { 2, 2, 2 }; CvMatND* mat = cvCreateMatND(3, size, CV_32F); CvMat row_header, *row; row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0); @endcode In C, the header file for this function includes a convenient macro cvReshapeND that does away with the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples may be replaced as follow: @code gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0); ... row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0); @endcode @param arr Input array @param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND output headers @param header Output header to be filled @param new_cn New number of channels. new_cn = 0 means that the number of channels remains unchanged. @param new_dims New number of dimensions. new_dims = 0 means that the number of dimensions remains the same. @param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not used. */ CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, int sizeof_header, CvArr* header, int new_cn, int new_dims, int* new_sizes ); #define cvReshapeND( arr, header, new_cn, new_dims, new_sizes ) \ cvReshapeMatND( (arr), sizeof(*(header)), (header), \ (new_cn), (new_dims), (new_sizes)) /** @brief Changes shape of matrix/image without copying data. The function initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both. The following example code creates one image buffer and two image headers, the first is for a 320x240x3 image and the second is for a 960x240x1 image: @code IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); CvMat gray_mat_hdr; IplImage gray_img_hdr, *gray_img; cvReshape(color_img, &gray_mat_hdr, 1); gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr); @endcode And the next example converts a 3x3 matrix to a single 1x9 vector: @code CvMat* mat = cvCreateMat(3, 3, CV_32F); CvMat row_header, *row; row = cvReshape(mat, &row_header, 0, 1); @endcode @param arr Input array @param header Output header to be filled @param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains unchanged. @param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains unchanged unless it needs to be changed according to new_cn value. */ CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header, int new_cn, int new_rows CV_DEFAULT(0) ); /** Repeats source 2d array several times in both horizontal and vertical direction to fill destination array */ CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst ); /** @brief Allocates array data The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used to allocate the data. @param arr Array header */ CVAPI(void) cvCreateData( CvArr* arr ); /** @brief Releases array data. The function releases the array data. In the case of CvMat or CvMatND it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to cvCreateData . @param arr Array header */ CVAPI(void) cvReleaseData( CvArr* arr ); /** @brief Assigns user data to the array header. The function assigns user data to the array header. Header should be initialized before using cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader, cvInitImageHeader or cvInitMatNDHeader. @param arr Array header @param data User data @param step Full row length in bytes */ CVAPI(void) cvSetData( CvArr* arr, void* data, int step ); /** @brief Retrieves low-level information about the array. The function fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with ROI set, the parameters of ROI are returned. The following example shows how to get access to array elements. It computes absolute values of the array elements : @code float* data; int step; CvSize size; cvGetRawData(array, (uchar**)&data, &step, &size); step /= sizeof(data[0]); for(int y = 0; y < size.height; y++, data += step ) for(int x = 0; x < size.width; x++ ) data[x] = (float)fabs(data[x]); @endcode @param arr Array header @param data Output pointer to the whole image origin or ROI origin if ROI is set @param step Output full row length in bytes @param roi_size Output ROI size */ CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data, int* step CV_DEFAULT(NULL), CvSize* roi_size CV_DEFAULT(NULL)); /** @brief Returns size of matrix or image ROI. The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In the case of image the size of ROI is returned. @param arr array header */ CVAPI(CvSize) cvGetSize( const CvArr* arr ); /** @brief Copies one array to another. The function copies selected elements from an input array to an output array: \f[\texttt{dst} (I)= \texttt{src} (I) \quad \text{if} \quad \texttt{mask} (I) \ne 0.\f] If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays must have the same type, the same number of dimensions, and the same size. The function can also copy sparse arrays (mask is not supported in this case). @param src The source array @param dst The destination array @param mask Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed */ CVAPI(void) cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL) ); /** @brief Sets every element of an array to a given value. The function copies the scalar value to every selected element of the destination array: \f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I) \ne 0\f] If array arr is of IplImage type, then is ROI used, but COI must not be set. @param arr The destination array @param value Fill value @param mask Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed */ CVAPI(void) cvSet( CvArr* arr, CvScalar value, const CvArr* mask CV_DEFAULT(NULL) ); /** @brief Clears the array. The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the elements are removed. @param arr Array to be cleared */ CVAPI(void) cvSetZero( CvArr* arr ); #define cvZero cvSetZero /** Splits a multi-channel array into the set of single-channel arrays or extracts particular [color] plane */ CVAPI(void) cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, CvArr* dst2, CvArr* dst3 ); /** Merges a set of single-channel arrays into the single multi-channel array or inserts one particular [color] plane to the array */ CVAPI(void) cvMerge( const CvArr* src0, const CvArr* src1, const CvArr* src2, const CvArr* src3, CvArr* dst ); /** Copies several channels from input arrays to certain channels of output arrays */ CVAPI(void) cvMixChannels( const CvArr** src, int src_count, CvArr** dst, int dst_count, const int* from_to, int pair_count ); /** @brief Converts one array to another with optional linear transformation. The function has several different purposes, and thus has several different names. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after: \f[\texttt{dst} (I) = \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f] All the channels of multi-channel arrays are processed independently. The type of conversion is done with rounding and saturation, that is if the result of scaling + conversion can not be represented exactly by a value of the destination array element type, it is set to the nearest representable value on the real axis. @param src Source array @param dst Destination array @param scale Scale factor @param shift Value added to the scaled source array elements */ CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, double scale CV_DEFAULT(1), double shift CV_DEFAULT(0) ); #define cvCvtScale cvConvertScale #define cvScale cvConvertScale #define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) /** Performs linear transformation on every source array element, stores absolute value of the result: dst(x,y,c) = abs(scale*src(x,y,c)+shift). destination array must have 8u type. In other cases one may use cvConvertScale + cvAbsDiffS */ CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale CV_DEFAULT(1), double shift CV_DEFAULT(0) ); #define cvCvtScaleAbs cvConvertScaleAbs /** checks termination criteria validity and sets eps to default_eps (if it is not set), max_iter to default_max_iters (if it is not set) */ CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, double default_eps, int default_max_iters ); /****************************************************************************************\ * Arithmetic, logic and comparison operations * \****************************************************************************************/ /** dst(mask) = src1(mask) + src2(mask) */ CVAPI(void) cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(mask) = src(mask) + value */ CVAPI(void) cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(mask) = src1(mask) - src2(mask) */ CVAPI(void) cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(mask) = src(mask) - value = src(mask) + (-value) */ CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)) { cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]), dst, mask ); } /** dst(mask) = value - src(mask) */ CVAPI(void) cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src1(idx) * src2(idx) * scale (scaled element-wise multiplication of 2 arrays) */ CVAPI(void) cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale CV_DEFAULT(1) ); /** element-wise division/inversion with scaling: dst(idx) = src1(idx) * scale / src2(idx) or dst(idx) = scale / src2(idx) if src1 == 0 */ CVAPI(void) cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale CV_DEFAULT(1)); /** dst = src1 * scale + src2 */ CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst ); #define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C) /** dst = src1 * alpha + src2 * beta + gamma */ CVAPI(void) cvAddWeighted( const CvArr* src1, double alpha, const CvArr* src2, double beta, double gamma, CvArr* dst ); /** @brief Calculates the dot product of two arrays in Euclidean metrics. The function calculates and returns the Euclidean dot product of two arrays. \f[src1 \bullet src2 = \sum _I ( \texttt{src1} (I) \texttt{src2} (I))\f] In the case of multiple channel arrays, the results for all channels are accumulated. In particular, cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can process multi-dimensional arrays, row by row, layer by layer, and so on. @param src1 The first source array @param src2 The second source array */ CVAPI(double) cvDotProduct( const CvArr* src1, const CvArr* src2 ); /** dst(idx) = src1(idx) & src2(idx) */ CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src(idx) & value */ CVAPI(void) cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src1(idx) | src2(idx) */ CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src(idx) | value */ CVAPI(void) cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src1(idx) ^ src2(idx) */ CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src(idx) ^ value */ CVAPI(void) cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = ~src(idx) */ CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); /** dst(idx) = lower(idx) <= src(idx) < upper(idx) */ CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst ); /** dst(idx) = lower <= src(idx) < upper */ CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst ); #define CV_CMP_EQ 0 #define CV_CMP_GT 1 #define CV_CMP_GE 2 #define CV_CMP_LT 3 #define CV_CMP_LE 4 #define CV_CMP_NE 5 /** The comparison operation support single-channel arrays only. Destination image should be 8uC1 or 8sC1 */ /** dst(idx) = src1(idx) _cmp_op_ src2(idx) */ CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); /** dst(idx) = src1(idx) _cmp_op_ value */ CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); /** dst(idx) = min(src1(idx),src2(idx)) */ CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** dst(idx) = max(src1(idx),src2(idx)) */ CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** dst(idx) = min(src(idx),value) */ CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst ); /** dst(idx) = max(src(idx),value) */ CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst ); /** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** dst(x,y,c) = abs(src(x,y,c) - value(c)) */ CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); #define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0)) /****************************************************************************************\ * Math operations * \****************************************************************************************/ /** Does cartesian->polar coordinates conversion. Either of output components (magnitude or angle) is optional */ CVAPI(void) cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL), int angle_in_degrees CV_DEFAULT(0)); /** Does polar->cartesian coordinates conversion. Either of output components (magnitude or angle) is optional. If magnitude is missing it is assumed to be all 1's */ CVAPI(void) cvPolarToCart( const CvArr* magnitude, const CvArr* angle, CvArr* x, CvArr* y, int angle_in_degrees CV_DEFAULT(0)); /** Does powering: dst(idx) = src(idx)^power */ CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); /** Does exponention: dst(idx) = exp(src(idx)). Overflow is not handled yet. Underflow is handled. Maximal relative error is ~7e-6 for single-precision input */ CVAPI(void) cvExp( const CvArr* src, CvArr* dst ); /** Calculates natural logarithms: dst(idx) = log(abs(src(idx))). Logarithm of 0 gives large negative number(~-700) Maximal relative error is ~3e-7 for single-precision output */ CVAPI(void) cvLog( const CvArr* src, CvArr* dst ); /** Fast arctangent calculation */ CVAPI(float) cvFastArctan( float y, float x ); /** Fast cubic root calculation */ CVAPI(float) cvCbrt( float value ); #define CV_CHECK_RANGE 1 #define CV_CHECK_QUIET 2 /** Checks array values for NaNs, Infs or simply for too large numbers (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set, no runtime errors is raised (function returns zero value in case of "bad" values). Otherwise cvError is called */ CVAPI(int) cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0), double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0)); #define cvCheckArray cvCheckArr #define CV_RAND_UNI 0 #define CV_RAND_NORMAL 1 /** @brief Fills an array with random numbers and updates the RNG state. The function fills the destination array with uniformly or normally distributed random numbers. @param rng CvRNG state initialized by cvRNG @param arr The destination array @param dist_type Distribution type > - **CV_RAND_UNI** uniform distribution > - **CV_RAND_NORMAL** normal or Gaussian distribution @param param1 The first parameter of the distribution. In the case of a uniform distribution it is the inclusive lower boundary of the random numbers range. In the case of a normal distribution it is the mean value of the random numbers. @param param2 The second parameter of the distribution. In the case of a uniform distribution it is the exclusive upper boundary of the random numbers range. In the case of a normal distribution it is the standard deviation of the random numbers. @sa randu, randn, RNG::fill. */ CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, CvScalar param1, CvScalar param2 ); CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng, double iter_factor CV_DEFAULT(1.)); #define CV_SORT_EVERY_ROW 0 #define CV_SORT_EVERY_COLUMN 1 #define CV_SORT_ASCENDING 0 #define CV_SORT_DESCENDING 16 CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), CvArr* idxmat CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); /** Finds real roots of a cubic equation */ CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); /** Finds all real and complex roots of a polynomial equation */ CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); /****************************************************************************************\ * Matrix operations * \****************************************************************************************/ /** @brief Calculates the cross product of two 3D vectors. The function calculates the cross product of two 3D vectors: \f[\texttt{dst} = \texttt{src1} \times \texttt{src2}\f] or: \f[\begin{array}{l} \texttt{dst} _1 = \texttt{src1} _2 \texttt{src2} _3 - \texttt{src1} _3 \texttt{src2} _2 \\ \texttt{dst} _2 = \texttt{src1} _3 \texttt{src2} _1 - \texttt{src1} _1 \texttt{src2} _3 \\ \texttt{dst} _3 = \texttt{src1} _1 \texttt{src2} _2 - \texttt{src1} _2 \texttt{src2} _1 \end{array}\f] @param src1 The first source vector @param src2 The second source vector @param dst The destination vector */ CVAPI(void) cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** Matrix transform: dst = A*B + C, C is optional */ #define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 ) #define cvMatMul( src1, src2, dst ) cvMatMulAdd( (src1), (src2), NULL, (dst)) #define CV_GEMM_A_T 1 #define CV_GEMM_B_T 2 #define CV_GEMM_C_T 4 /** Extended matrix transform: dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */ CVAPI(void) cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, const CvArr* src3, double beta, CvArr* dst, int tABC CV_DEFAULT(0)); #define cvMatMulAddEx cvGEMM /** Transforms each element of source array and stores resultant vectors in destination array */ CVAPI(void) cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec CV_DEFAULT(NULL)); #define cvMatMulAddS cvTransform /** Does perspective transform on every element of input array */ CVAPI(void) cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat ); /** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */ CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta CV_DEFAULT(NULL), double scale CV_DEFAULT(1.) ); /** Tranposes matrix. Square matrices can be transposed in-place */ CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst ); #define cvT cvTranspose /** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */ CVAPI(void) cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) ); /** Mirror array data around horizontal (flip=0), vertical (flip=1) or both(flip=-1) axises: cvFlip(src) flips images vertically and sequences horizontally (inplace) */ CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), int flip_mode CV_DEFAULT(0)); #define cvMirror cvFlip #define CV_SVD_MODIFY_A 1 #define CV_SVD_U_T 2 #define CV_SVD_V_T 4 /** Performs Singular Value Decomposition of a matrix */ CVAPI(void) cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL), CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); /** Performs Singular Value Back Substitution (solves A*X = B): flags must be the same as in cvSVD */ CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, const CvArr* V, const CvArr* B, CvArr* X, int flags ); #define CV_LU 0 #define CV_SVD 1 #define CV_SVD_SYM 2 #define CV_CHOLESKY 3 #define CV_QR 4 #define CV_NORMAL 16 /** Inverts matrix */ CVAPI(double) cvInvert( const CvArr* src, CvArr* dst, int method CV_DEFAULT(CV_LU)); #define cvInv cvInvert /** Solves linear system (src1)*(dst) = (src2) (returns 0 if src1 is a singular and CV_LU method is used) */ CVAPI(int) cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, int method CV_DEFAULT(CV_LU)); /** Calculates determinant of input matrix */ CVAPI(double) cvDet( const CvArr* mat ); /** Calculates trace of the matrix (sum of elements on the main diagonal) */ CVAPI(CvScalar) cvTrace( const CvArr* mat ); /** Finds eigen values and vectors of a symmetric matrix */ CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, double eps CV_DEFAULT(0), int lowindex CV_DEFAULT(-1), int highindex CV_DEFAULT(-1)); ///* Finds selected eigen values and vectors of a symmetric matrix */ //CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, // int lowindex, int highindex ); /** Makes an identity matrix (mat_ij = i == j) */ CVAPI(void) cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) ); /** Fills matrix with given range of numbers */ CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); /** @anchor core_c_CovarFlags @name Flags for cvCalcCovarMatrix @see cvCalcCovarMatrix @{ */ /** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ #define CV_COVAR_SCRAMBLED 0 /** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ #define CV_COVAR_NORMAL 1 /** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead (useful for calculating covariance matrix by parts) */ #define CV_COVAR_USE_AVG 2 /** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ #define CV_COVAR_SCALE 4 /** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ #define CV_COVAR_ROWS 8 /** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */ #define CV_COVAR_COLS 16 /** @} */ /** Calculates covariation matrix for a set of vectors @see @ref core_c_CovarFlags "flags" */ CVAPI(void) cvCalcCovarMatrix( const CvArr** vects, int count, CvArr* cov_mat, CvArr* avg, int flags ); #define CV_PCA_DATA_AS_ROW 0 #define CV_PCA_DATA_AS_COL 1 #define CV_PCA_USE_AVG 2 CVAPI(void) cvCalcPCA( const CvArr* data, CvArr* mean, CvArr* eigenvals, CvArr* eigenvects, int flags ); CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, const CvArr* eigenvects, CvArr* result ); CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, const CvArr* eigenvects, CvArr* result ); /** Calculates Mahalanobis(weighted) distance */ CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); #define cvMahalonobis cvMahalanobis /****************************************************************************************\ * Array Statistics * \****************************************************************************************/ /** Finds sum of array elements */ CVAPI(CvScalar) cvSum( const CvArr* arr ); /** Calculates number of non-zero pixels */ CVAPI(int) cvCountNonZero( const CvArr* arr ); /** Calculates mean value of array elements */ CVAPI(CvScalar) cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) ); /** Calculates mean and standard deviation of pixel values */ CVAPI(void) cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, const CvArr* mask CV_DEFAULT(NULL) ); /** Finds global minimum, maximum and their positions */ CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, CvPoint* min_loc CV_DEFAULT(NULL), CvPoint* max_loc CV_DEFAULT(NULL), const CvArr* mask CV_DEFAULT(NULL) ); /** @anchor core_c_NormFlags @name Flags for cvNorm and cvNormalize @{ */ #define CV_C 1 #define CV_L1 2 #define CV_L2 4 #define CV_NORM_MASK 7 #define CV_RELATIVE 8 #define CV_DIFF 16 #define CV_MINMAX 32 #define CV_DIFF_C (CV_DIFF | CV_C) #define CV_DIFF_L1 (CV_DIFF | CV_L1) #define CV_DIFF_L2 (CV_DIFF | CV_L2) #define CV_RELATIVE_C (CV_RELATIVE | CV_C) #define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1) #define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2) /** @} */ /** Finds norm, difference norm or relative difference norm for an array (or two arrays) @see ref core_c_NormFlags "flags" */ CVAPI(double) cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL), int norm_type CV_DEFAULT(CV_L2), const CvArr* mask CV_DEFAULT(NULL) ); /** @see ref core_c_NormFlags "flags" */ CVAPI(void) cvNormalize( const CvArr* src, CvArr* dst, double a CV_DEFAULT(1.), double b CV_DEFAULT(0.), int norm_type CV_DEFAULT(CV_L2), const CvArr* mask CV_DEFAULT(NULL) ); /** @anchor core_c_ReduceFlags @name Flags for cvReduce @{ */ #define CV_REDUCE_SUM 0 #define CV_REDUCE_AVG 1 #define CV_REDUCE_MAX 2 #define CV_REDUCE_MIN 3 /** @} */ /** @see @ref core_c_ReduceFlags "flags" */ CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), int op CV_DEFAULT(CV_REDUCE_SUM) ); /****************************************************************************************\ * Discrete Linear Transforms and Related Functions * \****************************************************************************************/ /** @anchor core_c_DftFlags @name Flags for cvDFT, cvDCT and cvMulSpectrums @{ */ #define CV_DXT_FORWARD 0 #define CV_DXT_INVERSE 1 #define CV_DXT_SCALE 2 /**< divide result by size of array */ #define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE) #define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE #define CV_DXT_ROWS 4 /**< transform each row individually */ #define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ /** @} */ /** Discrete Fourier Transform: complex->complex, real->ccs (forward), ccs->real (inverse) @see core_c_DftFlags "flags" */ CVAPI(void) cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero_rows CV_DEFAULT(0) ); #define cvFFT cvDFT /** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) @see core_c_DftFlags "flags" */ CVAPI(void) cvMulSpectrums( const CvArr* src1, const CvArr* src2, CvArr* dst, int flags ); /** Finds optimal DFT vector size >= size0 */ CVAPI(int) cvGetOptimalDFTSize( int size0 ); /** Discrete Cosine Transform @see core_c_DftFlags "flags" */ CVAPI(void) cvDCT( const CvArr* src, CvArr* dst, int flags ); /****************************************************************************************\ * Dynamic data structures * \****************************************************************************************/ /** Calculates length of sequence slice (with support of negative indices). */ CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); /** Creates new memory storage. block_size == 0 means that default, somewhat optimal size, is used (currently, it is 64K) */ CVAPI(CvMemStorage*) cvCreateMemStorage( int block_size CV_DEFAULT(0)); /** Creates a memory storage that will borrow memory blocks from parent storage */ CVAPI(CvMemStorage*) cvCreateChildMemStorage( CvMemStorage* parent ); /** Releases memory storage. All the children of a parent must be released before the parent. A child storage returns all the blocks to parent when it is released */ CVAPI(void) cvReleaseMemStorage( CvMemStorage** storage ); /** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... do not free any memory. A child storage returns all the blocks to the parent when it is cleared */ CVAPI(void) cvClearMemStorage( CvMemStorage* storage ); /** Remember a storage "free memory" position */ CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); /** Restore a storage "free memory" position */ CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); /** Allocates continuous buffer of the specified size in the storage */ CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); /** Allocates string in memory storage */ CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, int len CV_DEFAULT(-1) ); /** Creates new empty sequence that will reside in the specified storage */ CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, size_t elem_size, CvMemStorage* storage ); /** Changes default size (granularity) of sequence blocks. The default size is ~1Kbyte */ CVAPI(void) cvSetSeqBlockSize( CvSeq* seq, int delta_elems ); /** Adds new element to the end of sequence. Returns pointer to the element */ CVAPI(schar*) cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL)); /** Adds new element to the beginning of sequence. Returns pointer to it */ CVAPI(schar*) cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL)); /** Removes the last element from sequence and optionally saves it */ CVAPI(void) cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL)); /** Removes the first element from sequence and optioanally saves it */ CVAPI(void) cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL)); #define CV_FRONT 1 #define CV_BACK 0 /** Adds several new elements to the end of sequence */ CVAPI(void) cvSeqPushMulti( CvSeq* seq, const void* elements, int count, int in_front CV_DEFAULT(0) ); /** Removes several elements from the end of sequence and optionally saves them */ CVAPI(void) cvSeqPopMulti( CvSeq* seq, void* elements, int count, int in_front CV_DEFAULT(0) ); /** Inserts a new element in the middle of sequence. cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */ CVAPI(schar*) cvSeqInsert( CvSeq* seq, int before_index, const void* element CV_DEFAULT(NULL)); /** Removes specified sequence element */ CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); /** Removes all the elements from the sequence. The freed memory can be reused later only by the same sequence unless cvClearMemStorage or cvRestoreMemStoragePos is called */ CVAPI(void) cvClearSeq( CvSeq* seq ); /** Retrieves pointer to specified sequence element. Negative indices are supported and mean counting from the end (e.g -1 means the last sequence element) */ CVAPI(schar*) cvGetSeqElem( const CvSeq* seq, int index ); /** Calculates index of the specified sequence element. Returns -1 if element does not belong to the sequence */ CVAPI(int) cvSeqElemIdx( const CvSeq* seq, const void* element, CvSeqBlock** block CV_DEFAULT(NULL) ); /** Initializes sequence writer. The new elements will be added to the end of sequence */ CVAPI(void) cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer ); /** Combination of cvCreateSeq and cvStartAppendToSeq */ CVAPI(void) cvStartWriteSeq( int seq_flags, int header_size, int elem_size, CvMemStorage* storage, CvSeqWriter* writer ); /** Closes sequence writer, updates sequence header and returns pointer to the resultant sequence (which may be useful if the sequence was created using cvStartWriteSeq)) */ CVAPI(CvSeq*) cvEndWriteSeq( CvSeqWriter* writer ); /** Updates sequence header. May be useful to get access to some of previously written elements via cvGetSeqElem or sequence reader */ CVAPI(void) cvFlushSeqWriter( CvSeqWriter* writer ); /** Initializes sequence reader. The sequence can be read in forward or backward direction */ CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, int reverse CV_DEFAULT(0) ); /** Returns current sequence reader position (currently observed sequence element) */ CVAPI(int) cvGetSeqReaderPos( CvSeqReader* reader ); /** Changes sequence reader position. It may seek to an absolute or to relative to the current position */ CVAPI(void) cvSetSeqReaderPos( CvSeqReader* reader, int index, int is_relative CV_DEFAULT(0)); /** Copies sequence content to a continuous piece of memory */ CVAPI(void*) cvCvtSeqToArray( const CvSeq* seq, void* elements, CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) ); /** Creates sequence header for array. After that all the operations on sequences that do not alter the content can be applied to the resultant sequence */ CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size, int elem_size, void* elements, int total, CvSeq* seq, CvSeqBlock* block ); /** Extracts sequence slice (with or without copying sequence elements) */ CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice, CvMemStorage* storage CV_DEFAULT(NULL), int copy_data CV_DEFAULT(0)); CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL)) { return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); } /** Removes sequence slice */ CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); /** Inserts a sequence or array into another sequence */ CVAPI(void) cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); /** a < b ? -1 : a > b ? 1 : 0 */ typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata ); /** Sorts sequence in-place given element comparison function */ CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) ); /** Finds element in a [sorted] sequence */ CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, int is_sorted, int* elem_idx, void* userdata CV_DEFAULT(NULL) ); /** Reverses order of sequence elements in-place */ CVAPI(void) cvSeqInvert( CvSeq* seq ); /** Splits sequence into one or more equivalence classes using the specified criteria */ CVAPI(int) cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, CvSeq** labels, CvCmpFunc is_equal, void* userdata ); /************ Internal sequence functions ************/ CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); /** Creates a new set */ CVAPI(CvSet*) cvCreateSet( int set_flags, int header_size, int elem_size, CvMemStorage* storage ); /** Adds new element to the set and returns pointer to it */ CVAPI(int) cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL), CvSetElem** inserted_elem CV_DEFAULT(NULL) ); /** Fast variant of cvSetAdd */ CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) { CvSetElem* elem = set_header->free_elems; if( elem ) { set_header->free_elems = elem->next_free; elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK; set_header->active_count++; } else cvSetAdd( set_header, NULL, &elem ); return elem; } /** Removes set element given its pointer */ CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) { CvSetElem* _elem = (CvSetElem*)elem; assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ ); _elem->next_free = set_header->free_elems; _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG; set_header->free_elems = _elem; set_header->active_count--; } /** Removes element from the set by its index */ CVAPI(void) cvSetRemove( CvSet* set_header, int index ); /** Returns a set element by index. If the element doesn't belong to the set, NULL is returned */ CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) { CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx ); return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; } /** Removes all the elements from the set */ CVAPI(void) cvClearSet( CvSet* set_header ); /** Creates new graph */ CVAPI(CvGraph*) cvCreateGraph( int graph_flags, int header_size, int vtx_size, int edge_size, CvMemStorage* storage ); /** Adds new vertex to the graph */ CVAPI(int) cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL), CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) ); /** Removes vertex from the graph together with all incident edges */ CVAPI(int) cvGraphRemoveVtx( CvGraph* graph, int index ); CVAPI(int) cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ); /** Link two vertices specifed by indices or pointers if they are not connected or return pointer to already existing edge connecting the vertices. Functions return 1 if a new edge was created, 0 otherwise */ CVAPI(int) cvGraphAddEdge( CvGraph* graph, int start_idx, int end_idx, const CvGraphEdge* edge CV_DEFAULT(NULL), CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, const CvGraphEdge* edge CV_DEFAULT(NULL), CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); /** Remove edge connecting two vertices */ CVAPI(void) cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ); CVAPI(void) cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx ); /** Find edge connecting two vertices */ CVAPI(CvGraphEdge*) cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ); CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, const CvGraphVtx* start_vtx, const CvGraphVtx* end_vtx ); #define cvGraphFindEdge cvFindGraphEdge #define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr /** Remove all vertices and edges from the graph */ CVAPI(void) cvClearGraph( CvGraph* graph ); /** Count number of edges incident to the vertex */ CVAPI(int) cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ); CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ); /** Retrieves graph vertex by given index */ #define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) /** Retrieves index of a graph vertex given its pointer */ #define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK) /** Retrieves index of a graph edge given its pointer */ #define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK) #define cvGraphGetVtxCount( graph ) ((graph)->active_count) #define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count) #define CV_GRAPH_VERTEX 1 #define CV_GRAPH_TREE_EDGE 2 #define CV_GRAPH_BACK_EDGE 4 #define CV_GRAPH_FORWARD_EDGE 8 #define CV_GRAPH_CROSS_EDGE 16 #define CV_GRAPH_ANY_EDGE 30 #define CV_GRAPH_NEW_TREE 32 #define CV_GRAPH_BACKTRACKING 64 #define CV_GRAPH_OVER -1 #define CV_GRAPH_ALL_ITEMS -1 /** flags for graph vertices and edges */ #define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30) #define CV_IS_GRAPH_VERTEX_VISITED(vtx) \ (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG) #define CV_IS_GRAPH_EDGE_VISITED(edge) \ (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG) #define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29) #define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28) typedef struct CvGraphScanner { CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */ CvGraphVtx* dst; /* current graph edge destination vertex */ CvGraphEdge* edge; /* current edge */ CvGraph* graph; /* the graph */ CvSeq* stack; /* the graph vertex stack */ int index; /* the lower bound of certainly visited vertices */ int mask; /* event mask */ } CvGraphScanner; /** Creates new graph scanner. */ CVAPI(CvGraphScanner*) cvCreateGraphScanner( CvGraph* graph, CvGraphVtx* vtx CV_DEFAULT(NULL), int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS)); /** Releases graph scanner. */ CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); /** Get next graph element */ CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); /** Creates a copy of graph */ CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); /** Does look-up transformation. Elements of the source array (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */ CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut ); /******************* Iteration through the sequence tree *****************/ typedef struct CvTreeNodeIterator { const void* node; int level; int max_level; } CvTreeNodeIterator; CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, const void* first, int max_level ); CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); /** Inserts sequence into tree with specified "parent" sequence. If parent is equal to frame (e.g. the most external contour), then added contour will have null pointer to parent. */ CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame ); /** Removes contour from tree (together with the contour children). */ CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame ); /** Gathers pointers to all the sequences, accessible from the `first`, to the single sequence */ CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size, CvMemStorage* storage ); /** The function implements the K-means algorithm for clustering an array of sample vectors in a specified number of classes */ #define CV_KMEANS_USE_INITIAL_LABELS 1 CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, CvTermCriteria termcrit, int attempts CV_DEFAULT(1), CvRNG* rng CV_DEFAULT(0), int flags CV_DEFAULT(0), CvArr* _centers CV_DEFAULT(0), double* compactness CV_DEFAULT(0) ); /****************************************************************************************\ * System functions * \****************************************************************************************/ /** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ CVAPI(int) cvUseOptimized( int on_off ); typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) (int,int,int,char*,char*,int,int,int,int,int, IplROI*,IplImage*,void*,IplTileInfo*); typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int); typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int); typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int); typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*); /** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures. Normally, the function is not called directly. Instead, a simple macro CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers to IPL allocation functions. : @code ... CV_TURN_ON_IPL_COMPATIBILITY() ... @endcode @param create_header pointer to a function, creating IPL image header. @param allocate_data pointer to a function, allocating IPL image data. @param deallocate pointer to a function, deallocating IPL image. @param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest). @param clone_image pointer to a function, cloning an IPL image. */ CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, Cv_iplAllocateImageData allocate_data, Cv_iplDeallocate deallocate, Cv_iplCreateROI create_roi, Cv_iplCloneImage clone_image ); #define CV_TURN_ON_IPL_COMPATIBILITY() \ cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \ iplDeallocate, iplCreateROI, iplCloneImage ) /****************************************************************************************\ * Data Persistence * \****************************************************************************************/ /********************************** High-level functions ********************************/ /** @brief Opens file storage for reading or writing data. The function opens file storage for reading or writing data. In the latter case, a new file is created or an existing file is rewritten. The type of the read or written file is determined by the filename extension: .xml for XML and .yml or .yaml for YAML. The function returns a pointer to the CvFileStorage structure. If the file cannot be opened then the function returns NULL. @param filename Name of the file associated with the storage @param memstorage Memory storage used for temporary data and for : storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory storage is created and used. @param flags Can be one of the following: > - **CV_STORAGE_READ** the storage is open for reading > - **CV_STORAGE_WRITE** the storage is open for writing @param encoding */ CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags, const char* encoding CV_DEFAULT(NULL) ); /** @brief Releases file storage. The function closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished. @param fs Double pointer to the released file storage */ CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs ); /** returns attribute value or 0 (NULL) if there is no such attribute */ CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name ); /** @brief Starts writing a new structure. The function starts writing a compound structure (collection) that can be a sequence or a map. After all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should be called. The function can be used to group some objects or to implement the write function for a some user object (see CvTypeInfo). @param fs File storage @param name Name of the written structure. The structure can be accessed by this name when the storage is read. @param struct_flags A combination one of the following values: - **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ), that is, its elements do not have a name. - **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that is, all its elements have names. One and only one of the two above flags must be specified - **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars. @param type_name Optional parameter - the object type name. In case of XML it is written as a type_id attribute of the structure opening tag. In the case of YAML it is written after a colon following the structure name (see the example in CvFileStorage description). Mainly it is used with user objects. When the storage is read, the encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ). @param attributes This parameter is not used in the current implementation */ CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* type_name CV_DEFAULT(NULL), CvAttrList attributes CV_DEFAULT(cvAttrList())); /** @brief Finishes writing to a file node collection. @param fs File storage @sa cvStartWriteStruct. */ CVAPI(void) cvEndWriteStruct( CvFileStorage* fs ); /** @brief Writes an integer value. The function writes a single integer value (with or without a name) to the file storage. @param fs File storage @param name Name of the written value. Should be NULL if and only if the parent structure is a sequence. @param value The written value */ CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value ); /** @brief Writes a floating-point value. The function writes a single floating-point value (with or without a name) to file storage. Special values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf. The following example shows how to use the low-level writing functions to store custom structures, such as termination criteria, without registering a new type. : @code void write_termcriteria( CvFileStorage* fs, const char* struct_name, CvTermCriteria* termcrit ) { cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0)); cvWriteComment( fs, "termination criteria", 1 ); // just a description if( termcrit->type & CV_TERMCRIT_ITER ) cvWriteInteger( fs, "max_iterations", termcrit->max_iter ); if( termcrit->type & CV_TERMCRIT_EPS ) cvWriteReal( fs, "accuracy", termcrit->epsilon ); cvEndWriteStruct( fs ); } @endcode @param fs File storage @param name Name of the written value. Should be NULL if and only if the parent structure is a sequence. @param value The written value */ CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value ); /** @brief Writes a text string. The function writes a text string to file storage. @param fs File storage @param name Name of the written string . Should be NULL if and only if the parent structure is a sequence. @param str The written text string @param quote If non-zero, the written string is put in quotes, regardless of whether they are required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces). */ CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name, const char* str, int quote CV_DEFAULT(0) ); /** @brief Writes a comment. The function writes a comment into file storage. The comments are skipped when the storage is read. @param fs File storage @param comment The written comment, single-line or multi-line @param eol_comment If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line. */ CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, int eol_comment ); /** @brief Writes an object to file storage. The function writes an object to file storage. First, the appropriate type info is found using cvTypeOf. Then, the write method associated with the type info is called. Attributes are used to customize the writing procedure. The standard types support the following attributes (all the dt attributes have the same format as in cvWriteRawData): -# CvSeq - **header_dt** description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence) - **dt** description of the sequence elements. - **recursive** if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored. -# CvGraph - **header_dt** description of user fields of the graph header that follows CvGraph; - **vertex_dt** description of user fields of graph vertices - **edge_dt** description of user fields of graph edges (note that the edge weight is always written, so there is no need to specify it explicitly) Below is the code that creates the YAML file shown in the CvFileStorage description: @code #include "cxcore.h" int main( int argc, char** argv ) { CvMat* mat = cvCreateMat( 3, 3, CV_32F ); CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE ); cvSetIdentity( mat ); cvWrite( fs, "A", mat, cvAttrList(0,0) ); cvReleaseFileStorage( &fs ); cvReleaseMat( &mat ); return 0; } @endcode @param fs File storage @param name Name of the written object. Should be NULL if and only if the parent structure is a sequence. @param ptr Pointer to the object @param attributes The attributes of the object. They are specific for each particular type (see the discussion below). */ CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr, CvAttrList attributes CV_DEFAULT(cvAttrList())); /** @brief Starts the next stream. The function finishes the currently written stream and starts the next stream. In the case of XML the file with multiple streams looks like this: @code{.xml} ... @endcode The YAML file will look like this: @code{.yaml} %YAML:1.0 # stream #1 data ... --- # stream #2 data @endcode This is useful for concatenating files or for resuming the writing process. @param fs File storage */ CVAPI(void) cvStartNextStream( CvFileStorage* fs ); /** @brief Writes multiple numbers. The function writes an array, whose elements consist of single or multiple numbers. The function call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single call is more efficient. Note that because none of the elements have a name, they should be written to a sequence rather than a map. @param fs File storage @param src Pointer to the written array @param len Number of the array elements to write @param dt Specification of each array element, see @ref format_spec "format specification" */ CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src, int len, const char* dt ); /** @brief Returns a unique pointer for a given name. The function returns a unique pointer for each particular file node name. This pointer can be then passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares text strings by comparing pointers rather than the strings' content. Consider the following example where an array of points is encoded as a sequence of 2-entry maps: @code points: - { x: 10, y: 10 } - { x: 20, y: 20 } - { x: 30, y: 30 } # ... @endcode Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. : @code #include "cxcore.h" int main( int argc, char** argv ) { CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 ); CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 ); CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" ); if( CV_NODE_IS_SEQ(points->tag) ) { CvSeq* seq = points->data.seq; int i, total = seq->total; CvSeqReader reader; cvStartReadSeq( seq, &reader, 0 ); for( i = 0; i < total; i++ ) { CvFileNode* pt = (CvFileNode*)reader.ptr; #if 1 // faster variant CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 ); CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 ); assert( xnode && CV_NODE_IS_INT(xnode->tag) && ynode && CV_NODE_IS_INT(ynode->tag)); int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); #elif 1 // slower variant; does not use x_key & y_key CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" ); CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" ); assert( xnode && CV_NODE_IS_INT(xnode->tag) && ynode && CV_NODE_IS_INT(ynode->tag)); int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); #else // the slowest yet the easiest to use variant int x = cvReadIntByName( fs, pt, "x", 0 ); int y = cvReadIntByName( fs, pt, "y", 0 ); #endif CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); printf(" } } cvReleaseFileStorage( &fs ); return 0; } @endcode Please note that whatever method of accessing a map you are using, it is still much slower than using plain sequences; for example, in the above example, it is more efficient to encode the points as pairs of integers in a single numeric sequence. @param fs File storage @param name Literal node name @param len Length of the name (if it is known apriori), or -1 if it needs to be calculated @param create_missing Flag that specifies, whether an absent key should be added into the hash table */ CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name, int len CV_DEFAULT(-1), int create_missing CV_DEFAULT(0)); /** @brief Retrieves one of the top-level nodes of the file storage. The function returns one of the top-level file nodes. The top-level nodes do not have a name, they correspond to the streams that are stored one after another in the file storage. If the index is out of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned. This function can be used as a base for recursive traversal of the file storage. @param fs File storage @param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases, there is only one stream in the file; however, there can be several. */ CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs, int stream_index CV_DEFAULT(0) ); /** @brief Finds a node in a map or file storage. The function finds a file node. It is a faster version of cvGetFileNodeByName (see cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet. @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. If both map and key are NULLs, the function returns the root file node - a map that contains top-level nodes. @param key Unique pointer to the node name, retrieved with cvGetHashedKey @param create_missing Flag that specifies whether an absent node should be added to the map */ CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int create_missing CV_DEFAULT(0) ); /** @brief Finds a node in a map or file storage. The function finds a file node by name. The node is searched either in map or, if the pointer is NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or sequence reader) for sequences, it is possible to navigate through the file storage. To speed up multiple queries for a certain key (e.g., in the case of an array of structures) one may use a combination of cvGetHashedKey and cvGetFileNode. @param fs File storage @param map The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one. @param name The file node name */ CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs, const CvFileNode* map, const char* name ); /** @brief Retrieves an integer value from a file node. The function returns an integer that is represented by the file node. If the file node is NULL, the default_value is returned (thus, it is convenient to call the function right after cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer and returned. Otherwise the error is reported. @param node File node @param default_value The value that is returned if node is NULL */ CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) ) { return !node ? default_value : CV_NODE_IS_INT(node->tag) ? node->data.i : CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff; } /** @brief Finds a file node and returns its value. The function is a simple superposition of cvGetFileNodeByName and cvReadInt. @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param default_value The value that is returned if the file node is not found */ CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, int default_value CV_DEFAULT(0) ) { return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value ); } /** @brief Retrieves a floating-point value from a file node. The function returns a floating-point value that is represented by the file node. If the file node is NULL, the default_value is returned (thus, it is convenient to call the function right after cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL , then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f is converted to floating-point and returned. Otherwise the result is not determined. @param node File node @param default_value The value that is returned if node is NULL */ CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) ) { return !node ? default_value : CV_NODE_IS_INT(node->tag) ? (double)node->data.i : CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300; } /** @brief Finds a file node and returns its value. The function is a simple superposition of cvGetFileNodeByName and cvReadReal . @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param default_value The value that is returned if the file node is not found */ CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double default_value CV_DEFAULT(0.) ) { return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value ); } /** @brief Retrieves a text string from a file node. The function returns a text string that is represented by the file node. If the file node is NULL, the default_value is returned (thus, it is convenient to call the function right after cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then node-:math:\>data.str.ptr is returned. Otherwise the result is not determined. @param node File node @param default_value The value that is returned if node is NULL */ CV_INLINE const char* cvReadString( const CvFileNode* node, const char* default_value CV_DEFAULT(NULL) ) { return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0; } /** @brief Finds a file node by its name and returns its value. The function is a simple superposition of cvGetFileNodeByName and cvReadString . @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param default_value The value that is returned if the file node is not found */ CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* default_value CV_DEFAULT(NULL) ) { return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value ); } /** @brief Decodes an object and returns a pointer to it. The function decodes a user object (creates an object in a native representation from the file storage subtree) and returns it. The object to be decoded must be an instance of a registered type that supports the read method (see CvTypeInfo). The type of the object is determined by the type name that is encoded in the file. If the object is a dynamic structure, it is created either in memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is not a dynamic structure, it is created in a heap and should be released with a specialized function or by using the generic cvRelease. @param fs File storage @param node The root object node @param attributes Unused parameter */ CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node, CvAttrList* attributes CV_DEFAULT(NULL)); /** @brief Finds an object by name and decodes it. The function is a simple superposition of cvGetFileNodeByName and cvRead. @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param attributes Unused parameter */ CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, const char* name, CvAttrList* attributes CV_DEFAULT(NULL) ) { return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes ); } /** @brief Initializes the file node sequence reader. The function initializes the sequence reader to read data from a file node. The initialized reader can be then passed to cvReadRawDataSlice. @param fs File storage @param src The file node (a sequence) to read numbers from @param reader Pointer to the sequence reader */ CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, CvSeqReader* reader ); /** @brief Initializes file node sequence reader. The function reads one or more elements from the file node, representing a sequence, to a user-specified array. The total number of read sequence elements is a product of total and the number of components in each array element. For example, if dt=2if, the function will read total\*3 sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read repeatedly by repositioning the reader using cvSetSeqReaderPos. @param fs File storage @param reader The sequence reader. Initialize it with cvStartReadRawData . @param count The number of elements to read @param dst Pointer to the destination array @param dt Specification of each array element. It has the same format as in cvWriteRawData . */ CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, int count, void* dst, const char* dt ); /** @brief Reads multiple numbers. The function reads elements from a file node that represents a sequence of scalars. @param fs File storage @param src The file node (a sequence) to read numbers from @param dst Pointer to the destination array @param dt Specification of each array element. It has the same format as in cvWriteRawData . */ CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, void* dst, const char* dt ); /** @brief Writes a file node to another file storage. The function writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML and YAML formats. @param fs Destination file storage @param new_node_name New name of the file node in the destination file storage. To keep the existing name, use cvcvGetFileNodeName @param node The written node @param embed If the written node is a collection and this parameter is not zero, no extra level of hierarchy is created. Instead, all the elements of node are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence. */ CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, const CvFileNode* node, int embed ); /** @brief Returns the name of a file node. The function returns the name of a file node or NULL, if the file node does not have a name or if node is NULL. @param node File node */ CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node ); /*********************************** Adding own types ***********************************/ /** @brief Registers a new type. The function registers a new type, which is described by info . The function creates a copy of the structure, so the user should delete it after calling the function. @param info Type info structure */ CVAPI(void) cvRegisterType( const CvTypeInfo* info ); /** @brief Unregisters the type. The function unregisters a type with a specified name. If the name is unknown, it is possible to locate the type info by an instance of the type using cvTypeOf or by iterating the type list, starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName). @param type_name Name of an unregistered type */ CVAPI(void) cvUnregisterType( const char* type_name ); /** @brief Returns the beginning of a type list. The function returns the first type in the list of registered types. Navigation through the list can be done via the prev and next fields of the CvTypeInfo structure. */ CVAPI(CvTypeInfo*) cvFirstType(void); /** @brief Finds a type by its name. The function finds a registered type by its name. It returns NULL if there is no type with the specified name. @param type_name Type name */ CVAPI(CvTypeInfo*) cvFindType( const char* type_name ); /** @brief Returns the type of an object. The function finds the type of a given object. It iterates through the list of registered types and calls the is_instance function/method for every type info structure with that object until one of them returns non-zero or until the whole list has been traversed. In the latter case, the function returns NULL. @param struct_ptr The object pointer */ CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr ); /** @brief Releases an object. The function finds the type of a given object and calls release with the double pointer. @param struct_ptr Double pointer to the object */ CVAPI(void) cvRelease( void** struct_ptr ); /** @brief Makes a clone of an object. The function finds the type of a given object and calls clone with the passed object. Of course, if you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific function, like cvCloneMat. @param struct_ptr The object to clone */ CVAPI(void*) cvClone( const void* struct_ptr ); /** @brief Saves an object to a file. The function saves an object to a file. It provides a simple interface to cvWrite . @param filename File name @param struct_ptr Object to save @param name Optional object name. If it is NULL, the name will be formed from filename . @param comment Optional comment to put in the beginning of the file @param attributes Optional attributes passed to cvWrite */ CVAPI(void) cvSave( const char* filename, const void* struct_ptr, const char* name CV_DEFAULT(NULL), const char* comment CV_DEFAULT(NULL), CvAttrList attributes CV_DEFAULT(cvAttrList())); /** @brief Loads an object from a file. The function loads an object from a file. It basically reads the specified file, find the first top-level node and calls cvRead for that node. If the file node does not have type information or the type information can not be found by the type name, the function returns NULL. After the object is loaded, the file storage is closed and all the temporary buffers are deleted. Thus, to load a dynamic structure, such as a sequence, contour, or graph, one should pass a valid memory storage destination to the function. @param filename File name @param memstorage Memory storage for dynamic structures, such as CvSeq or CvGraph . It is not used for matrices or images. @param name Optional object name. If it is NULL, the first top-level object in the storage will be loaded. @param real_name Optional output parameter that will contain the name of the loaded object (useful if name=NULL ) */ CVAPI(void*) cvLoad( const char* filename, CvMemStorage* memstorage CV_DEFAULT(NULL), const char* name CV_DEFAULT(NULL), const char** real_name CV_DEFAULT(NULL) ); /*********************************** Measuring Execution Time ***************************/ /** helper functions for RNG initialization and accurate time measurement: uses internal clock counter on x86 */ CVAPI(int64) cvGetTickCount( void ); CVAPI(double) cvGetTickFrequency( void ); /*********************************** CPU capabilities ***********************************/ CVAPI(int) cvCheckHardwareSupport(int feature); /*********************************** Multi-Threading ************************************/ /** retrieve/set the number of threads used in OpenMP implementations */ CVAPI(int) cvGetNumThreads( void ); CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); /** get index of the thread being executed */ CVAPI(int) cvGetThreadNum( void ); /********************************** Error Handling **************************************/ /** Get current OpenCV error status */ CVAPI(int) cvGetErrStatus( void ); /** Sets error status silently */ CVAPI(void) cvSetErrStatus( int status ); #define CV_ErrModeLeaf 0 /* Print error and exit program */ #define CV_ErrModeParent 1 /* Print error and continue */ #define CV_ErrModeSilent 2 /* Don't print and continue */ /** Retrives current error processing mode */ CVAPI(int) cvGetErrMode( void ); /** Sets error processing mode, returns previously used mode */ CVAPI(int) cvSetErrMode( int mode ); /** Sets error status and performs some additonal actions (displaying message box, writing message to stderr, terminating application etc.) depending on the current error mode */ CVAPI(void) cvError( int status, const char* func_name, const char* err_msg, const char* file_name, int line ); /** Retrieves textual description of the error given its code */ CVAPI(const char*) cvErrorStr( int status ); /** Retrieves detailed information about the last error occured */ CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description, const char** filename, int* line ); /** Maps IPP error codes to the counterparts from OpenCV */ CVAPI(int) cvErrorFromIppStatus( int ipp_status ); typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); /** Assigns a new error-handling function */ CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler, void* userdata CV_DEFAULT(NULL), void** prev_userdata CV_DEFAULT(NULL) ); /** Output nothing */ CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); /** Output to console(fprintf(stderr,...)) */ CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); /** Output to MessageBox(WIN32) */ CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); #define OPENCV_ERROR(status,func,context) \ cvError((status),(func),(context),__FILE__,__LINE__) #define OPENCV_ASSERT(expr,func,context) \ {if (! (expr)) \ {OPENCV_ERROR(CV_StsInternal,(func),(context));}} #define OPENCV_CALL( Func ) \ { \ Func; \ } /** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ #ifdef CV_NO_FUNC_NAMES #define CV_FUNCNAME( Name ) #define cvFuncName "" #else #define CV_FUNCNAME( Name ) \ static char cvFuncName[] = Name #endif /** CV_ERROR macro unconditionally raises error with passed code and message. After raising error, control will be transferred to the exit label. */ #define CV_ERROR( Code, Msg ) \ { \ cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ __CV_EXIT__; \ } /** CV_CHECK macro checks error status after CV (or IPL) function call. If error detected, control will be transferred to the exit label. */ #define CV_CHECK() \ { \ if( cvGetErrStatus() < 0 ) \ CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ } /** CV_CALL macro calls CV (or IPL) function, checks error status and signals a error if the function failed. Useful in "parent node" error procesing mode */ #define CV_CALL( Func ) \ { \ Func; \ CV_CHECK(); \ } /** Runtime assertion macro */ #define CV_ASSERT( Condition ) \ { \ if( !(Condition) ) \ CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ } #define __CV_BEGIN__ { #define __CV_END__ goto exit; exit: ; } #define __CV_EXIT__ goto exit /** @} core_c */ #ifdef __cplusplus } // extern "C" #endif #ifdef __cplusplus //! @addtogroup core_c_glue //! @{ //! class for automatic module/RTTI data registration/unregistration struct CV_EXPORTS CvType { CvType( const char* type_name, CvIsInstanceFunc is_instance, CvReleaseFunc release=0, CvReadFunc read=0, CvWriteFunc write=0, CvCloneFunc clone=0 ); ~CvType(); CvTypeInfo* info; static CvTypeInfo* first; static CvTypeInfo* last; }; //! @} #include "opencv2/core/utility.hpp" namespace cv { //! @addtogroup core_c_glue //! @{ /////////////////////////////////////////// glue /////////////////////////////////////////// //! converts array (CvMat or IplImage) to cv::Mat CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, bool allowND=true, int coiMode=0, AutoBuffer* buf=0); static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) { return cvarrToMat(arr, copyData, true, coiMode); } //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); ////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMat* obj) const; template<> CV_EXPORTS void DefaultDeleter::operator ()(IplImage* obj) const; template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMatND* obj) const; template<> CV_EXPORTS void DefaultDeleter::operator ()(CvSparseMat* obj) const; template<> CV_EXPORTS void DefaultDeleter::operator ()(CvMemStorage* obj) const; ////////////// convenient wrappers for operating old-style dynamic structures ////////////// template class SeqIterator; typedef Ptr MemStorage; /*! Template Sequence Class derived from CvSeq The class provides more convenient access to sequence elements, STL-style operations and iterators. \note The class is targeted for simple data types, i.e. no constructors or destructors are called for the sequence elements. */ template class Seq { public: typedef SeqIterator<_Tp> iterator; typedef SeqIterator<_Tp> const_iterator; //! the default constructor Seq(); //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. Seq(const CvSeq* seq); //! creates the empty sequence that resides in the specified storage Seq(MemStorage& storage, int headerSize = sizeof(CvSeq)); //! returns read-write reference to the specified element _Tp& operator [](int idx); //! returns read-only reference to the specified element const _Tp& operator[](int idx) const; //! returns iterator pointing to the beginning of the sequence SeqIterator<_Tp> begin() const; //! returns iterator pointing to the element following the last sequence element SeqIterator<_Tp> end() const; //! returns the number of elements in the sequence size_t size() const; //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...) int type() const; //! returns the depth of sequence elements (CV_8U ... CV_64F) int depth() const; //! returns the number of channels in each sequence element int channels() const; //! returns the size of each sequence element size_t elemSize() const; //! returns index of the specified sequence element size_t index(const _Tp& elem) const; //! appends the specified element to the end of the sequence void push_back(const _Tp& elem); //! appends the specified element to the front of the sequence void push_front(const _Tp& elem); //! appends zero or more elements to the end of the sequence void push_back(const _Tp* elems, size_t count); //! appends zero or more elements to the front of the sequence void push_front(const _Tp* elems, size_t count); //! inserts the specified element to the specified position void insert(int idx, const _Tp& elem); //! inserts zero or more elements to the specified position void insert(int idx, const _Tp* elems, size_t count); //! removes element at the specified position void remove(int idx); //! removes the specified subsequence void remove(const Range& r); //! returns reference to the first sequence element _Tp& front(); //! returns read-only reference to the first sequence element const _Tp& front() const; //! returns reference to the last sequence element _Tp& back(); //! returns read-only reference to the last sequence element const _Tp& back() const; //! returns true iff the sequence contains no elements bool empty() const; //! removes all the elements from the sequence void clear(); //! removes the first element from the sequence void pop_front(); //! removes the last element from the sequence void pop_back(); //! removes zero or more elements from the beginning of the sequence void pop_front(_Tp* elems, size_t count); //! removes zero or more elements from the end of the sequence void pop_back(_Tp* elems, size_t count); //! copies the whole sequence or the sequence slice to the specified vector void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const; //! returns the vector containing all the sequence elements operator std::vector<_Tp>() const; CvSeq* seq; }; /*! STL-style Sequence Iterator inherited from the CvSeqReader structure */ template class SeqIterator : public CvSeqReader { public: //! the default constructor SeqIterator(); //! the constructor setting the iterator to the beginning or to the end of the sequence SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false); //! positions the iterator within the sequence void seek(size_t pos); //! reports the current iterator position size_t tell() const; //! returns reference to the current sequence element _Tp& operator *(); //! returns read-only reference to the current sequence element const _Tp& operator *() const; //! moves iterator to the next sequence element SeqIterator& operator ++(); //! moves iterator to the next sequence element SeqIterator operator ++(int) const; //! moves iterator to the previous sequence element SeqIterator& operator --(); //! moves iterator to the previous sequence element SeqIterator operator --(int) const; //! moves iterator forward by the specified offset (possibly negative) SeqIterator& operator +=(int); //! moves iterator backward by the specified offset (possibly negative) SeqIterator& operator -=(int); // this is index of the current element module seq->total*2 // (to distinguish between 0 and seq->total) int index; }; // bridge C++ => C Seq API CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0); CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0); CV_EXPORTS void seqPop( CvSeq* seq, void* element=0); CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0); CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements, int count, int in_front=0 ); CV_EXPORTS void seqRemove( CvSeq* seq, int index ); CV_EXPORTS void clearSeq( CvSeq* seq ); CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); template inline Seq<_Tp>::Seq() : seq(0) {} template inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) { CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp)); } template inline Seq<_Tp>::Seq( MemStorage& storage, int headerSize ) { CV_Assert(headerSize >= (int)sizeof(CvSeq)); seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage); } template inline _Tp& Seq<_Tp>::operator [](int idx) { return *(_Tp*)getSeqElem(seq, idx); } template inline const _Tp& Seq<_Tp>::operator [](int idx) const { return *(_Tp*)getSeqElem(seq, idx); } template inline SeqIterator<_Tp> Seq<_Tp>::begin() const { return SeqIterator<_Tp>(*this); } template inline SeqIterator<_Tp> Seq<_Tp>::end() const { return SeqIterator<_Tp>(*this, true); } template inline size_t Seq<_Tp>::size() const { return seq ? seq->total : 0; } template inline int Seq<_Tp>::type() const { return seq ? CV_MAT_TYPE(seq->flags) : 0; } template inline int Seq<_Tp>::depth() const { return seq ? CV_MAT_DEPTH(seq->flags) : 0; } template inline int Seq<_Tp>::channels() const { return seq ? CV_MAT_CN(seq->flags) : 0; } template inline size_t Seq<_Tp>::elemSize() const { return seq ? seq->elem_size : 0; } template inline size_t Seq<_Tp>::index(const _Tp& elem) const { return cvSeqElemIdx(seq, &elem); } template inline void Seq<_Tp>::push_back(const _Tp& elem) { cvSeqPush(seq, &elem); } template inline void Seq<_Tp>::push_front(const _Tp& elem) { cvSeqPushFront(seq, &elem); } template inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count) { cvSeqPushMulti(seq, elem, (int)count, 0); } template inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) { cvSeqPushMulti(seq, elem, (int)count, 1); } template inline _Tp& Seq<_Tp>::back() { return *(_Tp*)getSeqElem(seq, -1); } template inline const _Tp& Seq<_Tp>::back() const { return *(const _Tp*)getSeqElem(seq, -1); } template inline _Tp& Seq<_Tp>::front() { return *(_Tp*)getSeqElem(seq, 0); } template inline const _Tp& Seq<_Tp>::front() const { return *(const _Tp*)getSeqElem(seq, 0); } template inline bool Seq<_Tp>::empty() const { return !seq || seq->total == 0; } template inline void Seq<_Tp>::clear() { if(seq) clearSeq(seq); } template inline void Seq<_Tp>::pop_back() { seqPop(seq); } template inline void Seq<_Tp>::pop_front() { seqPopFront(seq); } template inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) { seqPopMulti(seq, elem, (int)count, 0); } template inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) { seqPopMulti(seq, elem, (int)count, 1); } template inline void Seq<_Tp>::insert(int idx, const _Tp& elem) { seqInsert(seq, idx, &elem); } template inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) { CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); seqInsertSlice(seq, idx, &m); } template inline void Seq<_Tp>::remove(int idx) { seqRemove(seq, idx); } template inline void Seq<_Tp>::remove(const Range& r) { seqRemoveSlice(seq, cvSlice(r.start, r.end)); } template inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const { size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; vec.resize(len); if( seq && len ) cvCvtSeqToArray(seq, &vec[0], range); } template inline Seq<_Tp>::operator std::vector<_Tp>() const { std::vector<_Tp> vec; copyTo(vec); return vec; } template inline SeqIterator<_Tp>::SeqIterator() { memset(this, 0, sizeof(*this)); } template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) { cvStartReadSeq(_seq.seq, this); index = seekEnd ? _seq.seq->total : 0; } template inline void SeqIterator<_Tp>::seek(size_t pos) { cvSetSeqReaderPos(this, (int)pos, false); index = pos; } template inline size_t SeqIterator<_Tp>::tell() const { return index; } template inline _Tp& SeqIterator<_Tp>::operator *() { return *(_Tp*)ptr; } template inline const _Tp& SeqIterator<_Tp>::operator *() const { return *(const _Tp*)ptr; } template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++() { CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this); if( ++index >= seq->total*2 ) index = 0; return *this; } template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const { SeqIterator<_Tp> it = *this; ++*this; return it; } template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --() { CV_PREV_SEQ_ELEM(sizeof(_Tp), *this); if( --index < 0 ) index = seq->total*2-1; return *this; } template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const { SeqIterator<_Tp> it = *this; --*this; return it; } template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta) { cvSetSeqReaderPos(this, delta, 1); index += delta; int n = seq->total*2; if( index < 0 ) index += n; if( index >= n ) index -= n; return *this; } template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta) { return (*this += -delta); } template inline ptrdiff_t operator - (const SeqIterator<_Tp>& a, const SeqIterator<_Tp>& b) { ptrdiff_t delta = a.index - b.index, n = a.seq->total; if( delta > n || delta < -n ) delta += delta < 0 ? n : -n; return delta; } template inline bool operator == (const SeqIterator<_Tp>& a, const SeqIterator<_Tp>& b) { return a.seq == b.seq && a.index == b.index; } template inline bool operator != (const SeqIterator<_Tp>& a, const SeqIterator<_Tp>& b) { return !(a == b); } //! @} } // cv #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/block.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_DEVICE_BLOCK_HPP__ #define __OPENCV_CUDA_DEVICE_BLOCK_HPP__ /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { struct Block { static __device__ __forceinline__ unsigned int id() { return blockIdx.x; } static __device__ __forceinline__ unsigned int stride() { return blockDim.x * blockDim.y * blockDim.z; } static __device__ __forceinline__ void sync() { __syncthreads(); } static __device__ __forceinline__ int flattenedThreadId() { return threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; } template static __device__ __forceinline__ void fill(It beg, It end, const T& value) { int STRIDE = stride(); It t = beg + flattenedThreadId(); for(; t < end; t += STRIDE) *t = value; } template static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) { int STRIDE = stride(); int tid = flattenedThreadId(); value += tid; for(OutIt t = beg + tid; t < end; t += STRIDE, value += STRIDE) *t = value; } template static __device__ __forceinline__ void copy(InIt beg, InIt end, OutIt out) { int STRIDE = stride(); InIt t = beg + flattenedThreadId(); OutIt o = out + (t - beg); for(; t < end; t += STRIDE, o += STRIDE) *o = *t; } template static __device__ __forceinline__ void transfrom(InIt beg, InIt end, OutIt out, UnOp op) { int STRIDE = stride(); InIt t = beg + flattenedThreadId(); OutIt o = out + (t - beg); for(; t < end; t += STRIDE, o += STRIDE) *o = op(*t); } template static __device__ __forceinline__ void transfrom(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) { int STRIDE = stride(); InIt1 t1 = beg1 + flattenedThreadId(); InIt2 t2 = beg2 + flattenedThreadId(); OutIt o = out + (t1 - beg1); for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, o += STRIDE) *o = op(*t1, *t2); } template static __device__ __forceinline__ void reduce(volatile T* buffer, BinOp op) { int tid = flattenedThreadId(); T val = buffer[tid]; if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } if (tid < 32) { if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } } } template static __device__ __forceinline__ T reduce(volatile T* buffer, T init, BinOp op) { int tid = flattenedThreadId(); T val = buffer[tid] = init; __syncthreads(); if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } if (tid < 32) { if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } } __syncthreads(); return buffer[0]; } template static __device__ __forceinline__ void reduce_n(T* data, unsigned int n, BinOp op) { int ftid = flattenedThreadId(); int sft = stride(); if (sft < n) { for (unsigned int i = sft + ftid; i < n; i += sft) data[ftid] = op(data[ftid], data[i]); __syncthreads(); n = sft; } while (n > 1) { unsigned int half = n/2; if (ftid < half) data[ftid] = op(data[ftid], data[n - ftid - 1]); __syncthreads(); n = n - half; } } }; }}} //! @endcond #endif /* __OPENCV_CUDA_DEVICE_BLOCK_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/border_interpolate.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_BORDER_INTERPOLATE_HPP__ #define __OPENCV_CUDA_BORDER_INTERPOLATE_HPP__ #include "saturate_cast.hpp" #include "vec_traits.hpp" #include "vec_math.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { ////////////////////////////////////////////////////////////// // BrdConstant template struct BrdRowConstant { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdRowConstant(int width_, const D& val_ = VecTraits::all(0)) : width(width_), val(val_) {} template __device__ __forceinline__ D at_low(int x, const T* data) const { return x >= 0 ? saturate_cast(data[x]) : val; } template __device__ __forceinline__ D at_high(int x, const T* data) const { return x < width ? saturate_cast(data[x]) : val; } template __device__ __forceinline__ D at(int x, const T* data) const { return (x >= 0 && x < width) ? saturate_cast(data[x]) : val; } int width; D val; }; template struct BrdColConstant { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdColConstant(int height_, const D& val_ = VecTraits::all(0)) : height(height_), val(val_) {} template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const { return y >= 0 ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; } template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const { return y < height ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; } template __device__ __forceinline__ D at(int y, const T* data, size_t step) const { return (y >= 0 && y < height) ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; } int height; D val; }; template struct BrdConstant { typedef D result_type; __host__ __device__ __forceinline__ BrdConstant(int height_, int width_, const D& val_ = VecTraits::all(0)) : height(height_), width(width_), val(val_) { } template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const { return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(((const T*)((const uchar*)data + y * step))[x]) : val; } template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const { return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; } int height; int width; D val; }; ////////////////////////////////////////////////////////////// // BrdReplicate template struct BrdRowReplicate { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdRowReplicate(int width) : last_col(width - 1) {} template __host__ __device__ __forceinline__ BrdRowReplicate(int width, U) : last_col(width - 1) {} __device__ __forceinline__ int idx_col_low(int x) const { return ::max(x, 0); } __device__ __forceinline__ int idx_col_high(int x) const { return ::min(x, last_col); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_low(idx_col_high(x)); } template __device__ __forceinline__ D at_low(int x, const T* data) const { return saturate_cast(data[idx_col_low(x)]); } template __device__ __forceinline__ D at_high(int x, const T* data) const { return saturate_cast(data[idx_col_high(x)]); } template __device__ __forceinline__ D at(int x, const T* data) const { return saturate_cast(data[idx_col(x)]); } int last_col; }; template struct BrdColReplicate { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdColReplicate(int height) : last_row(height - 1) {} template __host__ __device__ __forceinline__ BrdColReplicate(int height, U) : last_row(height - 1) {} __device__ __forceinline__ int idx_row_low(int y) const { return ::max(y, 0); } __device__ __forceinline__ int idx_row_high(int y) const { return ::min(y, last_row); } __device__ __forceinline__ int idx_row(int y) const { return idx_row_low(idx_row_high(y)); } template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const { return saturate_cast(*(const T*)((const char*)data + idx_row_low(y) * step)); } template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const { return saturate_cast(*(const T*)((const char*)data + idx_row_high(y) * step)); } template __device__ __forceinline__ D at(int y, const T* data, size_t step) const { return saturate_cast(*(const T*)((const char*)data + idx_row(y) * step)); } int last_row; }; template struct BrdReplicate { typedef D result_type; __host__ __device__ __forceinline__ BrdReplicate(int height, int width) : last_row(height - 1), last_col(width - 1) {} template __host__ __device__ __forceinline__ BrdReplicate(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} __device__ __forceinline__ int idx_row_low(int y) const { return ::max(y, 0); } __device__ __forceinline__ int idx_row_high(int y) const { return ::min(y, last_row); } __device__ __forceinline__ int idx_row(int y) const { return idx_row_low(idx_row_high(y)); } __device__ __forceinline__ int idx_col_low(int x) const { return ::max(x, 0); } __device__ __forceinline__ int idx_col_high(int x) const { return ::min(x, last_col); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_low(idx_col_high(x)); } template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const { return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); } template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const { return saturate_cast(src(idx_row(y), idx_col(x))); } int last_row; int last_col; }; ////////////////////////////////////////////////////////////// // BrdReflect101 template struct BrdRowReflect101 { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdRowReflect101(int width) : last_col(width - 1) {} template __host__ __device__ __forceinline__ BrdRowReflect101(int width, U) : last_col(width - 1) {} __device__ __forceinline__ int idx_col_low(int x) const { return ::abs(x) % (last_col + 1); } __device__ __forceinline__ int idx_col_high(int x) const { return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_low(idx_col_high(x)); } template __device__ __forceinline__ D at_low(int x, const T* data) const { return saturate_cast(data[idx_col_low(x)]); } template __device__ __forceinline__ D at_high(int x, const T* data) const { return saturate_cast(data[idx_col_high(x)]); } template __device__ __forceinline__ D at(int x, const T* data) const { return saturate_cast(data[idx_col(x)]); } int last_col; }; template struct BrdColReflect101 { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdColReflect101(int height) : last_row(height - 1) {} template __host__ __device__ __forceinline__ BrdColReflect101(int height, U) : last_row(height - 1) {} __device__ __forceinline__ int idx_row_low(int y) const { return ::abs(y) % (last_row + 1); } __device__ __forceinline__ int idx_row_high(int y) const { return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); } __device__ __forceinline__ int idx_row(int y) const { return idx_row_low(idx_row_high(y)); } template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); } template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); } template __device__ __forceinline__ D at(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); } int last_row; }; template struct BrdReflect101 { typedef D result_type; __host__ __device__ __forceinline__ BrdReflect101(int height, int width) : last_row(height - 1), last_col(width - 1) {} template __host__ __device__ __forceinline__ BrdReflect101(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} __device__ __forceinline__ int idx_row_low(int y) const { return ::abs(y) % (last_row + 1); } __device__ __forceinline__ int idx_row_high(int y) const { return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); } __device__ __forceinline__ int idx_row(int y) const { return idx_row_low(idx_row_high(y)); } __device__ __forceinline__ int idx_col_low(int x) const { return ::abs(x) % (last_col + 1); } __device__ __forceinline__ int idx_col_high(int x) const { return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_low(idx_col_high(x)); } template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const { return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); } template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const { return saturate_cast(src(idx_row(y), idx_col(x))); } int last_row; int last_col; }; ////////////////////////////////////////////////////////////// // BrdReflect template struct BrdRowReflect { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdRowReflect(int width) : last_col(width - 1) {} template __host__ __device__ __forceinline__ BrdRowReflect(int width, U) : last_col(width - 1) {} __device__ __forceinline__ int idx_col_low(int x) const { return (::abs(x) - (x < 0)) % (last_col + 1); } __device__ __forceinline__ int idx_col_high(int x) const { return ::abs(last_col - ::abs(last_col - x) + (x > last_col)) % (last_col + 1); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_high(::abs(x) - (x < 0)); } template __device__ __forceinline__ D at_low(int x, const T* data) const { return saturate_cast(data[idx_col_low(x)]); } template __device__ __forceinline__ D at_high(int x, const T* data) const { return saturate_cast(data[idx_col_high(x)]); } template __device__ __forceinline__ D at(int x, const T* data) const { return saturate_cast(data[idx_col(x)]); } int last_col; }; template struct BrdColReflect { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdColReflect(int height) : last_row(height - 1) {} template __host__ __device__ __forceinline__ BrdColReflect(int height, U) : last_row(height - 1) {} __device__ __forceinline__ int idx_row_low(int y) const { return (::abs(y) - (y < 0)) % (last_row + 1); } __device__ __forceinline__ int idx_row_high(int y) const { return ::abs(last_row - ::abs(last_row - y) + (y > last_row)) % (last_row + 1); } __device__ __forceinline__ int idx_row(int y) const { return idx_row_high(::abs(y) - (y < 0)); } template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); } template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); } template __device__ __forceinline__ D at(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); } int last_row; }; template struct BrdReflect { typedef D result_type; __host__ __device__ __forceinline__ BrdReflect(int height, int width) : last_row(height - 1), last_col(width - 1) {} template __host__ __device__ __forceinline__ BrdReflect(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} __device__ __forceinline__ int idx_row_low(int y) const { return (::abs(y) - (y < 0)) % (last_row + 1); } __device__ __forceinline__ int idx_row_high(int y) const { return /*::abs*/(last_row - ::abs(last_row - y) + (y > last_row)) /*% (last_row + 1)*/; } __device__ __forceinline__ int idx_row(int y) const { return idx_row_low(idx_row_high(y)); } __device__ __forceinline__ int idx_col_low(int x) const { return (::abs(x) - (x < 0)) % (last_col + 1); } __device__ __forceinline__ int idx_col_high(int x) const { return (last_col - ::abs(last_col - x) + (x > last_col)); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_low(idx_col_high(x)); } template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const { return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); } template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const { return saturate_cast(src(idx_row(y), idx_col(x))); } int last_row; int last_col; }; ////////////////////////////////////////////////////////////// // BrdWrap template struct BrdRowWrap { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdRowWrap(int width_) : width(width_) {} template __host__ __device__ __forceinline__ BrdRowWrap(int width_, U) : width(width_) {} __device__ __forceinline__ int idx_col_low(int x) const { return (x >= 0) * x + (x < 0) * (x - ((x - width + 1) / width) * width); } __device__ __forceinline__ int idx_col_high(int x) const { return (x < width) * x + (x >= width) * (x % width); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_high(idx_col_low(x)); } template __device__ __forceinline__ D at_low(int x, const T* data) const { return saturate_cast(data[idx_col_low(x)]); } template __device__ __forceinline__ D at_high(int x, const T* data) const { return saturate_cast(data[idx_col_high(x)]); } template __device__ __forceinline__ D at(int x, const T* data) const { return saturate_cast(data[idx_col(x)]); } int width; }; template struct BrdColWrap { typedef D result_type; explicit __host__ __device__ __forceinline__ BrdColWrap(int height_) : height(height_) {} template __host__ __device__ __forceinline__ BrdColWrap(int height_, U) : height(height_) {} __device__ __forceinline__ int idx_row_low(int y) const { return (y >= 0) * y + (y < 0) * (y - ((y - height + 1) / height) * height); } __device__ __forceinline__ int idx_row_high(int y) const { return (y < height) * y + (y >= height) * (y % height); } __device__ __forceinline__ int idx_row(int y) const { return idx_row_high(idx_row_low(y)); } template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); } template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); } template __device__ __forceinline__ D at(int y, const T* data, size_t step) const { return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); } int height; }; template struct BrdWrap { typedef D result_type; __host__ __device__ __forceinline__ BrdWrap(int height_, int width_) : height(height_), width(width_) { } template __host__ __device__ __forceinline__ BrdWrap(int height_, int width_, U) : height(height_), width(width_) { } __device__ __forceinline__ int idx_row_low(int y) const { return (y >= 0) ? y : (y - ((y - height + 1) / height) * height); } __device__ __forceinline__ int idx_row_high(int y) const { return (y < height) ? y : (y % height); } __device__ __forceinline__ int idx_row(int y) const { return idx_row_high(idx_row_low(y)); } __device__ __forceinline__ int idx_col_low(int x) const { return (x >= 0) ? x : (x - ((x - width + 1) / width) * width); } __device__ __forceinline__ int idx_col_high(int x) const { return (x < width) ? x : (x % width); } __device__ __forceinline__ int idx_col(int x) const { return idx_col_high(idx_col_low(x)); } template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const { return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); } template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const { return saturate_cast(src(idx_row(y), idx_col(x))); } int height; int width; }; ////////////////////////////////////////////////////////////// // BorderReader template struct BorderReader { typedef typename B::result_type elem_type; typedef typename Ptr2D::index_type index_type; __host__ __device__ __forceinline__ BorderReader(const Ptr2D& ptr_, const B& b_) : ptr(ptr_), b(b_) {} __device__ __forceinline__ elem_type operator ()(index_type y, index_type x) const { return b.at(y, x, ptr); } Ptr2D ptr; B b; }; // under win32 there is some bug with templated types that passed as kernel parameters // with this specialization all works fine template struct BorderReader< Ptr2D, BrdConstant > { typedef typename BrdConstant::result_type elem_type; typedef typename Ptr2D::index_type index_type; __host__ __device__ __forceinline__ BorderReader(const Ptr2D& src_, const BrdConstant& b) : src(src_), height(b.height), width(b.width), val(b.val) { } __device__ __forceinline__ D operator ()(index_type y, index_type x) const { return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; } Ptr2D src; int height; int width; D val; }; }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_BORDER_INTERPOLATE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/color.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_COLOR_HPP__ #define __OPENCV_CUDA_COLOR_HPP__ #include "detail/color_detail.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { // All OPENCV_CUDA_IMPLEMENT_*_TRAITS(ColorSpace1_to_ColorSpace2, ...) macros implements // template class ColorSpace1_to_ColorSpace2_traits // { // typedef ... functor_type; // static __host__ __device__ functor_type create_functor(); // }; OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgb, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_bgra, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgba, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_bgr, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgb, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgba, 4, 4, 2) #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr555, 3, 0, 5) OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr565, 3, 0, 6) OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr555, 3, 2, 5) OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr565, 3, 2, 6) OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr555, 4, 0, 5) OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr565, 4, 0, 6) OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr555, 4, 2, 5) OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr565, 4, 2, 6) #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgb, 3, 2, 5) OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgb, 3, 2, 6) OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgr, 3, 0, 5) OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgr, 3, 0, 6) OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgba, 4, 2, 5) OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgba, 4, 2, 6) OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgra, 4, 0, 5) OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgra, 4, 0, 6) #undef OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgr, 3) OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgra, 4) #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr555, 5) OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr565, 6) #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr555_to_gray, 5) OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr565_to_gray, 6) #undef OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgb_to_gray, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgr_to_gray, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgba_to_gray, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgra_to_gray, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv4, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv4, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv4, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv4, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgb, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgba, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgb, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgba, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgr, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgra, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgr, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgra, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb4, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb4, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb4, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb4, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgb, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgba, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgb, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgba, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgr, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgra, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgr, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgra, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz4, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz4, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz4, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz4, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgb, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgb, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgba, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgba, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgr, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgr, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgra, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgra, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv4, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv4, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv4, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv4, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgb, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgba, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgb, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgba, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgr, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgra, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgr, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgra, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls4, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls4, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls4, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls4, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgb, 3, 3, 2) OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgba, 3, 4, 2) OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgb, 4, 3, 2) OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgba, 4, 4, 2) OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgr, 3, 3, 0) OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgra, 3, 4, 0) OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgr, 4, 3, 0) OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgra, 4, 4, 0) #undef OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab, 3, 3, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab, 4, 3, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab4, 3, 4, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab4, 4, 4, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab, 3, 3, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab, 4, 3, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab4, 3, 4, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab4, 4, 4, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab, 3, 3, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab, 4, 3, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab4, 3, 4, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab4, 4, 4, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab, 3, 3, false, 0) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab, 4, 3, false, 0) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab4, 3, 4, false, 0) OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab4, 4, 4, false, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgb, 3, 3, true, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgb, 4, 3, true, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgba, 3, 4, true, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgba, 4, 4, true, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgr, 3, 3, true, 0) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgr, 4, 3, true, 0) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgra, 3, 4, true, 0) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgra, 4, 4, true, 0) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgb, 3, 3, false, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgb, 4, 3, false, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgba, 3, 4, false, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgba, 4, 4, false, 2) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgr, 3, 3, false, 0) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgr, 4, 3, false, 0) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgra, 3, 4, false, 0) OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgra, 4, 4, false, 0) #undef OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv, 3, 3, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv, 4, 3, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv4, 3, 4, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv4, 4, 4, true, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv, 3, 3, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv, 4, 3, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv4, 3, 4, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv4, 4, 4, true, 0) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv, 3, 3, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv, 4, 3, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv4, 3, 4, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv4, 4, 4, false, 2) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv, 3, 3, false, 0) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv, 4, 3, false, 0) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv4, 3, 4, false, 0) OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv4, 4, 4, false, 0) #undef OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgb, 3, 3, true, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgb, 4, 3, true, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgba, 3, 4, true, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgba, 4, 4, true, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgr, 3, 3, true, 0) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgr, 4, 3, true, 0) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgra, 3, 4, true, 0) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgra, 4, 4, true, 0) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgb, 3, 3, false, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgb, 4, 3, false, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgba, 3, 4, false, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgba, 4, 4, false, 2) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgr, 3, 3, false, 0) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgr, 4, 3, false, 0) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgra, 3, 4, false, 0) OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgra, 4, 4, false, 0) #undef OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_BORDER_INTERPOLATE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/common.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_COMMON_HPP__ #define __OPENCV_CUDA_COMMON_HPP__ #include #include "opencv2/core/cuda_types.hpp" #include "opencv2/core/cvdef.h" #include "opencv2/core/base.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED #ifndef CV_PI_F #ifndef CV_PI #define CV_PI_F 3.14159265f #else #define CV_PI_F ((float)CV_PI) #endif #endif namespace cv { namespace cuda { static inline void checkCudaError(cudaError_t err, const char* file, const int line, const char* func) { if (cudaSuccess != err) cv::error(cv::Error::GpuApiCallError, cudaGetErrorString(err), func, file, line); } }} #ifndef cudaSafeCall #define cudaSafeCall(expr) cv::cuda::checkCudaError(expr, __FILE__, __LINE__, CV_Func) #endif namespace cv { namespace cuda { template static inline bool isAligned(const T* ptr, size_t size) { return reinterpret_cast(ptr) % size == 0; } static inline bool isAligned(size_t step, size_t size) { return step % size == 0; } }} namespace cv { namespace cuda { namespace device { __host__ __device__ __forceinline__ int divUp(int total, int grain) { return (total + grain - 1) / grain; } template inline void bindTexture(const textureReference* tex, const PtrStepSz& img) { cudaChannelFormatDesc desc = cudaCreateChannelDesc(); cudaSafeCall( cudaBindTexture2D(0, tex, img.ptr(), &desc, img.cols, img.rows, img.step) ); } } }} //! @endcond #endif // __OPENCV_CUDA_COMMON_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/datamov_utils.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_DATAMOV_UTILS_HPP__ #define __OPENCV_CUDA_DATAMOV_UTILS_HPP__ #include "common.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 200 // for Fermi memory space is detected automatically template struct ForceGlob { __device__ __forceinline__ static void Load(const T* ptr, int offset, T& val) { val = ptr[offset]; } }; #else // __CUDA_ARCH__ >= 200 #if defined(_WIN64) || defined(__LP64__) // 64-bit register modifier for inlined asm #define OPENCV_CUDA_ASM_PTR "l" #else // 32-bit register modifier for inlined asm #define OPENCV_CUDA_ASM_PTR "r" #endif template struct ForceGlob; #define OPENCV_CUDA_DEFINE_FORCE_GLOB(base_type, ptx_type, reg_mod) \ template <> struct ForceGlob \ { \ __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ { \ asm("ld.global."#ptx_type" %0, [%1];" : "="#reg_mod(val) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ } \ }; #define OPENCV_CUDA_DEFINE_FORCE_GLOB_B(base_type, ptx_type) \ template <> struct ForceGlob \ { \ __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ { \ asm("ld.global."#ptx_type" %0, [%1];" : "=r"(*reinterpret_cast(&val)) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ } \ }; OPENCV_CUDA_DEFINE_FORCE_GLOB_B(uchar, u8) OPENCV_CUDA_DEFINE_FORCE_GLOB_B(schar, s8) OPENCV_CUDA_DEFINE_FORCE_GLOB_B(char, b8) OPENCV_CUDA_DEFINE_FORCE_GLOB (ushort, u16, h) OPENCV_CUDA_DEFINE_FORCE_GLOB (short, s16, h) OPENCV_CUDA_DEFINE_FORCE_GLOB (uint, u32, r) OPENCV_CUDA_DEFINE_FORCE_GLOB (int, s32, r) OPENCV_CUDA_DEFINE_FORCE_GLOB (float, f32, f) OPENCV_CUDA_DEFINE_FORCE_GLOB (double, f64, d) #undef OPENCV_CUDA_DEFINE_FORCE_GLOB #undef OPENCV_CUDA_DEFINE_FORCE_GLOB_B #undef OPENCV_CUDA_ASM_PTR #endif // __CUDA_ARCH__ >= 200 }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_DATAMOV_UTILS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/detail/color_detail.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_COLOR_DETAIL_HPP__ #define __OPENCV_CUDA_COLOR_DETAIL_HPP__ #include "../common.hpp" #include "../vec_traits.hpp" #include "../saturate_cast.hpp" #include "../limits.hpp" #include "../functional.hpp" //! @cond IGNORED namespace cv { namespace cuda { namespace device { #ifndef CV_DESCALE #define CV_DESCALE(x, n) (((x) + (1 << ((n)-1))) >> (n)) #endif namespace color_detail { template struct ColorChannel { typedef float worktype_f; static __device__ __forceinline__ T max() { return numeric_limits::max(); } static __device__ __forceinline__ T half() { return (T)(max()/2 + 1); } }; template<> struct ColorChannel { typedef float worktype_f; static __device__ __forceinline__ float max() { return 1.f; } static __device__ __forceinline__ float half() { return 0.5f; } }; template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) { } template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) { vec.w = val; } template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) { return ColorChannel::max(); } template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) { return vec.w; } enum { yuv_shift = 14, xyz_shift = 12, R2Y = 4899, G2Y = 9617, B2Y = 1868, BLOCK_SIZE = 256 }; } ////////////////// Various 3/4-channel to 3/4-channel RGB transformations ///////////////// namespace color_detail { template struct RGB2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; dst.x = (&src.x)[bidx]; dst.y = src.y; dst.z = (&src.x)[bidx^2]; setAlpha(dst, getAlpha(src)); return dst; } __host__ __device__ __forceinline__ RGB2RGB() {} __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} }; template <> struct RGB2RGB : unary_function { __device__ uint operator()(uint src) const { uint dst = 0; dst |= (0xffu & (src >> 16)); dst |= (0xffu & (src >> 8)) << 8; dst |= (0xffu & (src)) << 16; dst |= (0xffu & (src >> 24)) << 24; return dst; } __host__ __device__ __forceinline__ RGB2RGB() {} __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; /////////// Transforming 16-bit (565 or 555) RGB to/from 24/32-bit (888[8]) RGB ////////// namespace color_detail { template struct RGB2RGB5x5Converter; template struct RGB2RGB5x5Converter<6, bidx> { static __device__ __forceinline__ ushort cvt(const uchar3& src) { return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~3) << 3) | (((&src.x)[bidx^2] & ~7) << 8)); } static __device__ __forceinline__ ushort cvt(uint src) { uint b = 0xffu & (src >> (bidx * 8)); uint g = 0xffu & (src >> 8); uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); return (ushort)((b >> 3) | ((g & ~3) << 3) | ((r & ~7) << 8)); } }; template struct RGB2RGB5x5Converter<5, bidx> { static __device__ __forceinline__ ushort cvt(const uchar3& src) { return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~7) << 2) | (((&src.x)[bidx^2] & ~7) << 7)); } static __device__ __forceinline__ ushort cvt(uint src) { uint b = 0xffu & (src >> (bidx * 8)); uint g = 0xffu & (src >> 8); uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); uint a = 0xffu & (src >> 24); return (ushort)((b >> 3) | ((g & ~7) << 2) | ((r & ~7) << 7) | (a * 0x8000)); } }; template struct RGB2RGB5x5; template struct RGB2RGB5x5<3, bidx,green_bits> : unary_function { __device__ __forceinline__ ushort operator()(const uchar3& src) const { return RGB2RGB5x5Converter::cvt(src); } __host__ __device__ __forceinline__ RGB2RGB5x5() {} __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} }; template struct RGB2RGB5x5<4, bidx,green_bits> : unary_function { __device__ __forceinline__ ushort operator()(uint src) const { return RGB2RGB5x5Converter::cvt(src); } __host__ __device__ __forceinline__ RGB2RGB5x5() {} __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(name, scn, bidx, green_bits) \ struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2RGB5x5 functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { template struct RGB5x52RGBConverter; template struct RGB5x52RGBConverter<5, bidx> { static __device__ __forceinline__ void cvt(uint src, uchar3& dst) { (&dst.x)[bidx] = src << 3; dst.y = (src >> 2) & ~7; (&dst.x)[bidx ^ 2] = (src >> 7) & ~7; } static __device__ __forceinline__ void cvt(uint src, uint& dst) { dst = 0; dst |= (0xffu & (src << 3)) << (bidx * 8); dst |= (0xffu & ((src >> 2) & ~7)) << 8; dst |= (0xffu & ((src >> 7) & ~7)) << ((bidx ^ 2) * 8); dst |= ((src & 0x8000) * 0xffu) << 24; } }; template struct RGB5x52RGBConverter<6, bidx> { static __device__ __forceinline__ void cvt(uint src, uchar3& dst) { (&dst.x)[bidx] = src << 3; dst.y = (src >> 3) & ~3; (&dst.x)[bidx ^ 2] = (src >> 8) & ~7; } static __device__ __forceinline__ void cvt(uint src, uint& dst) { dst = 0xffu << 24; dst |= (0xffu & (src << 3)) << (bidx * 8); dst |= (0xffu &((src >> 3) & ~3)) << 8; dst |= (0xffu & ((src >> 8) & ~7)) << ((bidx ^ 2) * 8); } }; template struct RGB5x52RGB; template struct RGB5x52RGB<3, bidx, green_bits> : unary_function { __device__ __forceinline__ uchar3 operator()(ushort src) const { uchar3 dst; RGB5x52RGBConverter::cvt(src, dst); return dst; } __host__ __device__ __forceinline__ RGB5x52RGB() {} __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} }; template struct RGB5x52RGB<4, bidx, green_bits> : unary_function { __device__ __forceinline__ uint operator()(ushort src) const { uint dst; RGB5x52RGBConverter::cvt(src, dst); return dst; } __host__ __device__ __forceinline__ RGB5x52RGB() {} __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(name, dcn, bidx, green_bits) \ struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB5x52RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ///////////////////////////////// Grayscale to Color //////////////////////////////// namespace color_detail { template struct Gray2RGB : unary_function::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator()(T src) const { typename TypeVec::vec_type dst; dst.z = dst.y = dst.x = src; setAlpha(dst, ColorChannel::max()); return dst; } __host__ __device__ __forceinline__ Gray2RGB() {} __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} }; template <> struct Gray2RGB : unary_function { __device__ __forceinline__ uint operator()(uint src) const { uint dst = 0xffu << 24; dst |= src; dst |= src << 8; dst |= src << 16; return dst; } __host__ __device__ __forceinline__ Gray2RGB() {} __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(name, dcn) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::Gray2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { template struct Gray2RGB5x5Converter; template<> struct Gray2RGB5x5Converter<6> { static __device__ __forceinline__ ushort cvt(uint t) { return (ushort)((t >> 3) | ((t & ~3) << 3) | ((t & ~7) << 8)); } }; template<> struct Gray2RGB5x5Converter<5> { static __device__ __forceinline__ ushort cvt(uint t) { t >>= 3; return (ushort)(t | (t << 5) | (t << 10)); } }; template struct Gray2RGB5x5 : unary_function { __device__ __forceinline__ ushort operator()(uint src) const { return Gray2RGB5x5Converter::cvt(src); } __host__ __device__ __forceinline__ Gray2RGB5x5() {} __host__ __device__ __forceinline__ Gray2RGB5x5(const Gray2RGB5x5&) {} }; } #define OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(name, green_bits) \ struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::Gray2RGB5x5 functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ///////////////////////////////// Color to Grayscale //////////////////////////////// namespace color_detail { template struct RGB5x52GrayConverter; template <> struct RGB5x52GrayConverter<6> { static __device__ __forceinline__ uchar cvt(uint t) { return (uchar)CV_DESCALE(((t << 3) & 0xf8) * B2Y + ((t >> 3) & 0xfc) * G2Y + ((t >> 8) & 0xf8) * R2Y, yuv_shift); } }; template <> struct RGB5x52GrayConverter<5> { static __device__ __forceinline__ uchar cvt(uint t) { return (uchar)CV_DESCALE(((t << 3) & 0xf8) * B2Y + ((t >> 2) & 0xf8) * G2Y + ((t >> 7) & 0xf8) * R2Y, yuv_shift); } }; template struct RGB5x52Gray : unary_function { __device__ __forceinline__ uchar operator()(uint src) const { return RGB5x52GrayConverter::cvt(src); } __host__ __device__ __forceinline__ RGB5x52Gray() {} __host__ __device__ __forceinline__ RGB5x52Gray(const RGB5x52Gray&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(name, green_bits) \ struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB5x52Gray functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { template static __device__ __forceinline__ T RGB2GrayConvert(const T* src) { return (T)CV_DESCALE((unsigned)(src[bidx] * B2Y + src[1] * G2Y + src[bidx^2] * R2Y), yuv_shift); } template static __device__ __forceinline__ uchar RGB2GrayConvert(uint src) { uint b = 0xffu & (src >> (bidx * 8)); uint g = 0xffu & (src >> 8); uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); return CV_DESCALE((uint)(b * B2Y + g * G2Y + r * R2Y), yuv_shift); } template static __device__ __forceinline__ float RGB2GrayConvert(const float* src) { return src[bidx] * 0.114f + src[1] * 0.587f + src[bidx^2] * 0.299f; } template struct RGB2Gray : unary_function::vec_type, T> { __device__ __forceinline__ T operator()(const typename TypeVec::vec_type& src) const { return RGB2GrayConvert(&src.x); } __host__ __device__ __forceinline__ RGB2Gray() {} __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} }; template struct RGB2Gray : unary_function { __device__ __forceinline__ uchar operator()(uint src) const { return RGB2GrayConvert(src); } __host__ __device__ __forceinline__ RGB2Gray() {} __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(name, scn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2Gray functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ///////////////////////////////////// RGB <-> YUV ////////////////////////////////////// namespace color_detail { __constant__ float c_RGB2YUVCoeffs_f[5] = { 0.114f, 0.587f, 0.299f, 0.492f, 0.877f }; __constant__ int c_RGB2YUVCoeffs_i[5] = { B2Y, G2Y, R2Y, 8061, 14369 }; template static __device__ void RGB2YUVConvert(const T* src, D& dst) { const int delta = ColorChannel::half() * (1 << yuv_shift); const int Y = CV_DESCALE(src[0] * c_RGB2YUVCoeffs_i[bidx^2] + src[1] * c_RGB2YUVCoeffs_i[1] + src[2] * c_RGB2YUVCoeffs_i[bidx], yuv_shift); const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YUVCoeffs_i[3] + delta, yuv_shift); const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YUVCoeffs_i[4] + delta, yuv_shift); dst.x = saturate_cast(Y); dst.y = saturate_cast(Cr); dst.z = saturate_cast(Cb); } template static __device__ __forceinline__ void RGB2YUVConvert(const float* src, D& dst) { dst.x = src[0] * c_RGB2YUVCoeffs_f[bidx^2] + src[1] * c_RGB2YUVCoeffs_f[1] + src[2] * c_RGB2YUVCoeffs_f[bidx]; dst.y = (src[bidx^2] - dst.x) * c_RGB2YUVCoeffs_f[3] + ColorChannel::half(); dst.z = (src[bidx] - dst.x) * c_RGB2YUVCoeffs_f[4] + ColorChannel::half(); } template struct RGB2YUV : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2YUVConvert(&src.x, dst); return dst; } __host__ __device__ __forceinline__ RGB2YUV() {} __host__ __device__ __forceinline__ RGB2YUV(const RGB2YUV&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2YUV functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { __constant__ float c_YUV2RGBCoeffs_f[5] = { 2.032f, -0.395f, -0.581f, 1.140f }; __constant__ int c_YUV2RGBCoeffs_i[5] = { 33292, -6472, -9519, 18678 }; template static __device__ void YUV2RGBConvert(const T& src, D* dst) { const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); dst[bidx] = saturate_cast(b); dst[1] = saturate_cast(g); dst[bidx^2] = saturate_cast(r); } template static __device__ uint YUV2RGBConvert(uint src) { const int x = 0xff & (src); const int y = 0xff & (src >> 8); const int z = 0xff & (src >> 16); const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] + (y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); uint dst = 0xffu << 24; dst |= saturate_cast(b) << (bidx * 8); dst |= saturate_cast(g) << 8; dst |= saturate_cast(r) << ((bidx ^ 2) * 8); return dst; } template static __device__ __forceinline__ void YUV2RGBConvert(const T& src, float* dst) { dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[3]; dst[1] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[2] + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[1]; dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[0]; } template struct YUV2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; YUV2RGBConvert(src, &dst.x); setAlpha(dst, ColorChannel::max()); return dst; } __host__ __device__ __forceinline__ YUV2RGB() {} __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} }; template struct YUV2RGB : unary_function { __device__ __forceinline__ uint operator ()(uint src) const { return YUV2RGBConvert(src); } __host__ __device__ __forceinline__ YUV2RGB() {} __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::YUV2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ///////////////////////////////////// RGB <-> YCrCb ////////////////////////////////////// namespace color_detail { __constant__ float c_RGB2YCrCbCoeffs_f[5] = {0.299f, 0.587f, 0.114f, 0.713f, 0.564f}; __constant__ int c_RGB2YCrCbCoeffs_i[5] = {R2Y, G2Y, B2Y, 11682, 9241}; template static __device__ void RGB2YCrCbConvert(const T* src, D& dst) { const int delta = ColorChannel::half() * (1 << yuv_shift); const int Y = CV_DESCALE(src[0] * c_RGB2YCrCbCoeffs_i[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_i[1] + src[2] * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); dst.x = saturate_cast(Y); dst.y = saturate_cast(Cr); dst.z = saturate_cast(Cb); } template static __device__ uint RGB2YCrCbConvert(uint src) { const int delta = ColorChannel::half() * (1 << yuv_shift); const int Y = CV_DESCALE((0xffu & src) * c_RGB2YCrCbCoeffs_i[bidx^2] + (0xffu & (src >> 8)) * c_RGB2YCrCbCoeffs_i[1] + (0xffu & (src >> 16)) * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); const int Cr = CV_DESCALE(((0xffu & (src >> ((bidx ^ 2) * 8))) - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); const int Cb = CV_DESCALE(((0xffu & (src >> (bidx * 8))) - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); uint dst = 0; dst |= saturate_cast(Y); dst |= saturate_cast(Cr) << 8; dst |= saturate_cast(Cb) << 16; return dst; } template static __device__ __forceinline__ void RGB2YCrCbConvert(const float* src, D& dst) { dst.x = src[0] * c_RGB2YCrCbCoeffs_f[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_f[1] + src[2] * c_RGB2YCrCbCoeffs_f[bidx]; dst.y = (src[bidx^2] - dst.x) * c_RGB2YCrCbCoeffs_f[3] + ColorChannel::half(); dst.z = (src[bidx] - dst.x) * c_RGB2YCrCbCoeffs_f[4] + ColorChannel::half(); } template struct RGB2YCrCb : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2YCrCbConvert(&src.x, dst); return dst; } __host__ __device__ __forceinline__ RGB2YCrCb() {} __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} }; template struct RGB2YCrCb : unary_function { __device__ __forceinline__ uint operator ()(uint src) const { return RGB2YCrCbConvert(src); } __host__ __device__ __forceinline__ RGB2YCrCb() {} __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2YCrCb functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { __constant__ float c_YCrCb2RGBCoeffs_f[5] = {1.403f, -0.714f, -0.344f, 1.773f}; __constant__ int c_YCrCb2RGBCoeffs_i[5] = {22987, -11698, -5636, 29049}; template static __device__ void YCrCb2RGBConvert(const T& src, D* dst) { const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); dst[bidx] = saturate_cast(b); dst[1] = saturate_cast(g); dst[bidx^2] = saturate_cast(r); } template static __device__ uint YCrCb2RGBConvert(uint src) { const int x = 0xff & (src); const int y = 0xff & (src >> 8); const int z = 0xff & (src >> 16); const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); uint dst = 0xffu << 24; dst |= saturate_cast(b) << (bidx * 8); dst |= saturate_cast(g) << 8; dst |= saturate_cast(r) << ((bidx ^ 2) * 8); return dst; } template __device__ __forceinline__ void YCrCb2RGBConvert(const T& src, float* dst) { dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[3]; dst[1] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[1]; dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[0]; } template struct YCrCb2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; YCrCb2RGBConvert(src, &dst.x); setAlpha(dst, ColorChannel::max()); return dst; } __host__ __device__ __forceinline__ YCrCb2RGB() {} __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} }; template struct YCrCb2RGB : unary_function { __device__ __forceinline__ uint operator ()(uint src) const { return YCrCb2RGBConvert(src); } __host__ __device__ __forceinline__ YCrCb2RGB() {} __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::YCrCb2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ////////////////////////////////////// RGB <-> XYZ /////////////////////////////////////// namespace color_detail { __constant__ float c_RGB2XYZ_D65f[9] = { 0.412453f, 0.357580f, 0.180423f, 0.212671f, 0.715160f, 0.072169f, 0.019334f, 0.119193f, 0.950227f }; __constant__ int c_RGB2XYZ_D65i[9] = { 1689, 1465, 739, 871, 2929, 296, 79, 488, 3892 }; template static __device__ __forceinline__ void RGB2XYZConvert(const T* src, D& dst) { dst.z = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[6] + src[1] * c_RGB2XYZ_D65i[7] + src[bidx] * c_RGB2XYZ_D65i[8], xyz_shift)); dst.x = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[0] + src[1] * c_RGB2XYZ_D65i[1] + src[bidx] * c_RGB2XYZ_D65i[2], xyz_shift)); dst.y = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[3] + src[1] * c_RGB2XYZ_D65i[4] + src[bidx] * c_RGB2XYZ_D65i[5], xyz_shift)); } template static __device__ __forceinline__ uint RGB2XYZConvert(uint src) { const uint b = 0xffu & (src >> (bidx * 8)); const uint g = 0xffu & (src >> 8); const uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); const uint x = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[0] + g * c_RGB2XYZ_D65i[1] + b * c_RGB2XYZ_D65i[2], xyz_shift)); const uint y = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[3] + g * c_RGB2XYZ_D65i[4] + b * c_RGB2XYZ_D65i[5], xyz_shift)); const uint z = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[6] + g * c_RGB2XYZ_D65i[7] + b * c_RGB2XYZ_D65i[8], xyz_shift)); uint dst = 0; dst |= x; dst |= y << 8; dst |= z << 16; return dst; } template static __device__ __forceinline__ void RGB2XYZConvert(const float* src, D& dst) { dst.x = src[bidx^2] * c_RGB2XYZ_D65f[0] + src[1] * c_RGB2XYZ_D65f[1] + src[bidx] * c_RGB2XYZ_D65f[2]; dst.y = src[bidx^2] * c_RGB2XYZ_D65f[3] + src[1] * c_RGB2XYZ_D65f[4] + src[bidx] * c_RGB2XYZ_D65f[5]; dst.z = src[bidx^2] * c_RGB2XYZ_D65f[6] + src[1] * c_RGB2XYZ_D65f[7] + src[bidx] * c_RGB2XYZ_D65f[8]; } template struct RGB2XYZ : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2XYZConvert(&src.x, dst); return dst; } __host__ __device__ __forceinline__ RGB2XYZ() {} __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} }; template struct RGB2XYZ : unary_function { __device__ __forceinline__ uint operator()(uint src) const { return RGB2XYZConvert(src); } __host__ __device__ __forceinline__ RGB2XYZ() {} __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2XYZ functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { __constant__ float c_XYZ2sRGB_D65f[9] = { 3.240479f, -1.53715f, -0.498535f, -0.969256f, 1.875991f, 0.041556f, 0.055648f, -0.204043f, 1.057311f }; __constant__ int c_XYZ2sRGB_D65i[9] = { 13273, -6296, -2042, -3970, 7684, 170, 228, -836, 4331 }; template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, D* dst) { dst[bidx^2] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[0] + src.y * c_XYZ2sRGB_D65i[1] + src.z * c_XYZ2sRGB_D65i[2], xyz_shift)); dst[1] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[3] + src.y * c_XYZ2sRGB_D65i[4] + src.z * c_XYZ2sRGB_D65i[5], xyz_shift)); dst[bidx] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[6] + src.y * c_XYZ2sRGB_D65i[7] + src.z * c_XYZ2sRGB_D65i[8], xyz_shift)); } template static __device__ __forceinline__ uint XYZ2RGBConvert(uint src) { const int x = 0xff & src; const int y = 0xff & (src >> 8); const int z = 0xff & (src >> 16); const uint r = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[0] + y * c_XYZ2sRGB_D65i[1] + z * c_XYZ2sRGB_D65i[2], xyz_shift)); const uint g = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[3] + y * c_XYZ2sRGB_D65i[4] + z * c_XYZ2sRGB_D65i[5], xyz_shift)); const uint b = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[6] + y * c_XYZ2sRGB_D65i[7] + z * c_XYZ2sRGB_D65i[8], xyz_shift)); uint dst = 0xffu << 24; dst |= b << (bidx * 8); dst |= g << 8; dst |= r << ((bidx ^ 2) * 8); return dst; } template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, float* dst) { dst[bidx^2] = src.x * c_XYZ2sRGB_D65f[0] + src.y * c_XYZ2sRGB_D65f[1] + src.z * c_XYZ2sRGB_D65f[2]; dst[1] = src.x * c_XYZ2sRGB_D65f[3] + src.y * c_XYZ2sRGB_D65f[4] + src.z * c_XYZ2sRGB_D65f[5]; dst[bidx] = src.x * c_XYZ2sRGB_D65f[6] + src.y * c_XYZ2sRGB_D65f[7] + src.z * c_XYZ2sRGB_D65f[8]; } template struct XYZ2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; XYZ2RGBConvert(src, &dst.x); setAlpha(dst, ColorChannel::max()); return dst; } __host__ __device__ __forceinline__ XYZ2RGB() {} __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} }; template struct XYZ2RGB : unary_function { __device__ __forceinline__ uint operator()(uint src) const { return XYZ2RGBConvert(src); } __host__ __device__ __forceinline__ XYZ2RGB() {} __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::XYZ2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ////////////////////////////////////// RGB <-> HSV /////////////////////////////////////// namespace color_detail { __constant__ int c_HsvDivTable [256] = {0, 1044480, 522240, 348160, 261120, 208896, 174080, 149211, 130560, 116053, 104448, 94953, 87040, 80345, 74606, 69632, 65280, 61440, 58027, 54973, 52224, 49737, 47476, 45412, 43520, 41779, 40172, 38684, 37303, 36017, 34816, 33693, 32640, 31651, 30720, 29842, 29013, 28229, 27486, 26782, 26112, 25475, 24869, 24290, 23738, 23211, 22706, 22223, 21760, 21316, 20890, 20480, 20086, 19707, 19342, 18991, 18651, 18324, 18008, 17703, 17408, 17123, 16846, 16579, 16320, 16069, 15825, 15589, 15360, 15137, 14921, 14711, 14507, 14308, 14115, 13926, 13743, 13565, 13391, 13221, 13056, 12895, 12738, 12584, 12434, 12288, 12145, 12006, 11869, 11736, 11605, 11478, 11353, 11231, 11111, 10995, 10880, 10768, 10658, 10550, 10445, 10341, 10240, 10141, 10043, 9947, 9854, 9761, 9671, 9582, 9495, 9410, 9326, 9243, 9162, 9082, 9004, 8927, 8852, 8777, 8704, 8632, 8561, 8492, 8423, 8356, 8290, 8224, 8160, 8097, 8034, 7973, 7913, 7853, 7795, 7737, 7680, 7624, 7569, 7514, 7461, 7408, 7355, 7304, 7253, 7203, 7154, 7105, 7057, 7010, 6963, 6917, 6872, 6827, 6782, 6739, 6695, 6653, 6611, 6569, 6528, 6487, 6447, 6408, 6369, 6330, 6292, 6254, 6217, 6180, 6144, 6108, 6073, 6037, 6003, 5968, 5935, 5901, 5868, 5835, 5803, 5771, 5739, 5708, 5677, 5646, 5615, 5585, 5556, 5526, 5497, 5468, 5440, 5412, 5384, 5356, 5329, 5302, 5275, 5249, 5222, 5196, 5171, 5145, 5120, 5095, 5070, 5046, 5022, 4998, 4974, 4950, 4927, 4904, 4881, 4858, 4836, 4813, 4791, 4769, 4748, 4726, 4705, 4684, 4663, 4642, 4622, 4601, 4581, 4561, 4541, 4522, 4502, 4483, 4464, 4445, 4426, 4407, 4389, 4370, 4352, 4334, 4316, 4298, 4281, 4263, 4246, 4229, 4212, 4195, 4178, 4161, 4145, 4128, 4112, 4096}; __constant__ int c_HsvDivTable180[256] = {0, 122880, 61440, 40960, 30720, 24576, 20480, 17554, 15360, 13653, 12288, 11171, 10240, 9452, 8777, 8192, 7680, 7228, 6827, 6467, 6144, 5851, 5585, 5343, 5120, 4915, 4726, 4551, 4389, 4237, 4096, 3964, 3840, 3724, 3614, 3511, 3413, 3321, 3234, 3151, 3072, 2997, 2926, 2858, 2793, 2731, 2671, 2614, 2560, 2508, 2458, 2409, 2363, 2318, 2276, 2234, 2194, 2156, 2119, 2083, 2048, 2014, 1982, 1950, 1920, 1890, 1862, 1834, 1807, 1781, 1755, 1731, 1707, 1683, 1661, 1638, 1617, 1596, 1575, 1555, 1536, 1517, 1499, 1480, 1463, 1446, 1429, 1412, 1396, 1381, 1365, 1350, 1336, 1321, 1307, 1293, 1280, 1267, 1254, 1241, 1229, 1217, 1205, 1193, 1182, 1170, 1159, 1148, 1138, 1127, 1117, 1107, 1097, 1087, 1078, 1069, 1059, 1050, 1041, 1033, 1024, 1016, 1007, 999, 991, 983, 975, 968, 960, 953, 945, 938, 931, 924, 917, 910, 904, 897, 890, 884, 878, 871, 865, 859, 853, 847, 842, 836, 830, 825, 819, 814, 808, 803, 798, 793, 788, 783, 778, 773, 768, 763, 759, 754, 749, 745, 740, 736, 731, 727, 723, 719, 714, 710, 706, 702, 698, 694, 690, 686, 683, 679, 675, 671, 668, 664, 661, 657, 654, 650, 647, 643, 640, 637, 633, 630, 627, 624, 621, 617, 614, 611, 608, 605, 602, 599, 597, 594, 591, 588, 585, 582, 580, 577, 574, 572, 569, 566, 564, 561, 559, 556, 554, 551, 549, 546, 544, 541, 539, 537, 534, 532, 530, 527, 525, 523, 521, 518, 516, 514, 512, 510, 508, 506, 504, 502, 500, 497, 495, 493, 492, 490, 488, 486, 484, 482}; __constant__ int c_HsvDivTable256[256] = {0, 174763, 87381, 58254, 43691, 34953, 29127, 24966, 21845, 19418, 17476, 15888, 14564, 13443, 12483, 11651, 10923, 10280, 9709, 9198, 8738, 8322, 7944, 7598, 7282, 6991, 6722, 6473, 6242, 6026, 5825, 5638, 5461, 5296, 5140, 4993, 4855, 4723, 4599, 4481, 4369, 4263, 4161, 4064, 3972, 3884, 3799, 3718, 3641, 3567, 3495, 3427, 3361, 3297, 3236, 3178, 3121, 3066, 3013, 2962, 2913, 2865, 2819, 2774, 2731, 2689, 2648, 2608, 2570, 2533, 2497, 2461, 2427, 2394, 2362, 2330, 2300, 2270, 2241, 2212, 2185, 2158, 2131, 2106, 2081, 2056, 2032, 2009, 1986, 1964, 1942, 1920, 1900, 1879, 1859, 1840, 1820, 1802, 1783, 1765, 1748, 1730, 1713, 1697, 1680, 1664, 1649, 1633, 1618, 1603, 1589, 1574, 1560, 1547, 1533, 1520, 1507, 1494, 1481, 1469, 1456, 1444, 1432, 1421, 1409, 1398, 1387, 1376, 1365, 1355, 1344, 1334, 1324, 1314, 1304, 1295, 1285, 1276, 1266, 1257, 1248, 1239, 1231, 1222, 1214, 1205, 1197, 1189, 1181, 1173, 1165, 1157, 1150, 1142, 1135, 1128, 1120, 1113, 1106, 1099, 1092, 1085, 1079, 1072, 1066, 1059, 1053, 1046, 1040, 1034, 1028, 1022, 1016, 1010, 1004, 999, 993, 987, 982, 976, 971, 966, 960, 955, 950, 945, 940, 935, 930, 925, 920, 915, 910, 906, 901, 896, 892, 887, 883, 878, 874, 869, 865, 861, 857, 853, 848, 844, 840, 836, 832, 828, 824, 820, 817, 813, 809, 805, 802, 798, 794, 791, 787, 784, 780, 777, 773, 770, 767, 763, 760, 757, 753, 750, 747, 744, 741, 737, 734, 731, 728, 725, 722, 719, 716, 713, 710, 708, 705, 702, 699, 696, 694, 691, 688, 685}; template static __device__ void RGB2HSVConvert(const uchar* src, D& dst) { const int hsv_shift = 12; const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; int b = src[bidx], g = src[1], r = src[bidx^2]; int h, s, v = b; int vmin = b, diff; int vr, vg; v = ::max(v, g); v = ::max(v, r); vmin = ::min(vmin, g); vmin = ::min(vmin, r); diff = v - vmin; vr = (v == r) * -1; vg = (v == g) * -1; s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; h += (h < 0) * hr; dst.x = saturate_cast(h); dst.y = (uchar)s; dst.z = (uchar)v; } template static __device__ uint RGB2HSVConvert(uint src) { const int hsv_shift = 12; const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; const int b = 0xff & (src >> (bidx * 8)); const int g = 0xff & (src >> 8); const int r = 0xff & (src >> ((bidx ^ 2) * 8)); int h, s, v = b; int vmin = b, diff; int vr, vg; v = ::max(v, g); v = ::max(v, r); vmin = ::min(vmin, g); vmin = ::min(vmin, r); diff = v - vmin; vr = (v == r) * -1; vg = (v == g) * -1; s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; h += (h < 0) * hr; uint dst = 0; dst |= saturate_cast(h); dst |= (0xffu & s) << 8; dst |= (0xffu & v) << 16; return dst; } template static __device__ void RGB2HSVConvert(const float* src, D& dst) { const float hscale = hr * (1.f / 360.f); float b = src[bidx], g = src[1], r = src[bidx^2]; float h, s, v; float vmin, diff; v = vmin = r; v = fmax(v, g); v = fmax(v, b); vmin = fmin(vmin, g); vmin = fmin(vmin, b); diff = v - vmin; s = diff / (float)(::fabs(v) + numeric_limits::epsilon()); diff = (float)(60. / (diff + numeric_limits::epsilon())); h = (v == r) * (g - b) * diff; h += (v != r && v == g) * ((b - r) * diff + 120.f); h += (v != r && v != g) * ((r - g) * diff + 240.f); h += (h < 0) * 360.f; dst.x = h * hscale; dst.y = s; dst.z = v; } template struct RGB2HSV : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2HSVConvert(&src.x, dst); return dst; } __host__ __device__ __forceinline__ RGB2HSV() {} __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} }; template struct RGB2HSV : unary_function { __device__ __forceinline__ uint operator()(uint src) const { return RGB2HSVConvert(src); } __host__ __device__ __forceinline__ RGB2HSV() {} __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { __constant__ int c_HsvSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; template static __device__ void HSV2RGBConvert(const T& src, float* dst) { const float hscale = 6.f / hr; float h = src.x, s = src.y, v = src.z; float b = v, g = v, r = v; if (s != 0) { h *= hscale; if( h < 0 ) do h += 6; while( h < 0 ); else if( h >= 6 ) do h -= 6; while( h >= 6 ); int sector = __float2int_rd(h); h -= sector; if ( (unsigned)sector >= 6u ) { sector = 0; h = 0.f; } float tab[4]; tab[0] = v; tab[1] = v * (1.f - s); tab[2] = v * (1.f - s * h); tab[3] = v * (1.f - s * (1.f - h)); b = tab[c_HsvSectorData[sector][0]]; g = tab[c_HsvSectorData[sector][1]]; r = tab[c_HsvSectorData[sector][2]]; } dst[bidx] = b; dst[1] = g; dst[bidx^2] = r; } template static __device__ void HSV2RGBConvert(const T& src, uchar* dst) { float3 buf; buf.x = src.x; buf.y = src.y * (1.f / 255.f); buf.z = src.z * (1.f / 255.f); HSV2RGBConvert(buf, &buf.x); dst[0] = saturate_cast(buf.x * 255.f); dst[1] = saturate_cast(buf.y * 255.f); dst[2] = saturate_cast(buf.z * 255.f); } template static __device__ uint HSV2RGBConvert(uint src) { float3 buf; buf.x = src & 0xff; buf.y = ((src >> 8) & 0xff) * (1.f/255.f); buf.z = ((src >> 16) & 0xff) * (1.f/255.f); HSV2RGBConvert(buf, &buf.x); uint dst = 0xffu << 24; dst |= saturate_cast(buf.x * 255.f); dst |= saturate_cast(buf.y * 255.f) << 8; dst |= saturate_cast(buf.z * 255.f) << 16; return dst; } template struct HSV2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; HSV2RGBConvert(src, &dst.x); setAlpha(dst, ColorChannel::max()); return dst; } __host__ __device__ __forceinline__ HSV2RGB() {} __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} }; template struct HSV2RGB : unary_function { __device__ __forceinline__ uint operator()(uint src) const { return HSV2RGBConvert(src); } __host__ __device__ __forceinline__ HSV2RGB() {} __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; /////////////////////////////////////// RGB <-> HLS //////////////////////////////////////// namespace color_detail { template static __device__ void RGB2HLSConvert(const float* src, D& dst) { const float hscale = hr * (1.f / 360.f); float b = src[bidx], g = src[1], r = src[bidx^2]; float h = 0.f, s = 0.f, l; float vmin, vmax, diff; vmax = vmin = r; vmax = fmax(vmax, g); vmax = fmax(vmax, b); vmin = fmin(vmin, g); vmin = fmin(vmin, b); diff = vmax - vmin; l = (vmax + vmin) * 0.5f; if (diff > numeric_limits::epsilon()) { s = (l < 0.5f) * diff / (vmax + vmin); s += (l >= 0.5f) * diff / (2.0f - vmax - vmin); diff = 60.f / diff; h = (vmax == r) * (g - b) * diff; h += (vmax != r && vmax == g) * ((b - r) * diff + 120.f); h += (vmax != r && vmax != g) * ((r - g) * diff + 240.f); h += (h < 0.f) * 360.f; } dst.x = h * hscale; dst.y = l; dst.z = s; } template static __device__ void RGB2HLSConvert(const uchar* src, D& dst) { float3 buf; buf.x = src[0] * (1.f / 255.f); buf.y = src[1] * (1.f / 255.f); buf.z = src[2] * (1.f / 255.f); RGB2HLSConvert(&buf.x, buf); dst.x = saturate_cast(buf.x); dst.y = saturate_cast(buf.y*255.f); dst.z = saturate_cast(buf.z*255.f); } template static __device__ uint RGB2HLSConvert(uint src) { float3 buf; buf.x = (0xff & src) * (1.f / 255.f); buf.y = (0xff & (src >> 8)) * (1.f / 255.f); buf.z = (0xff & (src >> 16)) * (1.f / 255.f); RGB2HLSConvert(&buf.x, buf); uint dst = 0xffu << 24; dst |= saturate_cast(buf.x); dst |= saturate_cast(buf.y * 255.f) << 8; dst |= saturate_cast(buf.z * 255.f) << 16; return dst; } template struct RGB2HLS : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2HLSConvert(&src.x, dst); return dst; } __host__ __device__ __forceinline__ RGB2HLS() {} __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} }; template struct RGB2HLS : unary_function { __device__ __forceinline__ uint operator()(uint src) const { return RGB2HLSConvert(src); } __host__ __device__ __forceinline__ RGB2HLS() {} __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { __constant__ int c_HlsSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; template static __device__ void HLS2RGBConvert(const T& src, float* dst) { const float hscale = 6.0f / hr; float h = src.x, l = src.y, s = src.z; float b = l, g = l, r = l; if (s != 0) { float p2 = (l <= 0.5f) * l * (1 + s); p2 += (l > 0.5f) * (l + s - l * s); float p1 = 2 * l - p2; h *= hscale; if( h < 0 ) do h += 6; while( h < 0 ); else if( h >= 6 ) do h -= 6; while( h >= 6 ); int sector; sector = __float2int_rd(h); h -= sector; float tab[4]; tab[0] = p2; tab[1] = p1; tab[2] = p1 + (p2 - p1) * (1 - h); tab[3] = p1 + (p2 - p1) * h; b = tab[c_HlsSectorData[sector][0]]; g = tab[c_HlsSectorData[sector][1]]; r = tab[c_HlsSectorData[sector][2]]; } dst[bidx] = b; dst[1] = g; dst[bidx^2] = r; } template static __device__ void HLS2RGBConvert(const T& src, uchar* dst) { float3 buf; buf.x = src.x; buf.y = src.y * (1.f / 255.f); buf.z = src.z * (1.f / 255.f); HLS2RGBConvert(buf, &buf.x); dst[0] = saturate_cast(buf.x * 255.f); dst[1] = saturate_cast(buf.y * 255.f); dst[2] = saturate_cast(buf.z * 255.f); } template static __device__ uint HLS2RGBConvert(uint src) { float3 buf; buf.x = 0xff & src; buf.y = (0xff & (src >> 8)) * (1.f / 255.f); buf.z = (0xff & (src >> 16)) * (1.f / 255.f); HLS2RGBConvert(buf, &buf.x); uint dst = 0xffu << 24; dst |= saturate_cast(buf.x * 255.f); dst |= saturate_cast(buf.y * 255.f) << 8; dst |= saturate_cast(buf.z * 255.f) << 16; return dst; } template struct HLS2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; HLS2RGBConvert(src, &dst.x); setAlpha(dst, ColorChannel::max()); return dst; } __host__ __device__ __forceinline__ HLS2RGB() {} __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} }; template struct HLS2RGB : unary_function { __device__ __forceinline__ uint operator()(uint src) const { return HLS2RGBConvert(src); } __host__ __device__ __forceinline__ HLS2RGB() {} __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(name, scn, dcn, bidx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; \ template <> struct name ## _full_traits \ { \ typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ///////////////////////////////////// RGB <-> Lab ///////////////////////////////////// namespace color_detail { enum { LAB_CBRT_TAB_SIZE = 1024, GAMMA_TAB_SIZE = 1024, lab_shift = xyz_shift, gamma_shift = 3, lab_shift2 = (lab_shift + gamma_shift), LAB_CBRT_TAB_SIZE_B = (256 * 3 / 2 * (1 << gamma_shift)) }; __constant__ ushort c_sRGBGammaTab_b[] = {0,1,1,2,2,3,4,4,5,6,6,7,8,8,9,10,11,11,12,13,14,15,16,17,19,20,21,22,24,25,26,28,29,31,33,34,36,38,40,41,43,45,47,49,51,54,56,58,60,63,65,68,70,73,75,78,81,83,86,89,92,95,98,101,105,108,111,115,118,121,125,129,132,136,140,144,147,151,155,160,164,168,172,176,181,185,190,194,199,204,209,213,218,223,228,233,239,244,249,255,260,265,271,277,282,288,294,300,306,312,318,324,331,337,343,350,356,363,370,376,383,390,397,404,411,418,426,433,440,448,455,463,471,478,486,494,502,510,518,527,535,543,552,560,569,578,586,595,604,613,622,631,641,650,659,669,678,688,698,707,717,727,737,747,757,768,778,788,799,809,820,831,842,852,863,875,886,897,908,920,931,943,954,966,978,990,1002,1014,1026,1038,1050,1063,1075,1088,1101,1113,1126,1139,1152,1165,1178,1192,1205,1218,1232,1245,1259,1273,1287,1301,1315,1329,1343,1357,1372,1386,1401,1415,1430,1445,1460,1475,1490,1505,1521,1536,1551,1567,1583,1598,1614,1630,1646,1662,1678,1695,1711,1728,1744,1761,1778,1794,1811,1828,1846,1863,1880,1897,1915,1933,1950,1968,1986,2004,2022,2040}; __device__ __forceinline__ int LabCbrt_b(int i) { float x = i * (1.f / (255.f * (1 << gamma_shift))); return (1 << lab_shift2) * (x < 0.008856f ? x * 7.787f + 0.13793103448275862f : ::cbrtf(x)); } template __device__ __forceinline__ void RGB2LabConvert_b(const T& src, D& dst) { const int Lscale = (116 * 255 + 50) / 100; const int Lshift = -((16 * 255 * (1 << lab_shift2) + 50) / 100); int B = blueIdx == 0 ? src.x : src.z; int G = src.y; int R = blueIdx == 0 ? src.z : src.x; if (srgb) { B = c_sRGBGammaTab_b[B]; G = c_sRGBGammaTab_b[G]; R = c_sRGBGammaTab_b[R]; } else { B <<= 3; G <<= 3; R <<= 3; } int fX = LabCbrt_b(CV_DESCALE(B * 778 + G * 1541 + R * 1777, lab_shift)); int fY = LabCbrt_b(CV_DESCALE(B * 296 + G * 2929 + R * 871, lab_shift)); int fZ = LabCbrt_b(CV_DESCALE(B * 3575 + G * 448 + R * 73, lab_shift)); int L = CV_DESCALE(Lscale * fY + Lshift, lab_shift2); int a = CV_DESCALE(500 * (fX - fY) + 128 * (1 << lab_shift2), lab_shift2); int b = CV_DESCALE(200 * (fY - fZ) + 128 * (1 << lab_shift2), lab_shift2); dst.x = saturate_cast(L); dst.y = saturate_cast(a); dst.z = saturate_cast(b); } __device__ __forceinline__ float splineInterpolate(float x, const float* tab, int n) { int ix = ::min(::max(int(x), 0), n-1); x -= ix; tab += ix * 4; return ((tab[3] * x + tab[2]) * x + tab[1]) * x + tab[0]; } __constant__ float c_sRGBGammaTab[] = {0,7.55853e-05,0.,-7.51331e-13,7.55853e-05,7.55853e-05,-2.25399e-12,3.75665e-12,0.000151171,7.55853e-05,9.01597e-12,-6.99932e-12,0.000226756,7.55853e-05,-1.1982e-11,2.41277e-12,0.000302341,7.55853e-05,-4.74369e-12,1.19001e-11,0.000377927,7.55853e-05,3.09568e-11,-2.09095e-11,0.000453512,7.55853e-05,-3.17718e-11,1.35303e-11,0.000529097,7.55853e-05,8.81905e-12,-4.10782e-12,0.000604683,7.55853e-05,-3.50439e-12,2.90097e-12,0.000680268,7.55853e-05,5.19852e-12,-7.49607e-12,0.000755853,7.55853e-05,-1.72897e-11,2.70833e-11,0.000831439,7.55854e-05,6.39602e-11,-4.26295e-11,0.000907024,7.55854e-05,-6.39282e-11,2.70193e-11,0.000982609,7.55853e-05,1.71298e-11,-7.24017e-12,0.00105819,7.55853e-05,-4.59077e-12,1.94137e-12,0.00113378,7.55853e-05,1.23333e-12,-5.25291e-13,0.00120937,7.55853e-05,-3.42545e-13,1.59799e-13,0.00128495,7.55853e-05,1.36852e-13,-1.13904e-13,0.00136054,7.55853e-05,-2.04861e-13,2.95818e-13,0.00143612,7.55853e-05,6.82594e-13,-1.06937e-12,0.00151171,7.55853e-05,-2.52551e-12,3.98166e-12,0.00158729,7.55853e-05,9.41946e-12,-1.48573e-11,0.00166288,7.55853e-05,-3.51523e-11,5.54474e-11,0.00173846,7.55854e-05,1.3119e-10,-9.0517e-11,0.00181405,7.55854e-05,-1.40361e-10,7.37899e-11,0.00188963,7.55853e-05,8.10085e-11,-8.82272e-11,0.00196522,7.55852e-05,-1.83673e-10,1.62704e-10,0.0020408,7.55853e-05,3.04438e-10,-2.13341e-10,0.00211639,7.55853e-05,-3.35586e-10,2.25e-10,0.00219197,7.55853e-05,3.39414e-10,-2.20997e-10,0.00226756,7.55853e-05,-3.23576e-10,1.93326e-10,0.00234315,7.55853e-05,2.564e-10,-8.66446e-11,0.00241873,7.55855e-05,-3.53328e-12,-7.9578e-11,0.00249432,7.55853e-05,-2.42267e-10,1.72126e-10,0.0025699,7.55853e-05,2.74111e-10,-1.43265e-10,0.00264549,7.55854e-05,-1.55683e-10,-6.47292e-11,0.00272107,7.55849e-05,-3.4987e-10,8.67842e-10,0.00279666,7.55868e-05,2.25366e-09,-3.8723e-09,0.00287224,7.55797e-05,-9.36325e-09,1.5087e-08,0.00294783,7.56063e-05,3.58978e-08,-5.69415e-08,0.00302341,7.55072e-05,-1.34927e-07,2.13144e-07,0.003099,7.58768e-05,5.04507e-07,1.38713e-07,0.00317552,7.7302e-05,9.20646e-07,-1.55186e-07,0.00325359,7.86777e-05,4.55087e-07,4.26813e-08,0.00333276,7.97159e-05,5.83131e-07,-1.06495e-08,0.00341305,8.08502e-05,5.51182e-07,3.87467e-09,0.00349446,8.19642e-05,5.62806e-07,-1.92586e-10,0.00357698,8.30892e-05,5.62228e-07,1.0866e-09,0.00366063,8.4217e-05,5.65488e-07,5.02818e-10,0.00374542,8.53494e-05,5.66997e-07,8.60211e-10,0.00383133,8.6486e-05,5.69577e-07,7.13044e-10,0.00391839,8.76273e-05,5.71716e-07,4.78527e-10,0.00400659,8.87722e-05,5.73152e-07,1.09818e-09,0.00409594,8.99218e-05,5.76447e-07,2.50964e-10,0.00418644,9.10754e-05,5.772e-07,1.15762e-09,0.00427809,9.22333e-05,5.80672e-07,2.40865e-10,0.0043709,9.33954e-05,5.81395e-07,1.13854e-09,0.00446488,9.45616e-05,5.84811e-07,3.27267e-10,0.00456003,9.57322e-05,5.85792e-07,8.1197e-10,0.00465635,9.69062e-05,5.88228e-07,6.15823e-10,0.00475384,9.80845e-05,5.90076e-07,9.15747e-10,0.00485252,9.92674e-05,5.92823e-07,3.778e-10,0.00495238,0.000100454,5.93956e-07,8.32623e-10,0.00505343,0.000101645,5.96454e-07,4.82695e-10,0.00515567,0.000102839,5.97902e-07,9.61904e-10,0.00525911,0.000104038,6.00788e-07,3.26281e-10,0.00536375,0.00010524,6.01767e-07,9.926e-10,0.00546959,0.000106447,6.04745e-07,3.59933e-10,0.00557664,0.000107657,6.05824e-07,8.2728e-10,0.0056849,0.000108871,6.08306e-07,5.21898e-10,0.00579438,0.00011009,6.09872e-07,8.10492e-10,0.00590508,0.000111312,6.12303e-07,4.27046e-10,0.00601701,0.000112538,6.13585e-07,7.40878e-10,0.00613016,0.000113767,6.15807e-07,8.00469e-10,0.00624454,0.000115001,6.18209e-07,2.48178e-10,0.00636016,0.000116238,6.18953e-07,1.00073e-09,0.00647702,0.000117479,6.21955e-07,4.05654e-10,0.00659512,0.000118724,6.23172e-07,6.36192e-10,0.00671447,0.000119973,6.25081e-07,7.74927e-10,0.00683507,0.000121225,6.27406e-07,4.54975e-10,0.00695692,0.000122481,6.28771e-07,6.64841e-10,0.00708003,0.000123741,6.30765e-07,6.10972e-10,0.00720441,0.000125004,6.32598e-07,6.16543e-10,0.00733004,0.000126271,6.34448e-07,6.48204e-10,0.00745695,0.000127542,6.36392e-07,5.15835e-10,0.00758513,0.000128816,6.3794e-07,5.48103e-10,0.00771458,0.000130094,6.39584e-07,1.01706e-09,0.00784532,0.000131376,6.42635e-07,4.0283e-11,0.00797734,0.000132661,6.42756e-07,6.84471e-10,0.00811064,0.000133949,6.4481e-07,9.47144e-10,0.00824524,0.000135241,6.47651e-07,1.83472e-10,0.00838112,0.000136537,6.48201e-07,1.11296e-09,0.00851831,0.000137837,6.5154e-07,2.13163e-11,0.0086568,0.00013914,6.51604e-07,6.64462e-10,0.00879659,0.000140445,6.53598e-07,1.04613e-09,0.00893769,0.000141756,6.56736e-07,-1.92377e-10,0.0090801,0.000143069,6.56159e-07,1.58601e-09,0.00922383,0.000144386,6.60917e-07,-5.63754e-10,0.00936888,0.000145706,6.59226e-07,1.60033e-09,0.00951524,0.000147029,6.64027e-07,-2.49543e-10,0.00966294,0.000148356,6.63278e-07,1.26043e-09,0.00981196,0.000149687,6.67059e-07,-1.35572e-10,0.00996231,0.00015102,6.66653e-07,1.14458e-09,0.010114,0.000152357,6.70086e-07,2.13864e-10,0.010267,0.000153698,6.70728e-07,7.93856e-10,0.0104214,0.000155042,6.73109e-07,3.36077e-10,0.0105771,0.000156389,6.74118e-07,6.55765e-10,0.0107342,0.000157739,6.76085e-07,7.66211e-10,0.0108926,0.000159094,6.78384e-07,4.66116e-12,0.0110524,0.000160451,6.78398e-07,1.07775e-09,0.0112135,0.000161811,6.81631e-07,3.41023e-10,0.011376,0.000163175,6.82654e-07,3.5205e-10,0.0115398,0.000164541,6.8371e-07,1.04473e-09,0.0117051,0.000165912,6.86844e-07,1.25757e-10,0.0118717,0.000167286,6.87222e-07,3.14818e-10,0.0120396,0.000168661,6.88166e-07,1.40886e-09,0.012209,0.000170042,6.92393e-07,-3.62244e-10,0.0123797,0.000171425,6.91306e-07,9.71397e-10,0.0125518,0.000172811,6.9422e-07,2.02003e-10,0.0127253,0.0001742,6.94826e-07,1.01448e-09,0.0129002,0.000175593,6.97869e-07,3.96653e-10,0.0130765,0.00017699,6.99059e-07,1.92927e-10,0.0132542,0.000178388,6.99638e-07,6.94305e-10,0.0134333,0.00017979,7.01721e-07,7.55108e-10,0.0136138,0.000181195,7.03986e-07,1.05918e-11,0.0137957,0.000182603,7.04018e-07,1.06513e-09,0.013979,0.000184015,7.07214e-07,3.85512e-10,0.0141637,0.00018543,7.0837e-07,1.86769e-10,0.0143499,0.000186848,7.0893e-07,7.30116e-10,0.0145374,0.000188268,7.11121e-07,6.17983e-10,0.0147264,0.000189692,7.12975e-07,5.23282e-10,0.0149168,0.000191119,7.14545e-07,8.28398e-11,0.0151087,0.000192549,7.14793e-07,1.0081e-09,0.0153019,0.000193981,7.17817e-07,5.41244e-10,0.0154966,0.000195418,7.19441e-07,-3.7907e-10,0.0156928,0.000196856,7.18304e-07,1.90641e-09,0.0158903,0.000198298,7.24023e-07,-7.27387e-10,0.0160893,0.000199744,7.21841e-07,1.00317e-09,0.0162898,0.000201191,7.24851e-07,4.39949e-10,0.0164917,0.000202642,7.2617e-07,9.6234e-10,0.0166951,0.000204097,7.29057e-07,-5.64019e-10,0.0168999,0.000205554,7.27365e-07,1.29374e-09,0.0171062,0.000207012,7.31247e-07,9.77025e-10,0.017314,0.000208478,7.34178e-07,-1.47651e-09,0.0175232,0.000209942,7.29748e-07,3.06636e-09,0.0177338,0.00021141,7.38947e-07,-1.47573e-09,0.017946,0.000212884,7.3452e-07,9.7386e-10,0.0181596,0.000214356,7.37442e-07,1.30562e-09,0.0183747,0.000215835,7.41358e-07,-6.08376e-10,0.0185913,0.000217315,7.39533e-07,1.12785e-09,0.0188093,0.000218798,7.42917e-07,-1.77711e-10,0.0190289,0.000220283,7.42384e-07,1.44562e-09,0.0192499,0.000221772,7.46721e-07,-1.68825e-11,0.0194724,0.000223266,7.4667e-07,4.84533e-10,0.0196964,0.000224761,7.48124e-07,-5.85298e-11,0.0199219,0.000226257,7.47948e-07,1.61217e-09,0.0201489,0.000227757,7.52785e-07,-8.02136e-10,0.0203775,0.00022926,7.50378e-07,1.59637e-09,0.0206075,0.000230766,7.55167e-07,4.47168e-12,0.020839,0.000232276,7.55181e-07,2.48387e-10,0.021072,0.000233787,7.55926e-07,8.6474e-10,0.0213066,0.000235302,7.5852e-07,1.78299e-11,0.0215426,0.000236819,7.58573e-07,9.26567e-10,0.0217802,0.000238339,7.61353e-07,1.34529e-12,0.0220193,0.000239862,7.61357e-07,9.30659e-10,0.0222599,0.000241387,7.64149e-07,1.34529e-12,0.0225021,0.000242915,7.64153e-07,9.26567e-10,0.0227458,0.000244447,7.66933e-07,1.76215e-11,0.022991,0.00024598,7.66986e-07,8.65536e-10,0.0232377,0.000247517,7.69582e-07,2.45677e-10,0.023486,0.000249057,7.70319e-07,1.44193e-11,0.0237358,0.000250598,7.70363e-07,1.55918e-09,0.0239872,0.000252143,7.7504e-07,-6.63173e-10,0.0242401,0.000253691,7.73051e-07,1.09357e-09,0.0244946,0.000255241,7.76331e-07,1.41919e-11,0.0247506,0.000256793,7.76374e-07,7.12248e-10,0.0250082,0.000258348,7.78511e-07,8.62049e-10,0.0252673,0.000259908,7.81097e-07,-4.35061e-10,0.025528,0.000261469,7.79792e-07,8.7825e-10,0.0257902,0.000263031,7.82426e-07,6.47181e-10,0.0260541,0.000264598,7.84368e-07,2.58448e-10,0.0263194,0.000266167,7.85143e-07,1.81558e-10,0.0265864,0.000267738,7.85688e-07,8.78041e-10,0.0268549,0.000269312,7.88322e-07,3.15102e-11,0.027125,0.000270889,7.88417e-07,8.58525e-10,0.0273967,0.000272468,7.90992e-07,2.59812e-10,0.02767,0.000274051,7.91772e-07,-3.5224e-11,0.0279448,0.000275634,7.91666e-07,1.74377e-09,0.0282212,0.000277223,7.96897e-07,-1.35196e-09,0.0284992,0.000278813,7.92841e-07,1.80141e-09,0.0287788,0.000280404,7.98246e-07,-2.65629e-10,0.0290601,0.000281999,7.97449e-07,1.12374e-09,0.0293428,0.000283598,8.0082e-07,-5.04106e-10,0.0296272,0.000285198,7.99308e-07,8.92764e-10,0.0299132,0.000286799,8.01986e-07,6.58379e-10,0.0302008,0.000288405,8.03961e-07,1.98971e-10,0.0304901,0.000290014,8.04558e-07,4.08382e-10,0.0307809,0.000291624,8.05783e-07,3.01839e-11,0.0310733,0.000293236,8.05874e-07,1.33343e-09,0.0313673,0.000294851,8.09874e-07,2.2419e-10,0.031663,0.000296472,8.10547e-07,-3.67606e-10,0.0319603,0.000298092,8.09444e-07,1.24624e-09,0.0322592,0.000299714,8.13182e-07,-8.92025e-10,0.0325597,0.000301338,8.10506e-07,2.32183e-09,0.0328619,0.000302966,8.17472e-07,-9.44719e-10,0.0331657,0.000304598,8.14638e-07,1.45703e-09,0.0334711,0.000306232,8.19009e-07,-1.15805e-09,0.0337781,0.000307866,8.15535e-07,3.17507e-09,0.0340868,0.000309507,8.2506e-07,-4.09161e-09,0.0343971,0.000311145,8.12785e-07,5.74079e-09,0.0347091,0.000312788,8.30007e-07,-3.97034e-09,0.0350227,0.000314436,8.18096e-07,2.68985e-09,0.035338,0.00031608,8.26166e-07,6.61676e-10,0.0356549,0.000317734,8.28151e-07,-1.61123e-09,0.0359734,0.000319386,8.23317e-07,2.05786e-09,0.0362936,0.000321038,8.29491e-07,8.30388e-10,0.0366155,0.0003227,8.31982e-07,-1.65424e-09,0.036939,0.000324359,8.27019e-07,2.06129e-09,0.0372642,0.000326019,8.33203e-07,8.59719e-10,0.0375911,0.000327688,8.35782e-07,-1.77488e-09,0.0379196,0.000329354,8.30458e-07,2.51464e-09,0.0382498,0.000331023,8.38002e-07,-8.33135e-10,0.0385817,0.000332696,8.35502e-07,8.17825e-10,0.0389152,0.00033437,8.37956e-07,1.28718e-09,0.0392504,0.00033605,8.41817e-07,-2.2413e-09,0.0395873,0.000337727,8.35093e-07,3.95265e-09,0.0399258,0.000339409,8.46951e-07,-2.39332e-09,0.0402661,0.000341095,8.39771e-07,1.89533e-09,0.040608,0.000342781,8.45457e-07,-1.46271e-09,0.0409517,0.000344467,8.41069e-07,3.95554e-09,0.041297,0.000346161,8.52936e-07,-3.18369e-09,0.041644,0.000347857,8.43385e-07,1.32873e-09,0.0419927,0.000349548,8.47371e-07,1.59402e-09,0.0423431,0.000351248,8.52153e-07,-2.54336e-10,0.0426952,0.000352951,8.5139e-07,-5.76676e-10,0.043049,0.000354652,8.4966e-07,2.56114e-09,0.0434045,0.000356359,8.57343e-07,-2.21744e-09,0.0437617,0.000358067,8.50691e-07,2.58344e-09,0.0441206,0.000359776,8.58441e-07,-6.65826e-10,0.0444813,0.000361491,8.56444e-07,7.99218e-11,0.0448436,0.000363204,8.56684e-07,3.46063e-10,0.0452077,0.000364919,8.57722e-07,2.26116e-09,0.0455734,0.000366641,8.64505e-07,-1.94005e-09,0.045941,0.000368364,8.58685e-07,1.77384e-09,0.0463102,0.000370087,8.64007e-07,-1.43005e-09,0.0466811,0.000371811,8.59717e-07,3.94634e-09,0.0470538,0.000373542,8.71556e-07,-3.17946e-09,0.0474282,0.000375276,8.62017e-07,1.32104e-09,0.0478043,0.000377003,8.6598e-07,1.62045e-09,0.0481822,0.00037874,8.70842e-07,-3.52297e-10,0.0485618,0.000380481,8.69785e-07,-2.11211e-10,0.0489432,0.00038222,8.69151e-07,1.19716e-09,0.0493263,0.000383962,8.72743e-07,-8.52026e-10,0.0497111,0.000385705,8.70187e-07,2.21092e-09,0.0500977,0.000387452,8.76819e-07,-5.41339e-10,0.050486,0.000389204,8.75195e-07,-4.5361e-11,0.0508761,0.000390954,8.75059e-07,7.22669e-10,0.0512679,0.000392706,8.77227e-07,8.79936e-10,0.0516615,0.000394463,8.79867e-07,-5.17048e-10,0.0520568,0.000396222,8.78316e-07,1.18833e-09,0.0524539,0.000397982,8.81881e-07,-5.11022e-10,0.0528528,0.000399744,8.80348e-07,8.55683e-10,0.0532534,0.000401507,8.82915e-07,8.13562e-10,0.0536558,0.000403276,8.85356e-07,-3.84603e-10,0.05406,0.000405045,8.84202e-07,7.24962e-10,0.0544659,0.000406816,8.86377e-07,1.20986e-09,0.0548736,0.000408592,8.90006e-07,-1.83896e-09,0.0552831,0.000410367,8.84489e-07,2.42071e-09,0.0556944,0.000412143,8.91751e-07,-3.93413e-10,0.0561074,0.000413925,8.90571e-07,-8.46967e-10,0.0565222,0.000415704,8.8803e-07,3.78122e-09,0.0569388,0.000417491,8.99374e-07,-3.1021e-09,0.0573572,0.000419281,8.90068e-07,1.17658e-09,0.0577774,0.000421064,8.93597e-07,2.12117e-09,0.0581993,0.000422858,8.99961e-07,-2.21068e-09,0.0586231,0.000424651,8.93329e-07,2.9961e-09,0.0590486,0.000426447,9.02317e-07,-2.32311e-09,0.059476,0.000428244,8.95348e-07,2.57122e-09,0.0599051,0.000430043,9.03062e-07,-5.11098e-10,0.0603361,0.000431847,9.01528e-07,-5.27166e-10,0.0607688,0.000433649,8.99947e-07,2.61984e-09,0.0612034,0.000435457,9.07806e-07,-2.50141e-09,0.0616397,0.000437265,9.00302e-07,3.66045e-09,0.0620779,0.000439076,9.11283e-07,-4.68977e-09,0.0625179,0.000440885,8.97214e-07,7.64783e-09,0.0629597,0.000442702,9.20158e-07,-7.27499e-09,0.0634033,0.000444521,8.98333e-07,6.55113e-09,0.0638487,0.000446337,9.17986e-07,-4.02844e-09,0.0642959,0.000448161,9.05901e-07,2.11196e-09,0.064745,0.000449979,9.12236e-07,3.03125e-09,0.0651959,0.000451813,9.2133e-07,-6.78648e-09,0.0656486,0.000453635,9.00971e-07,9.21375e-09,0.0661032,0.000455464,9.28612e-07,-7.71684e-09,0.0665596,0.000457299,9.05462e-07,6.7522e-09,0.0670178,0.00045913,9.25718e-07,-4.3907e-09,0.0674778,0.000460968,9.12546e-07,3.36e-09,0.0679397,0.000462803,9.22626e-07,-1.59876e-09,0.0684034,0.000464644,9.1783e-07,3.0351e-09,0.068869,0.000466488,9.26935e-07,-3.09101e-09,0.0693364,0.000468333,9.17662e-07,1.8785e-09,0.0698057,0.000470174,9.23298e-07,3.02733e-09,0.0702768,0.00047203,9.3238e-07,-6.53722e-09,0.0707497,0.000473875,9.12768e-07,8.22054e-09,0.0712245,0.000475725,9.37429e-07,-3.99325e-09,0.0717012,0.000477588,9.2545e-07,3.01839e-10,0.0721797,0.00047944,9.26355e-07,2.78597e-09,0.0726601,0.000481301,9.34713e-07,-3.99507e-09,0.0731423,0.000483158,9.22728e-07,5.7435e-09,0.0736264,0.000485021,9.39958e-07,-4.07776e-09,0.0741123,0.000486888,9.27725e-07,3.11695e-09,0.0746002,0.000488753,9.37076e-07,-9.39394e-10,0.0750898,0.000490625,9.34258e-07,6.4055e-10,0.0755814,0.000492495,9.3618e-07,-1.62265e-09,0.0760748,0.000494363,9.31312e-07,5.84995e-09,0.0765701,0.000496243,9.48861e-07,-6.87601e-09,0.0770673,0.00049812,9.28233e-07,6.75296e-09,0.0775664,0.000499997,9.48492e-07,-5.23467e-09,0.0780673,0.000501878,9.32788e-07,6.73523e-09,0.0785701,0.000503764,9.52994e-07,-6.80514e-09,0.0790748,0.000505649,9.32578e-07,5.5842e-09,0.0795814,0.000507531,9.49331e-07,-6.30583e-10,0.0800899,0.000509428,9.47439e-07,-3.0618e-09,0.0806003,0.000511314,9.38254e-07,5.4273e-09,0.0811125,0.000513206,9.54536e-07,-3.74627e-09,0.0816267,0.000515104,9.43297e-07,2.10713e-09,0.0821427,0.000516997,9.49618e-07,2.76839e-09,0.0826607,0.000518905,9.57924e-07,-5.73006e-09,0.0831805,0.000520803,9.40733e-07,5.25072e-09,0.0837023,0.0005227,9.56486e-07,-3.71718e-10,0.084226,0.000524612,9.5537e-07,-3.76404e-09,0.0847515,0.000526512,9.44078e-07,7.97735e-09,0.085279,0.000528424,9.6801e-07,-5.79367e-09,0.0858084,0.000530343,9.50629e-07,2.96268e-10,0.0863397,0.000532245,9.51518e-07,4.6086e-09,0.0868729,0.000534162,9.65344e-07,-3.82947e-09,0.087408,0.000536081,9.53856e-07,3.25861e-09,0.087945,0.000537998,9.63631e-07,-1.7543e-09,0.088484,0.00053992,9.58368e-07,3.75849e-09,0.0890249,0.000541848,9.69644e-07,-5.82891e-09,0.0895677,0.00054377,9.52157e-07,4.65593e-09,0.0901124,0.000545688,9.66125e-07,2.10643e-09,0.0906591,0.000547627,9.72444e-07,-5.63099e-09,0.0912077,0.000549555,9.55551e-07,5.51627e-09,0.0917582,0.000551483,9.721e-07,-1.53292e-09,0.0923106,0.000553422,9.67501e-07,6.15311e-10,0.092865,0.000555359,9.69347e-07,-9.28291e-10,0.0934213,0.000557295,9.66562e-07,3.09774e-09,0.0939796,0.000559237,9.75856e-07,-4.01186e-09,0.0945398,0.000561177,9.6382e-07,5.49892e-09,0.095102,0.000563121,9.80317e-07,-3.08258e-09,0.0956661,0.000565073,9.71069e-07,-6.19176e-10,0.0962321,0.000567013,9.69212e-07,5.55932e-09,0.0968001,0.000568968,9.8589e-07,-6.71704e-09,0.09737,0.00057092,9.65738e-07,6.40762e-09,0.0979419,0.00057287,9.84961e-07,-4.0122e-09,0.0985158,0.000574828,9.72925e-07,2.19059e-09,0.0990916,0.000576781,9.79496e-07,2.70048e-09,0.0996693,0.000578748,9.87598e-07,-5.54193e-09,0.100249,0.000580706,9.70972e-07,4.56597e-09,0.100831,0.000582662,9.8467e-07,2.17923e-09,0.101414,0.000584638,9.91208e-07,-5.83232e-09,0.102,0.000586603,9.73711e-07,6.24884e-09,0.102588,0.000588569,9.92457e-07,-4.26178e-09,0.103177,0.000590541,9.79672e-07,3.34781e-09,0.103769,0.00059251,9.89715e-07,-1.67904e-09,0.104362,0.000594485,9.84678e-07,3.36839e-09,0.104958,0.000596464,9.94783e-07,-4.34397e-09,0.105555,0.000598441,9.81751e-07,6.55696e-09,0.106155,0.000600424,1.00142e-06,-6.98272e-09,0.106756,0.000602406,9.80474e-07,6.4728e-09,0.107359,0.000604386,9.99893e-07,-4.00742e-09,0.107965,0.000606374,9.8787e-07,2.10654e-09,0.108572,0.000608356,9.9419e-07,3.0318e-09,0.109181,0.000610353,1.00329e-06,-6.7832e-09,0.109793,0.00061234,9.82936e-07,9.1998e-09,0.110406,0.000614333,1.01054e-06,-7.6642e-09,0.111021,0.000616331,9.87543e-07,6.55579e-09,0.111639,0.000618326,1.00721e-06,-3.65791e-09,0.112258,0.000620329,9.96236e-07,6.25467e-10,0.112879,0.000622324,9.98113e-07,1.15593e-09,0.113503,0.000624323,1.00158e-06,2.20158e-09,0.114128,0.000626333,1.00819e-06,-2.51191e-09,0.114755,0.000628342,1.00065e-06,3.95517e-10,0.115385,0.000630345,1.00184e-06,9.29807e-10,0.116016,0.000632351,1.00463e-06,3.33599e-09,0.116649,0.00063437,1.01463e-06,-6.82329e-09,0.117285,0.000636379,9.94163e-07,9.05595e-09,0.117922,0.000638395,1.02133e-06,-7.04862e-09,0.118562,0.000640416,1.00019e-06,4.23737e-09,0.119203,0.000642429,1.0129e-06,-2.45033e-09,0.119847,0.000644448,1.00555e-06,5.56395e-09,0.120492,0.000646475,1.02224e-06,-4.9043e-09,0.121139,0.000648505,1.00753e-06,-8.47952e-10,0.121789,0.000650518,1.00498e-06,8.29622e-09,0.122441,0.000652553,1.02987e-06,-9.98538e-09,0.123094,0.000654582,9.99914e-07,9.2936e-09,0.12375,0.00065661,1.02779e-06,-4.83707e-09,0.124407,0.000658651,1.01328e-06,2.60411e-09,0.125067,0.000660685,1.0211e-06,-5.57945e-09,0.125729,0.000662711,1.00436e-06,1.22631e-08,0.126392,0.000664756,1.04115e-06,-1.36704e-08,0.127058,0.000666798,1.00014e-06,1.26161e-08,0.127726,0.000668836,1.03798e-06,-6.99155e-09,0.128396,0.000670891,1.01701e-06,4.48836e-10,0.129068,0.000672926,1.01836e-06,5.19606e-09,0.129742,0.000674978,1.03394e-06,-6.3319e-09,0.130418,0.000677027,1.01495e-06,5.2305e-09,0.131096,0.000679073,1.03064e-06,3.11123e-10,0.131776,0.000681135,1.03157e-06,-6.47511e-09,0.132458,0.000683179,1.01215e-06,1.06882e-08,0.133142,0.000685235,1.04421e-06,-6.47519e-09,0.133829,0.000687304,1.02479e-06,3.11237e-10,0.134517,0.000689355,1.02572e-06,5.23035e-09,0.135207,0.000691422,1.04141e-06,-6.3316e-09,0.1359,0.000693486,1.02242e-06,5.19484e-09,0.136594,0.000695546,1.038e-06,4.53497e-10,0.137291,0.000697623,1.03936e-06,-7.00891e-09,0.137989,0.000699681,1.01834e-06,1.2681e-08,0.13869,0.000701756,1.05638e-06,-1.39128e-08,0.139393,0.000703827,1.01464e-06,1.31679e-08,0.140098,0.000705896,1.05414e-06,-8.95659e-09,0.140805,0.000707977,1.02727e-06,7.75742e-09,0.141514,0.000710055,1.05055e-06,-7.17182e-09,0.142225,0.000712135,1.02903e-06,6.02862e-09,0.142938,0.000714211,1.04712e-06,-2.04163e-09,0.143653,0.000716299,1.04099e-06,2.13792e-09,0.144371,0.000718387,1.04741e-06,-6.51009e-09,0.14509,0.000720462,1.02787e-06,9.00123e-09,0.145812,0.000722545,1.05488e-06,3.07523e-10,0.146535,0.000724656,1.0558e-06,-1.02312e-08,0.147261,0.000726737,1.02511e-06,1.0815e-08,0.147989,0.000728819,1.05755e-06,-3.22681e-09,0.148719,0.000730925,1.04787e-06,2.09244e-09,0.14945,0.000733027,1.05415e-06,-5.143e-09,0.150185,0.00073512,1.03872e-06,3.57844e-09,0.150921,0.000737208,1.04946e-06,5.73027e-09,0.151659,0.000739324,1.06665e-06,-1.15983e-08,0.152399,0.000741423,1.03185e-06,1.08605e-08,0.153142,0.000743519,1.06443e-06,-2.04106e-09,0.153886,0.000745642,1.05831e-06,-2.69642e-09,0.154633,0.00074775,1.05022e-06,-2.07425e-09,0.155382,0.000749844,1.044e-06,1.09934e-08,0.156133,0.000751965,1.07698e-06,-1.20972e-08,0.156886,0.000754083,1.04069e-06,7.59288e-09,0.157641,0.000756187,1.06347e-06,-3.37305e-09,0.158398,0.000758304,1.05335e-06,5.89921e-09,0.159158,0.000760428,1.07104e-06,-5.32248e-09,0.159919,0.000762554,1.05508e-06,4.8927e-10,0.160683,0.000764666,1.05654e-06,3.36547e-09,0.161448,0.000766789,1.06664e-06,9.50081e-10,0.162216,0.000768925,1.06949e-06,-7.16568e-09,0.162986,0.000771043,1.04799e-06,1.28114e-08,0.163758,0.000773177,1.08643e-06,-1.42774e-08,0.164533,0.000775307,1.0436e-06,1.44956e-08,0.165309,0.000777438,1.08708e-06,-1.39025e-08,0.166087,0.00077957,1.04538e-06,1.13118e-08,0.166868,0.000781695,1.07931e-06,-1.54224e-09,0.167651,0.000783849,1.07468e-06,-5.14312e-09,0.168436,0.000785983,1.05925e-06,7.21381e-09,0.169223,0.000788123,1.0809e-06,-8.81096e-09,0.170012,0.000790259,1.05446e-06,1.31289e-08,0.170803,0.000792407,1.09385e-06,-1.39022e-08,0.171597,0.000794553,1.05214e-06,1.26775e-08,0.172392,0.000796695,1.09018e-06,-7.00557e-09,0.17319,0.000798855,1.06916e-06,4.43796e-10,0.17399,0.000800994,1.07049e-06,5.23031e-09,0.174792,0.000803151,1.08618e-06,-6.46397e-09,0.175596,0.000805304,1.06679e-06,5.72444e-09,0.176403,0.000807455,1.08396e-06,-1.53254e-09,0.177211,0.000809618,1.07937e-06,4.05673e-10,0.178022,0.000811778,1.08058e-06,-9.01916e-11,0.178835,0.000813939,1.08031e-06,-4.49821e-11,0.17965,0.000816099,1.08018e-06,2.70234e-10,0.180467,0.00081826,1.08099e-06,-1.03603e-09,0.181286,0.000820419,1.07788e-06,3.87392e-09,0.182108,0.000822587,1.0895e-06,4.41522e-10,0.182932,0.000824767,1.09083e-06,-5.63997e-09,0.183758,0.000826932,1.07391e-06,7.21707e-09,0.184586,0.000829101,1.09556e-06,-8.32718e-09,0.185416,0.000831267,1.07058e-06,1.11907e-08,0.186248,0.000833442,1.10415e-06,-6.63336e-09,0.187083,0.00083563,1.08425e-06,4.41484e-10,0.187919,0.0008378,1.08557e-06,4.86754e-09,0.188758,0.000839986,1.10017e-06,-5.01041e-09,0.189599,0.000842171,1.08514e-06,2.72811e-10,0.190443,0.000844342,1.08596e-06,3.91916e-09,0.191288,0.000846526,1.09772e-06,-1.04819e-09,0.192136,0.000848718,1.09457e-06,2.73531e-10,0.192985,0.000850908,1.0954e-06,-4.58916e-11,0.193837,0.000853099,1.09526e-06,-9.01158e-11,0.194692,0.000855289,1.09499e-06,4.06506e-10,0.195548,0.00085748,1.09621e-06,-1.53595e-09,0.196407,0.000859668,1.0916e-06,5.73717e-09,0.197267,0.000861869,1.10881e-06,-6.51164e-09,0.19813,0.000864067,1.08928e-06,5.40831e-09,0.198995,0.000866261,1.1055e-06,-2.20401e-10,0.199863,0.000868472,1.10484e-06,-4.52652e-09,0.200732,0.000870668,1.09126e-06,3.42508e-09,0.201604,0.000872861,1.10153e-06,5.72762e-09,0.202478,0.000875081,1.11872e-06,-1.14344e-08,0.203354,0.000877284,1.08441e-06,1.02076e-08,0.204233,0.000879484,1.11504e-06,4.06355e-10,0.205113,0.000881715,1.11626e-06,-1.18329e-08,0.205996,0.000883912,1.08076e-06,1.71227e-08,0.206881,0.000886125,1.13213e-06,-1.19546e-08,0.207768,0.000888353,1.09626e-06,8.93465e-10,0.208658,0.000890548,1.09894e-06,8.38062e-09,0.209549,0.000892771,1.12408e-06,-4.61353e-09,0.210443,0.000895006,1.11024e-06,-4.82756e-09,0.211339,0.000897212,1.09576e-06,9.02245e-09,0.212238,0.00089943,1.12283e-06,-1.45997e-09,0.213138,0.000901672,1.11845e-06,-3.18255e-09,0.214041,0.000903899,1.1089e-06,-7.11073e-10,0.214946,0.000906115,1.10677e-06,6.02692e-09,0.215853,0.000908346,1.12485e-06,-8.49548e-09,0.216763,0.00091057,1.09936e-06,1.30537e-08,0.217675,0.000912808,1.13852e-06,-1.3917e-08,0.218588,0.000915044,1.09677e-06,1.28121e-08,0.219505,0.000917276,1.13521e-06,-7.5288e-09,0.220423,0.000919523,1.11262e-06,2.40205e-09,0.221344,0.000921756,1.11983e-06,-2.07941e-09,0.222267,0.000923989,1.11359e-06,5.91551e-09,0.223192,0.000926234,1.13134e-06,-6.68149e-09,0.224119,0.000928477,1.11129e-06,5.90929e-09,0.225049,0.000930717,1.12902e-06,-2.05436e-09,0.22598,0.000932969,1.12286e-06,2.30807e-09,0.226915,0.000935222,1.12978e-06,-7.17796e-09,0.227851,0.00093746,1.10825e-06,1.15028e-08,0.228789,0.000939711,1.14276e-06,-9.03083e-09,0.22973,0.000941969,1.11566e-06,9.71932e-09,0.230673,0.00094423,1.14482e-06,-1.49452e-08,0.231619,0.000946474,1.09998e-06,2.02591e-08,0.232566,0.000948735,1.16076e-06,-2.13879e-08,0.233516,0.000950993,1.0966e-06,2.05888e-08,0.234468,0.000953247,1.15837e-06,-1.62642e-08,0.235423,0.000955515,1.10957e-06,1.46658e-08,0.236379,0.000957779,1.15357e-06,-1.25966e-08,0.237338,0.000960048,1.11578e-06,5.91793e-09,0.238299,0.000962297,1.13353e-06,3.82602e-09,0.239263,0.000964576,1.14501e-06,-6.3208e-09,0.240229,0.000966847,1.12605e-06,6.55613e-09,0.241197,0.000969119,1.14572e-06,-5.00268e-09,0.242167,0.000971395,1.13071e-06,-1.44659e-09,0.243139,0.000973652,1.12637e-06,1.07891e-08,0.244114,0.000975937,1.15874e-06,-1.19073e-08,0.245091,0.000978219,1.12302e-06,7.03782e-09,0.246071,0.000980486,1.14413e-06,-1.34276e-09,0.247052,0.00098277,1.1401e-06,-1.66669e-09,0.248036,0.000985046,1.1351e-06,8.00935e-09,0.249022,0.00098734,1.15913e-06,-1.54694e-08,0.250011,0.000989612,1.11272e-06,2.4066e-08,0.251002,0.000991909,1.18492e-06,-2.11901e-08,0.251995,0.000994215,1.12135e-06,1.08973e-09,0.25299,0.000996461,1.12462e-06,1.68311e-08,0.253988,0.000998761,1.17511e-06,-8.8094e-09,0.254987,0.00100109,1.14868e-06,-1.13958e-08,0.25599,0.00100335,1.1145e-06,2.45902e-08,0.256994,0.00100565,1.18827e-06,-2.73603e-08,0.258001,0.00100795,1.10618e-06,2.52464e-08,0.25901,0.00101023,1.18192e-06,-1.40207e-08,0.260021,0.00101256,1.13986e-06,1.03387e-09,0.261035,0.00101484,1.14296e-06,9.8853e-09,0.262051,0.00101715,1.17262e-06,-1.07726e-08,0.263069,0.00101947,1.1403e-06,3.40272e-09,0.26409,0.00102176,1.15051e-06,-2.83827e-09,0.265113,0.00102405,1.142e-06,7.95039e-09,0.266138,0.00102636,1.16585e-06,8.39047e-10,0.267166,0.00102869,1.16836e-06,-1.13066e-08,0.268196,0.00103099,1.13444e-06,1.4585e-08,0.269228,0.00103331,1.1782e-06,-1.72314e-08,0.270262,0.00103561,1.1265e-06,2.45382e-08,0.271299,0.00103794,1.20012e-06,-2.13166e-08,0.272338,0.00104028,1.13617e-06,1.12364e-09,0.273379,0.00104255,1.13954e-06,1.68221e-08,0.274423,0.00104488,1.19001e-06,-8.80736e-09,0.275469,0.00104723,1.16358e-06,-1.13948e-08,0.276518,0.00104953,1.1294e-06,2.45839e-08,0.277568,0.00105186,1.20315e-06,-2.73361e-08,0.278621,0.00105418,1.12114e-06,2.51559e-08,0.279677,0.0010565,1.19661e-06,-1.36832e-08,0.280734,0.00105885,1.15556e-06,-2.25706e-10,0.281794,0.00106116,1.15488e-06,1.45862e-08,0.282857,0.00106352,1.19864e-06,-2.83167e-08,0.283921,0.00106583,1.11369e-06,3.90759e-08,0.284988,0.00106817,1.23092e-06,-3.85801e-08,0.286058,0.00107052,1.11518e-06,2.58375e-08,0.287129,0.00107283,1.19269e-06,-5.16498e-09,0.288203,0.0010752,1.1772e-06,-5.17768e-09,0.28928,0.00107754,1.16167e-06,-3.92671e-09,0.290358,0.00107985,1.14988e-06,2.08846e-08,0.29144,0.00108221,1.21254e-06,-2.00072e-08,0.292523,0.00108458,1.15252e-06,-4.60659e-10,0.293609,0.00108688,1.15114e-06,2.18499e-08,0.294697,0.00108925,1.21669e-06,-2.73343e-08,0.295787,0.0010916,1.13468e-06,2.78826e-08,0.29688,0.00109395,1.21833e-06,-2.45915e-08,0.297975,0.00109632,1.14456e-06,1.08787e-08,0.299073,0.00109864,1.17719e-06,1.08788e-08,0.300172,0.00110102,1.20983e-06,-2.45915e-08,0.301275,0.00110337,1.13605e-06,2.78828e-08,0.302379,0.00110573,1.2197e-06,-2.73348e-08,0.303486,0.00110808,1.1377e-06,2.18518e-08,0.304595,0.00111042,1.20325e-06,-4.67556e-10,0.305707,0.00111283,1.20185e-06,-1.99816e-08,0.306821,0.00111517,1.14191e-06,2.07891e-08,0.307937,0.00111752,1.20427e-06,-3.57026e-09,0.309056,0.00111992,1.19356e-06,-6.50797e-09,0.310177,0.00112228,1.17404e-06,-2.00165e-10,0.3113,0.00112463,1.17344e-06,7.30874e-09,0.312426,0.001127,1.19536e-06,7.67424e-10,0.313554,0.00112939,1.19767e-06,-1.03784e-08,0.314685,0.00113176,1.16653e-06,1.09437e-08,0.315818,0.00113412,1.19936e-06,-3.59406e-09,0.316953,0.00113651,1.18858e-06,3.43251e-09,0.318091,0.0011389,1.19888e-06,-1.0136e-08,0.319231,0.00114127,1.16847e-06,7.30915e-09,0.320374,0.00114363,1.1904e-06,1.07018e-08,0.321518,0.00114604,1.2225e-06,-2.03137e-08,0.322666,0.00114842,1.16156e-06,1.09484e-08,0.323815,0.00115078,1.19441e-06,6.32224e-09,0.324967,0.00115319,1.21337e-06,-6.43509e-09,0.326122,0.00115559,1.19407e-06,-1.03842e-08,0.327278,0.00115795,1.16291e-06,1.81697e-08,0.328438,0.00116033,1.21742e-06,-2.6901e-09,0.329599,0.00116276,1.20935e-06,-7.40939e-09,0.330763,0.00116515,1.18713e-06,2.52533e-09,0.331929,0.00116754,1.1947e-06,-2.69191e-09,0.333098,0.00116992,1.18663e-06,8.24218e-09,0.334269,0.00117232,1.21135e-06,-4.74377e-10,0.335443,0.00117474,1.20993e-06,-6.34471e-09,0.336619,0.00117714,1.1909e-06,-3.94922e-09,0.337797,0.00117951,1.17905e-06,2.21417e-08,0.338978,0.00118193,1.24547e-06,-2.50128e-08,0.340161,0.00118435,1.17043e-06,1.8305e-08,0.341346,0.00118674,1.22535e-06,-1.84048e-08,0.342534,0.00118914,1.17013e-06,2.55121e-08,0.343725,0.00119156,1.24667e-06,-2.40389e-08,0.344917,0.00119398,1.17455e-06,1.10389e-08,0.346113,0.00119636,1.20767e-06,9.68574e-09,0.34731,0.0011988,1.23673e-06,-1.99797e-08,0.34851,0.00120122,1.17679e-06,1.06284e-08,0.349713,0.0012036,1.20867e-06,7.26868e-09,0.350917,0.00120604,1.23048e-06,-9.90072e-09,0.352125,0.00120847,1.20078e-06,2.53177e-09,0.353334,0.00121088,1.20837e-06,-2.26199e-10,0.354546,0.0012133,1.20769e-06,-1.62705e-09,0.355761,0.00121571,1.20281e-06,6.73435e-09,0.356978,0.00121813,1.22302e-06,4.49207e-09,0.358197,0.00122059,1.23649e-06,-2.47027e-08,0.359419,0.00122299,1.16238e-06,3.47142e-08,0.360643,0.00122542,1.26653e-06,-2.47472e-08,0.36187,0.00122788,1.19229e-06,4.66965e-09,0.363099,0.00123028,1.20629e-06,6.06872e-09,0.36433,0.00123271,1.2245e-06,8.57729e-10,0.365564,0.00123516,1.22707e-06,-9.49952e-09,0.366801,0.00123759,1.19858e-06,7.33792e-09,0.36804,0.00124001,1.22059e-06,9.95025e-09,0.369281,0.00124248,1.25044e-06,-1.73366e-08,0.370525,0.00124493,1.19843e-06,-2.08464e-10,0.371771,0.00124732,1.1978e-06,1.81704e-08,0.373019,0.00124977,1.25232e-06,-1.28683e-08,0.37427,0.00125224,1.21371e-06,3.50042e-09,0.375524,0.00125468,1.22421e-06,-1.1335e-09,0.37678,0.00125712,1.22081e-06,1.03345e-09,0.378038,0.00125957,1.22391e-06,-3.00023e-09,0.379299,0.00126201,1.21491e-06,1.09676e-08,0.380562,0.00126447,1.24781e-06,-1.10676e-08,0.381828,0.00126693,1.21461e-06,3.50042e-09,0.383096,0.00126937,1.22511e-06,-2.93403e-09,0.384366,0.00127181,1.21631e-06,8.23574e-09,0.385639,0.00127427,1.24102e-06,-2.06607e-10,0.386915,0.00127675,1.2404e-06,-7.40935e-09,0.388193,0.00127921,1.21817e-06,4.1761e-11,0.389473,0.00128165,1.21829e-06,7.24223e-09,0.390756,0.0012841,1.24002e-06,7.91564e-10,0.392042,0.00128659,1.2424e-06,-1.04086e-08,0.393329,0.00128904,1.21117e-06,1.10405e-08,0.39462,0.0012915,1.24429e-06,-3.951e-09,0.395912,0.00129397,1.23244e-06,4.7634e-09,0.397208,0.00129645,1.24673e-06,-1.51025e-08,0.398505,0.0012989,1.20142e-06,2.58443e-08,0.399805,0.00130138,1.27895e-06,-2.86702e-08,0.401108,0.00130385,1.19294e-06,2.92318e-08,0.402413,0.00130632,1.28064e-06,-2.86524e-08,0.403721,0.0013088,1.19468e-06,2.57731e-08,0.405031,0.00131127,1.272e-06,-1.48355e-08,0.406343,0.00131377,1.2275e-06,3.76652e-09,0.407658,0.00131623,1.23879e-06,-2.30784e-10,0.408976,0.00131871,1.2381e-06,-2.84331e-09,0.410296,0.00132118,1.22957e-06,1.16041e-08,0.411618,0.00132367,1.26438e-06,-1.37708e-08,0.412943,0.00132616,1.22307e-06,1.36768e-08,0.41427,0.00132865,1.2641e-06,-1.1134e-08,0.4156,0.00133114,1.2307e-06,1.05714e-09,0.416933,0.00133361,1.23387e-06,6.90538e-09,0.418267,0.00133609,1.25459e-06,1.12372e-09,0.419605,0.00133861,1.25796e-06,-1.14002e-08,0.420945,0.00134109,1.22376e-06,1.46747e-08,0.422287,0.00134358,1.26778e-06,-1.7496e-08,0.423632,0.00134606,1.21529e-06,2.5507e-08,0.424979,0.00134857,1.29182e-06,-2.49272e-08,0.426329,0.00135108,1.21703e-06,1.45972e-08,0.427681,0.00135356,1.26083e-06,-3.65935e-09,0.429036,0.00135607,1.24985e-06,4.00178e-11,0.430393,0.00135857,1.24997e-06,3.49917e-09,0.431753,0.00136108,1.26047e-06,-1.40366e-08,0.433116,0.00136356,1.21836e-06,2.28448e-08,0.43448,0.00136606,1.28689e-06,-1.77378e-08,0.435848,0.00136858,1.23368e-06,1.83043e-08,0.437218,0.0013711,1.28859e-06,-2.56769e-08,0.43859,0.0013736,1.21156e-06,2.47987e-08,0.439965,0.0013761,1.28595e-06,-1.39133e-08,0.441342,0.00137863,1.24421e-06,1.05202e-09,0.442722,0.00138112,1.24737e-06,9.70507e-09,0.444104,0.00138365,1.27649e-06,-1.00698e-08,0.445489,0.00138617,1.24628e-06,7.72123e-10,0.446877,0.00138867,1.24859e-06,6.98132e-09,0.448267,0.00139118,1.26954e-06,1.10477e-09,0.449659,0.00139373,1.27285e-06,-1.14003e-08,0.451054,0.00139624,1.23865e-06,1.4694e-08,0.452452,0.00139876,1.28273e-06,-1.75734e-08,0.453852,0.00140127,1.23001e-06,2.5797e-08,0.455254,0.00140381,1.3074e-06,-2.60097e-08,0.456659,0.00140635,1.22937e-06,1.86371e-08,0.458067,0.00140886,1.28529e-06,-1.8736e-08,0.459477,0.00141137,1.22908e-06,2.65048e-08,0.46089,0.00141391,1.30859e-06,-2.76784e-08,0.462305,0.00141645,1.22556e-06,2.46043e-08,0.463722,0.00141897,1.29937e-06,-1.11341e-08,0.465143,0.00142154,1.26597e-06,-9.87033e-09,0.466565,0.00142404,1.23636e-06,2.08131e-08,0.467991,0.00142657,1.2988e-06,-1.37773e-08,0.469419,0.00142913,1.25746e-06,4.49378e-09,0.470849,0.00143166,1.27094e-06,-4.19781e-09,0.472282,0.00143419,1.25835e-06,1.22975e-08,0.473717,0.00143674,1.29524e-06,-1.51902e-08,0.475155,0.00143929,1.24967e-06,1.86608e-08,0.476596,0.00144184,1.30566e-06,-2.96506e-08,0.478039,0.00144436,1.2167e-06,4.03368e-08,0.479485,0.00144692,1.33771e-06,-4.22896e-08,0.480933,0.00144947,1.21085e-06,3.94148e-08,0.482384,0.00145201,1.32909e-06,-2.59626e-08,0.483837,0.00145459,1.2512e-06,4.83124e-09,0.485293,0.0014571,1.2657e-06,6.63757e-09,0.486751,0.00145966,1.28561e-06,-1.57911e-09,0.488212,0.00146222,1.28087e-06,-3.21468e-10,0.489676,0.00146478,1.27991e-06,2.86517e-09,0.491142,0.00146735,1.2885e-06,-1.11392e-08,0.49261,0.00146989,1.25508e-06,1.18893e-08,0.494081,0.00147244,1.29075e-06,-6.61574e-09,0.495555,0.001475,1.27091e-06,1.45736e-08,0.497031,0.00147759,1.31463e-06,-2.18759e-08,0.49851,0.00148015,1.249e-06,1.33252e-08,0.499992,0.00148269,1.28897e-06,-1.62277e-09,0.501476,0.00148526,1.28411e-06,-6.83421e-09,0.502962,0.00148781,1.2636e-06,2.89596e-08,0.504451,0.00149042,1.35048e-06,-4.93997e-08,0.505943,0.00149298,1.20228e-06,4.94299e-08,0.507437,0.00149553,1.35057e-06,-2.91107e-08,0.508934,0.00149814,1.26324e-06,7.40848e-09,0.510434,0.00150069,1.28547e-06,-5.23187e-10,0.511936,0.00150326,1.2839e-06,-5.31585e-09,0.51344,0.00150581,1.26795e-06,2.17866e-08,0.514947,0.00150841,1.33331e-06,-2.22257e-08,0.516457,0.00151101,1.26663e-06,7.51178e-09,0.517969,0.00151357,1.28917e-06,-7.82128e-09,0.519484,0.00151613,1.2657e-06,2.37733e-08,0.521002,0.00151873,1.33702e-06,-2.76674e-08,0.522522,0.00152132,1.25402e-06,2.72917e-08,0.524044,0.00152391,1.3359e-06,-2.18949e-08,0.525569,0.00152652,1.27021e-06,6.83372e-10,0.527097,0.00152906,1.27226e-06,1.91613e-08,0.528628,0.00153166,1.32974e-06,-1.77241e-08,0.53016,0.00153427,1.27657e-06,-7.86963e-09,0.531696,0.0015368,1.25296e-06,4.92027e-08,0.533234,0.00153945,1.40057e-06,-6.9732e-08,0.534775,0.00154204,1.19138e-06,5.09114e-08,0.536318,0.00154458,1.34411e-06,-1.4704e-08,0.537864,0.00154722,1.3e-06,7.9048e-09,0.539413,0.00154984,1.32371e-06,-1.69152e-08,0.540964,0.00155244,1.27297e-06,1.51355e-10,0.542517,0.00155499,1.27342e-06,1.63099e-08,0.544074,0.00155758,1.32235e-06,-5.78647e-09,0.545633,0.00156021,1.30499e-06,6.83599e-09,0.547194,0.00156284,1.3255e-06,-2.15575e-08,0.548758,0.00156543,1.26083e-06,1.97892e-08,0.550325,0.00156801,1.32019e-06,2.00525e-09,0.551894,0.00157065,1.32621e-06,-2.78103e-08,0.553466,0.00157322,1.24278e-06,4.96314e-08,0.555041,0.00157586,1.39167e-06,-5.1506e-08,0.556618,0.00157849,1.23716e-06,3.71835e-08,0.558198,0.00158107,1.34871e-06,-3.76233e-08,0.55978,0.00158366,1.23584e-06,5.37052e-08,0.561365,0.00158629,1.39695e-06,-5.79884e-08,0.562953,0.00158891,1.22299e-06,5.90392e-08,0.564543,0.00159153,1.4001e-06,-5.89592e-08,0.566136,0.00159416,1.22323e-06,5.7588e-08,0.567731,0.00159678,1.39599e-06,-5.21835e-08,0.569329,0.00159941,1.23944e-06,3.19369e-08,0.57093,0.00160199,1.33525e-06,-1.59594e-08,0.572533,0.00160461,1.28737e-06,3.19006e-08,0.574139,0.00160728,1.38307e-06,-5.20383e-08,0.575748,0.00160989,1.22696e-06,5.70431e-08,0.577359,0.00161251,1.39809e-06,-5.69247e-08,0.578973,0.00161514,1.22731e-06,5.14463e-08,0.580589,0.00161775,1.38165e-06,-2.9651e-08,0.582208,0.00162042,1.2927e-06,7.55339e-09,0.58383,0.00162303,1.31536e-06,-5.62636e-10,0.585455,0.00162566,1.31367e-06,-5.30281e-09,0.587081,0.00162827,1.29776e-06,2.17738e-08,0.588711,0.00163093,1.36309e-06,-2.21875e-08,0.590343,0.00163359,1.29652e-06,7.37164e-09,0.591978,0.00163621,1.31864e-06,-7.29907e-09,0.593616,0.00163882,1.29674e-06,2.18247e-08,0.595256,0.00164148,1.36221e-06,-2.03952e-08,0.596899,0.00164414,1.30103e-06,1.51241e-10,0.598544,0.00164675,1.30148e-06,1.97902e-08,0.600192,0.00164941,1.36085e-06,-1.97074e-08,0.601843,0.00165207,1.30173e-06,-5.65175e-10,0.603496,0.00165467,1.30004e-06,2.1968e-08,0.605152,0.00165734,1.36594e-06,-2.77024e-08,0.606811,0.00165999,1.28283e-06,2.92369e-08,0.608472,0.00166264,1.37054e-06,-2.96407e-08,0.610136,0.00166529,1.28162e-06,2.97215e-08,0.611803,0.00166795,1.37079e-06,-2.96408e-08,0.613472,0.0016706,1.28186e-06,2.92371e-08,0.615144,0.00167325,1.36957e-06,-2.77031e-08,0.616819,0.00167591,1.28647e-06,2.19708e-08,0.618496,0.00167855,1.35238e-06,-5.75407e-10,0.620176,0.00168125,1.35065e-06,-1.9669e-08,0.621858,0.00168389,1.29164e-06,1.96468e-08,0.623544,0.00168653,1.35058e-06,6.86403e-10,0.625232,0.00168924,1.35264e-06,-2.23924e-08,0.626922,0.00169187,1.28547e-06,2.92788e-08,0.628615,0.00169453,1.3733e-06,-3.51181e-08,0.630311,0.00169717,1.26795e-06,5.15889e-08,0.63201,0.00169987,1.42272e-06,-5.2028e-08,0.633711,0.00170255,1.26663e-06,3.73139e-08,0.635415,0.0017052,1.37857e-06,-3.76227e-08,0.637121,0.00170784,1.2657e-06,5.35722e-08,0.63883,0.00171054,1.42642e-06,-5.74567e-08,0.640542,0.00171322,1.25405e-06,5.70456e-08,0.642257,0.0017159,1.42519e-06,-5.15163e-08,0.643974,0.00171859,1.27064e-06,2.98103e-08,0.645694,0.00172122,1.36007e-06,-8.12016e-09,0.647417,0.00172392,1.33571e-06,2.67039e-09,0.649142,0.0017266,1.34372e-06,-2.56152e-09,0.65087,0.00172928,1.33604e-06,7.57571e-09,0.6526,0.00173197,1.35876e-06,-2.77413e-08,0.654334,0.00173461,1.27554e-06,4.3785e-08,0.65607,0.00173729,1.40689e-06,-2.81896e-08,0.657808,0.00174002,1.32233e-06,9.36893e-09,0.65955,0.00174269,1.35043e-06,-9.28617e-09,0.661294,0.00174536,1.32257e-06,2.77757e-08,0.66304,0.00174809,1.4059e-06,-4.2212e-08,0.66479,0.00175078,1.27926e-06,2.1863e-08,0.666542,0.0017534,1.34485e-06,1.43648e-08,0.668297,0.00175613,1.38795e-06,-1.97177e-08,0.670054,0.00175885,1.3288e-06,4.90115e-09,0.671814,0.00176152,1.3435e-06,1.13232e-10,0.673577,0.00176421,1.34384e-06,-5.3542e-09,0.675343,0.00176688,1.32778e-06,2.13035e-08,0.677111,0.0017696,1.39169e-06,-2.02553e-08,0.678882,0.00177232,1.33092e-06,1.13005e-10,0.680656,0.00177499,1.33126e-06,1.98031e-08,0.682432,0.00177771,1.39067e-06,-1.97211e-08,0.684211,0.00178043,1.33151e-06,-5.2349e-10,0.685993,0.00178309,1.32994e-06,2.18151e-08,0.687777,0.00178582,1.39538e-06,-2.71325e-08,0.689564,0.00178853,1.31398e-06,2.71101e-08,0.691354,0.00179124,1.39531e-06,-2.17035e-08,0.693147,0.00179396,1.3302e-06,9.92865e-11,0.694942,0.00179662,1.3305e-06,2.13063e-08,0.69674,0.00179935,1.39442e-06,-2.57198e-08,0.698541,0.00180206,1.31726e-06,2.19682e-08,0.700344,0.00180476,1.38317e-06,-2.54852e-09,0.70215,0.00180752,1.37552e-06,-1.17741e-08,0.703959,0.00181023,1.3402e-06,-9.95999e-09,0.705771,0.00181288,1.31032e-06,5.16141e-08,0.707585,0.00181566,1.46516e-06,-7.72869e-08,0.709402,0.00181836,1.2333e-06,7.87197e-08,0.711222,0.00182106,1.46946e-06,-5.87781e-08,0.713044,0.00182382,1.29312e-06,3.71834e-08,0.714869,0.00182652,1.40467e-06,-3.03511e-08,0.716697,0.00182924,1.31362e-06,2.46161e-08,0.718528,0.00183194,1.38747e-06,-8.5087e-09,0.720361,0.00183469,1.36194e-06,9.41892e-09,0.722197,0.00183744,1.3902e-06,-2.91671e-08,0.724036,0.00184014,1.3027e-06,4.76448e-08,0.725878,0.00184288,1.44563e-06,-4.22028e-08,0.727722,0.00184565,1.31902e-06,1.95682e-09,0.729569,0.00184829,1.3249e-06,3.43754e-08,0.731419,0.00185104,1.42802e-06,-2.0249e-08,0.733271,0.00185384,1.36727e-06,-1.29838e-08,0.735126,0.00185654,1.32832e-06,1.25794e-08,0.736984,0.00185923,1.36606e-06,2.22711e-08,0.738845,0.00186203,1.43287e-06,-4.20594e-08,0.740708,0.00186477,1.3067e-06,2.67571e-08,0.742574,0.00186746,1.38697e-06,-5.36424e-09,0.744443,0.00187022,1.37087e-06,-5.30023e-09,0.746315,0.00187295,1.35497e-06,2.65653e-08,0.748189,0.00187574,1.43467e-06,-4.13564e-08,0.750066,0.00187848,1.3106e-06,1.9651e-08,0.751946,0.00188116,1.36955e-06,2.23572e-08,0.753828,0.00188397,1.43663e-06,-4.9475e-08,0.755714,0.00188669,1.2882e-06,5.63335e-08,0.757602,0.00188944,1.4572e-06,-5.66499e-08,0.759493,0.00189218,1.28725e-06,5.10567e-08,0.761386,0.00189491,1.44042e-06,-2.83677e-08,0.763283,0.00189771,1.35532e-06,2.80962e-09,0.765182,0.00190042,1.36375e-06,1.71293e-08,0.767083,0.0019032,1.41513e-06,-1.17221e-08,0.768988,0.001906,1.37997e-06,-2.98453e-08,0.770895,0.00190867,1.29043e-06,7.14987e-08,0.772805,0.00191146,1.50493e-06,-7.73354e-08,0.774718,0.00191424,1.27292e-06,5.90292e-08,0.776634,0.00191697,1.45001e-06,-3.9572e-08,0.778552,0.00191975,1.33129e-06,3.9654e-08,0.780473,0.00192253,1.45026e-06,-5.94395e-08,0.782397,0.00192525,1.27194e-06,7.88945e-08,0.784324,0.00192803,1.50862e-06,-7.73249e-08,0.786253,0.00193082,1.27665e-06,5.15913e-08,0.788185,0.00193352,1.43142e-06,-9.83099e-09,0.79012,0.00193636,1.40193e-06,-1.22672e-08,0.792058,0.00193912,1.36513e-06,-7.05275e-10,0.793999,0.00194185,1.36301e-06,1.50883e-08,0.795942,0.00194462,1.40828e-06,-4.33147e-11,0.797888,0.00194744,1.40815e-06,-1.49151e-08,0.799837,0.00195021,1.3634e-06,9.93244e-11,0.801788,0.00195294,1.3637e-06,1.45179e-08,0.803743,0.00195571,1.40725e-06,1.43363e-09,0.8057,0.00195853,1.41155e-06,-2.02525e-08,0.80766,0.00196129,1.35079e-06,1.99718e-08,0.809622,0.00196405,1.41071e-06,-3.01649e-11,0.811588,0.00196687,1.41062e-06,-1.9851e-08,0.813556,0.00196964,1.35107e-06,1.98296e-08,0.815527,0.0019724,1.41056e-06,1.37485e-10,0.817501,0.00197522,1.41097e-06,-2.03796e-08,0.819477,0.00197798,1.34983e-06,2.17763e-08,0.821457,0.00198074,1.41516e-06,-7.12085e-09,0.823439,0.00198355,1.3938e-06,6.70707e-09,0.825424,0.00198636,1.41392e-06,-1.97074e-08,0.827412,0.00198913,1.35479e-06,1.25179e-08,0.829402,0.00199188,1.39235e-06,2.92405e-08,0.831396,0.00199475,1.48007e-06,-6.98755e-08,0.833392,0.0019975,1.27044e-06,7.14477e-08,0.835391,0.00200026,1.48479e-06,-3.71014e-08,0.837392,0.00200311,1.37348e-06,1.73533e-08,0.839397,0.00200591,1.42554e-06,-3.23118e-08,0.841404,0.00200867,1.32861e-06,5.2289e-08,0.843414,0.00201148,1.48547e-06,-5.76348e-08,0.845427,0.00201428,1.31257e-06,5.9041e-08,0.847443,0.00201708,1.48969e-06,-5.93197e-08,0.849461,0.00201988,1.31173e-06,5.90289e-08,0.851482,0.00202268,1.48882e-06,-5.75864e-08,0.853507,0.00202549,1.31606e-06,5.21075e-08,0.855533,0.00202828,1.47238e-06,-3.16344e-08,0.857563,0.00203113,1.37748e-06,1.48257e-08,0.859596,0.00203393,1.42196e-06,-2.76684e-08,0.861631,0.00203669,1.33895e-06,3.62433e-08,0.863669,0.00203947,1.44768e-06,1.90463e-09,0.86571,0.00204237,1.45339e-06,-4.38617e-08,0.867754,0.00204515,1.32181e-06,5.43328e-08,0.8698,0.00204796,1.48481e-06,-5.42603e-08,0.87185,0.00205076,1.32203e-06,4.34989e-08,0.873902,0.00205354,1.45252e-06,-5.26029e-10,0.875957,0.00205644,1.45095e-06,-4.13949e-08,0.878015,0.00205922,1.32676e-06,4.68962e-08,0.880075,0.00206201,1.46745e-06,-2.69807e-08,0.882139,0.00206487,1.38651e-06,1.42181e-09,0.884205,0.00206764,1.39077e-06,2.12935e-08,0.886274,0.00207049,1.45465e-06,-2.69912e-08,0.888346,0.00207332,1.37368e-06,2.70664e-08,0.890421,0.00207615,1.45488e-06,-2.16698e-08,0.892498,0.00207899,1.38987e-06,8.14756e-12,0.894579,0.00208177,1.38989e-06,2.16371e-08,0.896662,0.00208462,1.45481e-06,-2.6952e-08,0.898748,0.00208744,1.37395e-06,2.65663e-08,0.900837,0.00209027,1.45365e-06,-1.97084e-08,0.902928,0.00209312,1.39452e-06,-7.33731e-09,0.905023,0.00209589,1.37251e-06,4.90578e-08,0.90712,0.00209878,1.51968e-06,-6.96845e-08,0.90922,0.00210161,1.31063e-06,5.08664e-08,0.911323,0.00210438,1.46323e-06,-1.45717e-08,0.913429,0.00210727,1.41952e-06,7.42038e-09,0.915538,0.00211013,1.44178e-06,-1.51097e-08,0.917649,0.00211297,1.39645e-06,-6.58618e-09,0.919764,0.00211574,1.37669e-06,4.14545e-08,0.921881,0.00211862,1.50105e-06,-4.00222e-08,0.924001,0.0021215,1.38099e-06,-5.7518e-10,0.926124,0.00212426,1.37926e-06,4.23229e-08,0.92825,0.00212714,1.50623e-06,-4.9507e-08,0.930378,0.00213001,1.35771e-06,3.64958e-08,0.93251,0.00213283,1.4672e-06,-3.68713e-08,0.934644,0.00213566,1.35658e-06,5.13848e-08,0.936781,0.00213852,1.51074e-06,-4.94585e-08,0.938921,0.0021414,1.36236e-06,2.72399e-08,0.941064,0.0021442,1.44408e-06,1.0372e-10,0.943209,0.00214709,1.44439e-06,-2.76547e-08,0.945358,0.0021499,1.36143e-06,5.09106e-08,0.947509,0.00215277,1.51416e-06,-5.67784e-08,0.949663,0.00215563,1.34382e-06,5.69935e-08,0.95182,0.00215849,1.5148e-06,-5.19861e-08,0.95398,0.00216136,1.35885e-06,3.17417e-08,0.956143,0.00216418,1.45407e-06,-1.53758e-08,0.958309,0.00216704,1.40794e-06,2.97615e-08,0.960477,0.00216994,1.49723e-06,-4.40657e-08,0.962649,0.00217281,1.36503e-06,2.72919e-08,0.964823,0.00217562,1.44691e-06,-5.49729e-09,0.967,0.0021785,1.43041e-06,-5.30273e-09,0.96918,0.00218134,1.41451e-06,2.67084e-08,0.971363,0.00218425,1.49463e-06,-4.19265e-08,0.973548,0.00218711,1.36885e-06,2.17881e-08,0.975737,0.00218992,1.43422e-06,1.43789e-08,0.977928,0.00219283,1.47735e-06,-1.96989e-08,0.980122,0.00219572,1.41826e-06,4.81221e-09,0.98232,0.00219857,1.43269e-06,4.50048e-10,0.98452,0.00220144,1.43404e-06,-6.61237e-09,0.986722,0.00220429,1.41421e-06,2.59993e-08,0.988928,0.0022072,1.4922e-06,-3.77803e-08,0.991137,0.00221007,1.37886e-06,5.9127e-09,0.993348,0.00221284,1.3966e-06,1.33339e-07,0.995563,0.00221604,1.79662e-06,-5.98872e-07,0.99778,0.00222015,0.,0.}; template __device__ __forceinline__ void RGB2LabConvert_f(const T& src, D& dst) { const float _1_3 = 1.0f / 3.0f; const float _a = 16.0f / 116.0f; float B = blueIdx == 0 ? src.x : src.z; float G = src.y; float R = blueIdx == 0 ? src.z : src.x; if (srgb) { B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); } float X = B * 0.189828f + G * 0.376219f + R * 0.433953f; float Y = B * 0.072169f + G * 0.715160f + R * 0.212671f; float Z = B * 0.872766f + G * 0.109477f + R * 0.017758f; float FX = X > 0.008856f ? ::powf(X, _1_3) : (7.787f * X + _a); float FY = Y > 0.008856f ? ::powf(Y, _1_3) : (7.787f * Y + _a); float FZ = Z > 0.008856f ? ::powf(Z, _1_3) : (7.787f * Z + _a); float L = Y > 0.008856f ? (116.f * FY - 16.f) : (903.3f * Y); float a = 500.f * (FX - FY); float b = 200.f * (FY - FZ); dst.x = L; dst.y = a; dst.z = b; } template struct RGB2Lab; template struct RGB2Lab : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2LabConvert_b(src, dst); return dst; } __host__ __device__ __forceinline__ RGB2Lab() {} __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} }; template struct RGB2Lab : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2LabConvert_f(src, dst); return dst; } __host__ __device__ __forceinline__ RGB2Lab() {} __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(name, scn, dcn, srgb, blueIdx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2Lab functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { __constant__ float c_sRGBInvGammaTab[] = {0,0.0126255,0.,-8.33961e-06,0.0126172,0.0126005,-2.50188e-05,4.1698e-05,0.0252344,0.0126756,0.000100075,-0.000158451,0.0378516,0.0124004,-0.000375277,-0.000207393,0.0496693,0.0110276,-0.000997456,0.00016837,0.0598678,0.00953783,-0.000492346,2.07235e-05,0.068934,0.00861531,-0.000430176,3.62876e-05,0.0771554,0.00786382,-0.000321313,1.87625e-05,0.0847167,0.00727748,-0.000265025,1.53594e-05,0.0917445,0.00679351,-0.000218947,1.10545e-05,0.0983301,0.00638877,-0.000185784,8.66984e-06,0.104542,0.00604322,-0.000159774,6.82996e-06,0.110432,0.00574416,-0.000139284,5.51008e-06,0.116042,0.00548212,-0.000122754,4.52322e-06,0.121406,0.00525018,-0.000109184,3.75557e-06,0.126551,0.00504308,-9.79177e-05,3.17134e-06,0.131499,0.00485676,-8.84037e-05,2.68469e-06,0.13627,0.004688,-8.03496e-05,2.31725e-06,0.14088,0.00453426,-7.33978e-05,2.00868e-06,0.145343,0.00439349,-6.73718e-05,1.74775e-06,0.149671,0.00426399,-6.21286e-05,1.53547e-06,0.153875,0.00414434,-5.75222e-05,1.364e-06,0.157963,0.00403338,-5.34301e-05,1.20416e-06,0.161944,0.00393014,-4.98177e-05,1.09114e-06,0.165825,0.00383377,-4.65443e-05,9.57987e-07,0.169613,0.00374356,-4.36703e-05,8.88359e-07,0.173314,0.00365888,-4.10052e-05,7.7849e-07,0.176933,0.00357921,-3.86697e-05,7.36254e-07,0.180474,0.00350408,-3.6461e-05,6.42534e-07,0.183942,0.00343308,-3.45334e-05,6.12614e-07,0.187342,0.00336586,-3.26955e-05,5.42894e-07,0.190675,0.00330209,-3.10669e-05,5.08967e-07,0.193947,0.00324149,-2.954e-05,4.75977e-07,0.197159,0.00318383,-2.8112e-05,4.18343e-07,0.200315,0.00312887,-2.6857e-05,4.13651e-07,0.203418,0.00307639,-2.5616e-05,3.70847e-07,0.206469,0.00302627,-2.45035e-05,3.3813e-07,0.209471,0.00297828,-2.34891e-05,3.32999e-07,0.212426,0.0029323,-2.24901e-05,2.96826e-07,0.215336,0.00288821,-2.15996e-05,2.82736e-07,0.218203,0.00284586,-2.07514e-05,2.70961e-07,0.221029,0.00280517,-1.99385e-05,2.42744e-07,0.223814,0.00276602,-1.92103e-05,2.33277e-07,0.226561,0.0027283,-1.85105e-05,2.2486e-07,0.229271,0.00269195,-1.78359e-05,2.08383e-07,0.231945,0.00265691,-1.72108e-05,1.93305e-07,0.234585,0.00262307,-1.66308e-05,1.80687e-07,0.237192,0.00259035,-1.60888e-05,1.86632e-07,0.239766,0.00255873,-1.55289e-05,1.60569e-07,0.24231,0.00252815,-1.50472e-05,1.54566e-07,0.244823,0.00249852,-1.45835e-05,1.59939e-07,0.247307,0.00246983,-1.41037e-05,1.29549e-07,0.249763,0.00244202,-1.3715e-05,1.41429e-07,0.252191,0.00241501,-1.32907e-05,1.39198e-07,0.254593,0.00238885,-1.28731e-05,1.06444e-07,0.256969,0.00236342,-1.25538e-05,1.2048e-07,0.25932,0.00233867,-1.21924e-05,1.26892e-07,0.261647,0.00231467,-1.18117e-05,8.72084e-08,0.26395,0.00229131,-1.15501e-05,1.20323e-07,0.26623,0.00226857,-1.11891e-05,8.71514e-08,0.268487,0.00224645,-1.09276e-05,9.73165e-08,0.270723,0.00222489,-1.06357e-05,8.98259e-08,0.272937,0.00220389,-1.03662e-05,7.98218e-08,0.275131,0.00218339,-1.01267e-05,9.75254e-08,0.277304,0.00216343,-9.83416e-06,6.65195e-08,0.279458,0.00214396,-9.63461e-06,8.34313e-08,0.281592,0.00212494,-9.38431e-06,7.65919e-08,0.283708,0.00210641,-9.15454e-06,5.7236e-08,0.285805,0.00208827,-8.98283e-06,8.18939e-08,0.287885,0.00207055,-8.73715e-06,6.2224e-08,0.289946,0.00205326,-8.55047e-06,5.66388e-08,0.291991,0.00203633,-8.38056e-06,6.88491e-08,0.294019,0.00201978,-8.17401e-06,5.53955e-08,0.296031,0.00200359,-8.00782e-06,6.71971e-08,0.298027,0.00198778,-7.80623e-06,3.34439e-08,0.300007,0.00197227,-7.7059e-06,6.7248e-08,0.301971,0.00195706,-7.50416e-06,5.51915e-08,0.303921,0.00194221,-7.33858e-06,3.98124e-08,0.305856,0.00192766,-7.21915e-06,5.37795e-08,0.307776,0.00191338,-7.05781e-06,4.30919e-08,0.309683,0.00189939,-6.92853e-06,4.20744e-08,0.311575,0.00188566,-6.80231e-06,5.68321e-08,0.313454,0.00187223,-6.63181e-06,2.86195e-08,0.31532,0.00185905,-6.54595e-06,3.73075e-08,0.317172,0.00184607,-6.43403e-06,6.05684e-08,0.319012,0.00183338,-6.25233e-06,1.84426e-08,0.320839,0.00182094,-6.197e-06,4.44757e-08,0.322654,0.00180867,-6.06357e-06,4.20729e-08,0.324456,0.00179667,-5.93735e-06,2.56511e-08,0.326247,0.00178488,-5.8604e-06,3.41368e-08,0.328026,0.00177326,-5.75799e-06,4.64177e-08,0.329794,0.00176188,-5.61874e-06,1.86107e-08,0.33155,0.0017507,-5.5629e-06,2.81511e-08,0.333295,0.00173966,-5.47845e-06,4.75987e-08,0.335029,0.00172884,-5.33565e-06,1.98726e-08,0.336753,0.00171823,-5.27604e-06,2.19226e-08,0.338466,0.00170775,-5.21027e-06,4.14483e-08,0.340169,0.00169745,-5.08592e-06,2.09017e-08,0.341861,0.00168734,-5.02322e-06,2.39561e-08,0.343543,0.00167737,-4.95135e-06,3.22852e-08,0.345216,0.00166756,-4.85449e-06,2.57173e-08,0.346878,0.00165793,-4.77734e-06,1.38569e-08,0.348532,0.00164841,-4.73577e-06,3.80634e-08,0.350175,0.00163906,-4.62158e-06,1.27043e-08,0.35181,0.00162985,-4.58347e-06,3.03279e-08,0.353435,0.00162078,-4.49249e-06,1.49961e-08,0.355051,0.00161184,-4.4475e-06,2.88977e-08,0.356659,0.00160303,-4.3608e-06,1.84241e-08,0.358257,0.00159436,-4.30553e-06,1.6616e-08,0.359848,0.0015858,-4.25568e-06,3.43218e-08,0.361429,0.00157739,-4.15272e-06,-4.89172e-09,0.363002,0.00156907,-4.16739e-06,4.48498e-08,0.364567,0.00156087,-4.03284e-06,4.30676e-09,0.366124,0.00155282,-4.01992e-06,2.73303e-08,0.367673,0.00154486,-3.93793e-06,5.58036e-09,0.369214,0.001537,-3.92119e-06,3.97554e-08,0.370747,0.00152928,-3.80193e-06,-1.55904e-08,0.372272,0.00152163,-3.8487e-06,5.24081e-08,0.37379,0.00151409,-3.69147e-06,-1.52272e-08,0.375301,0.00150666,-3.73715e-06,3.83028e-08,0.376804,0.0014993,-3.62225e-06,1.10278e-08,0.378299,0.00149209,-3.58916e-06,6.99326e-09,0.379788,0.00148493,-3.56818e-06,2.06038e-08,0.381269,0.00147786,-3.50637e-06,2.98009e-08,0.382744,0.00147093,-3.41697e-06,-2.05978e-08,0.384211,0.00146404,-3.47876e-06,5.25899e-08,0.385672,0.00145724,-3.32099e-06,-1.09471e-08,0.387126,0.00145056,-3.35383e-06,2.10009e-08,0.388573,0.00144392,-3.29083e-06,1.63501e-08,0.390014,0.00143739,-3.24178e-06,3.00641e-09,0.391448,0.00143091,-3.23276e-06,3.12282e-08,0.392875,0.00142454,-3.13908e-06,-8.70932e-09,0.394297,0.00141824,-3.16521e-06,3.34114e-08,0.395712,0.00141201,-3.06497e-06,-5.72754e-09,0.397121,0.00140586,-3.08215e-06,1.9301e-08,0.398524,0.00139975,-3.02425e-06,1.7931e-08,0.39992,0.00139376,-2.97046e-06,-1.61822e-09,0.401311,0.00138781,-2.97531e-06,1.83442e-08,0.402696,0.00138192,-2.92028e-06,1.76485e-08,0.404075,0.00137613,-2.86733e-06,4.68617e-10,0.405448,0.00137039,-2.86593e-06,1.02794e-08,0.406816,0.00136469,-2.83509e-06,1.80179e-08,0.408178,0.00135908,-2.78104e-06,7.05594e-09,0.409534,0.00135354,-2.75987e-06,1.33633e-08,0.410885,0.00134806,-2.71978e-06,-9.04568e-10,0.41223,0.00134261,-2.72249e-06,2.0057e-08,0.41357,0.00133723,-2.66232e-06,1.00841e-08,0.414905,0.00133194,-2.63207e-06,-7.88835e-10,0.416234,0.00132667,-2.63444e-06,2.28734e-08,0.417558,0.00132147,-2.56582e-06,-1.29785e-09,0.418877,0.00131633,-2.56971e-06,1.21205e-08,0.420191,0.00131123,-2.53335e-06,1.24202e-08,0.421499,0.0013062,-2.49609e-06,-2.19681e-09,0.422803,0.0013012,-2.50268e-06,2.61696e-08,0.424102,0.00129628,-2.42417e-06,-1.30747e-08,0.425396,0.00129139,-2.46339e-06,2.6129e-08,0.426685,0.00128654,-2.38501e-06,-2.03454e-09,0.427969,0.00128176,-2.39111e-06,1.18115e-08,0.429248,0.00127702,-2.35567e-06,1.43932e-08,0.430523,0.00127235,-2.31249e-06,-9.77965e-09,0.431793,0.00126769,-2.34183e-06,2.47253e-08,0.433058,0.00126308,-2.26766e-06,2.85278e-10,0.434319,0.00125855,-2.2668e-06,3.93614e-09,0.435575,0.00125403,-2.25499e-06,1.37722e-08,0.436827,0.00124956,-2.21368e-06,5.79803e-10,0.438074,0.00124513,-2.21194e-06,1.37112e-08,0.439317,0.00124075,-2.1708e-06,4.17973e-09,0.440556,0.00123642,-2.15826e-06,-6.27703e-10,0.44179,0.0012321,-2.16015e-06,2.81332e-08,0.44302,0.00122787,-2.07575e-06,-2.24985e-08,0.444246,0.00122365,-2.14324e-06,3.20586e-08,0.445467,0.00121946,-2.04707e-06,-1.6329e-08,0.446685,0.00121532,-2.09605e-06,3.32573e-08,0.447898,0.00121122,-1.99628e-06,-2.72927e-08,0.449107,0.00120715,-2.07816e-06,4.6111e-08,0.450312,0.00120313,-1.93983e-06,-3.79416e-08,0.451514,0.00119914,-2.05365e-06,4.60507e-08,0.452711,0.00119517,-1.9155e-06,-2.7052e-08,0.453904,0.00119126,-1.99666e-06,3.23551e-08,0.455093,0.00118736,-1.89959e-06,-1.29613e-08,0.456279,0.00118352,-1.93848e-06,1.94905e-08,0.45746,0.0011797,-1.88e-06,-5.39588e-09,0.458638,0.00117593,-1.89619e-06,2.09282e-09,0.459812,0.00117214,-1.88991e-06,2.68267e-08,0.460982,0.00116844,-1.80943e-06,-1.99925e-08,0.462149,0.00116476,-1.86941e-06,2.3341e-08,0.463312,0.00116109,-1.79939e-06,-1.37674e-08,0.464471,0.00115745,-1.84069e-06,3.17287e-08,0.465627,0.00115387,-1.7455e-06,-2.37407e-08,0.466779,0.00115031,-1.81673e-06,3.34315e-08,0.467927,0.00114677,-1.71643e-06,-2.05786e-08,0.469073,0.00114328,-1.77817e-06,1.90802e-08,0.470214,0.00113978,-1.72093e-06,3.86247e-09,0.471352,0.00113635,-1.70934e-06,-4.72759e-09,0.472487,0.00113292,-1.72352e-06,1.50478e-08,0.473618,0.00112951,-1.67838e-06,4.14108e-09,0.474746,0.00112617,-1.66595e-06,-1.80986e-09,0.47587,0.00112283,-1.67138e-06,3.09816e-09,0.476991,0.0011195,-1.66209e-06,1.92198e-08,0.478109,0.00111623,-1.60443e-06,-2.03726e-08,0.479224,0.00111296,-1.66555e-06,3.2468e-08,0.480335,0.00110973,-1.56814e-06,-2.00922e-08,0.481443,0.00110653,-1.62842e-06,1.80983e-08,0.482548,0.00110333,-1.57413e-06,7.30362e-09,0.48365,0.0011002,-1.55221e-06,-1.75107e-08,0.484749,0.00109705,-1.60475e-06,3.29373e-08,0.485844,0.00109393,-1.50594e-06,-2.48315e-08,0.486937,0.00109085,-1.58043e-06,3.65865e-08,0.488026,0.0010878,-1.47067e-06,-3.21078e-08,0.489112,0.00108476,-1.56699e-06,3.22397e-08,0.490195,0.00108172,-1.47027e-06,-7.44391e-09,0.491276,0.00107876,-1.49261e-06,-2.46428e-09,0.492353,0.00107577,-1.5e-06,1.73011e-08,0.493427,0.00107282,-1.4481e-06,-7.13552e-09,0.494499,0.0010699,-1.4695e-06,1.1241e-08,0.495567,0.001067,-1.43578e-06,-8.02637e-09,0.496633,0.0010641,-1.45986e-06,2.08645e-08,0.497695,0.00106124,-1.39726e-06,-1.58271e-08,0.498755,0.0010584,-1.44475e-06,1.26415e-08,0.499812,0.00105555,-1.40682e-06,2.48655e-08,0.500866,0.00105281,-1.33222e-06,-5.24988e-08,0.501918,0.00104999,-1.48972e-06,6.59206e-08,0.502966,0.00104721,-1.29196e-06,-3.237e-08,0.504012,0.00104453,-1.38907e-06,3.95479e-09,0.505055,0.00104176,-1.3772e-06,1.65509e-08,0.506096,0.00103905,-1.32755e-06,-1.05539e-08,0.507133,0.00103637,-1.35921e-06,2.56648e-08,0.508168,0.00103373,-1.28222e-06,-3.25007e-08,0.509201,0.00103106,-1.37972e-06,4.47336e-08,0.51023,0.00102844,-1.24552e-06,-2.72245e-08,0.511258,0.00102587,-1.32719e-06,4.55952e-09,0.512282,0.00102323,-1.31352e-06,8.98645e-09,0.513304,0.00102063,-1.28656e-06,1.90992e-08,0.514323,0.00101811,-1.22926e-06,-2.57786e-08,0.51534,0.00101557,-1.30659e-06,2.44104e-08,0.516355,0.00101303,-1.23336e-06,-1.22581e-08,0.517366,0.00101053,-1.27014e-06,2.4622e-08,0.518376,0.00100806,-1.19627e-06,-2.66253e-08,0.519383,0.00100559,-1.27615e-06,2.22744e-08,0.520387,0.00100311,-1.20932e-06,-2.8679e-09,0.521389,0.00100068,-1.21793e-06,-1.08029e-08,0.522388,0.000998211,-1.25034e-06,4.60795e-08,0.523385,0.000995849,-1.1121e-06,-5.4306e-08,0.52438,0.000993462,-1.27502e-06,5.19354e-08,0.525372,0.000991067,-1.11921e-06,-3.42262e-08,0.526362,0.000988726,-1.22189e-06,2.53646e-08,0.52735,0.000986359,-1.14579e-06,-7.62782e-09,0.528335,0.000984044,-1.16868e-06,5.14668e-09,0.529318,0.000981722,-1.15324e-06,-1.29589e-08,0.530298,0.000979377,-1.19211e-06,4.66888e-08,0.531276,0.000977133,-1.05205e-06,-5.45868e-08,0.532252,0.000974865,-1.21581e-06,5.24495e-08,0.533226,0.000972591,-1.05846e-06,-3.60019e-08,0.534198,0.000970366,-1.16647e-06,3.19537e-08,0.535167,0.000968129,-1.07061e-06,-3.2208e-08,0.536134,0.000965891,-1.16723e-06,3.72738e-08,0.537099,0.000963668,-1.05541e-06,2.32205e-09,0.538061,0.000961564,-1.04844e-06,-4.65618e-08,0.539022,0.000959328,-1.18813e-06,6.47159e-08,0.53998,0.000957146,-9.93979e-07,-3.3488e-08,0.540936,0.000955057,-1.09444e-06,9.63166e-09,0.54189,0.000952897,-1.06555e-06,-5.03871e-09,0.542842,0.000950751,-1.08066e-06,1.05232e-08,0.543792,0.000948621,-1.04909e-06,2.25503e-08,0.544739,0.000946591,-9.81444e-07,-4.11195e-08,0.545685,0.000944504,-1.1048e-06,2.27182e-08,0.546628,0.000942363,-1.03665e-06,9.85146e-09,0.54757,0.000940319,-1.00709e-06,-2.51938e-09,0.548509,0.000938297,-1.01465e-06,2.25858e-10,0.549446,0.000936269,-1.01397e-06,1.61598e-09,0.550381,0.000934246,-1.00913e-06,-6.68983e-09,0.551315,0.000932207,-1.0292e-06,2.51434e-08,0.552246,0.000930224,-9.53765e-07,-3.42793e-08,0.553175,0.000928214,-1.0566e-06,5.23688e-08,0.554102,0.000926258,-8.99497e-07,-5.59865e-08,0.555028,0.000924291,-1.06746e-06,5.23679e-08,0.555951,0.000922313,-9.10352e-07,-3.42763e-08,0.556872,0.00092039,-1.01318e-06,2.51326e-08,0.557792,0.000918439,-9.37783e-07,-6.64954e-09,0.558709,0.000916543,-9.57732e-07,1.46554e-09,0.559625,0.000914632,-9.53335e-07,7.87281e-10,0.560538,0.000912728,-9.50973e-07,-4.61466e-09,0.56145,0.000910812,-9.64817e-07,1.76713e-08,0.56236,0.000908935,-9.11804e-07,-6.46564e-09,0.563268,0.000907092,-9.312e-07,8.19121e-09,0.564174,0.000905255,-9.06627e-07,-2.62992e-08,0.565078,0.000903362,-9.85524e-07,3.74007e-08,0.565981,0.000901504,-8.73322e-07,-4.0942e-09,0.566882,0.000899745,-8.85605e-07,-2.1024e-08,0.56778,0.00089791,-9.48677e-07,2.85854e-08,0.568677,0.000896099,-8.62921e-07,-3.3713e-08,0.569573,0.000894272,-9.64059e-07,4.6662e-08,0.570466,0.000892484,-8.24073e-07,-3.37258e-08,0.571358,0.000890734,-9.25251e-07,2.86365e-08,0.572247,0.00088897,-8.39341e-07,-2.12155e-08,0.573135,0.000887227,-9.02988e-07,-3.37913e-09,0.574022,0.000885411,-9.13125e-07,3.47319e-08,0.574906,0.000883689,-8.08929e-07,-1.63394e-08,0.575789,0.000882022,-8.57947e-07,-2.8979e-08,0.57667,0.00088022,-9.44885e-07,7.26509e-08,0.57755,0.000878548,-7.26932e-07,-8.28106e-08,0.578427,0.000876845,-9.75364e-07,7.97774e-08,0.579303,0.000875134,-7.36032e-07,-5.74849e-08,0.580178,0.00087349,-9.08486e-07,3.09529e-08,0.58105,0.000871765,-8.15628e-07,-6.72206e-09,0.581921,0.000870114,-8.35794e-07,-4.06451e-09,0.582791,0.00086843,-8.47987e-07,2.29799e-08,0.583658,0.000866803,-7.79048e-07,-2.82503e-08,0.584524,0.00086516,-8.63799e-07,3.04167e-08,0.585388,0.000863524,-7.72548e-07,-3.38119e-08,0.586251,0.000861877,-8.73984e-07,4.52264e-08,0.587112,0.000860265,-7.38305e-07,-2.78842e-08,0.587972,0.000858705,-8.21958e-07,6.70567e-09,0.58883,0.000857081,-8.01841e-07,1.06161e-09,0.589686,0.000855481,-7.98656e-07,-1.09521e-08,0.590541,0.00085385,-8.31512e-07,4.27468e-08,0.591394,0.000852316,-7.03272e-07,-4.08257e-08,0.592245,0.000850787,-8.25749e-07,1.34677e-09,0.593095,0.000849139,-8.21709e-07,3.54387e-08,0.593944,0.000847602,-7.15393e-07,-2.38924e-08,0.59479,0.0008461,-7.8707e-07,5.26143e-10,0.595636,0.000844527,-7.85491e-07,2.17879e-08,0.596479,0.000843021,-7.20127e-07,-2.80733e-08,0.597322,0.000841497,-8.04347e-07,3.09005e-08,0.598162,0.000839981,-7.11646e-07,-3.5924e-08,0.599002,0.00083845,-8.19418e-07,5.3191e-08,0.599839,0.000836971,-6.59845e-07,-5.76307e-08,0.600676,0.000835478,-8.32737e-07,5.81227e-08,0.60151,0.000833987,-6.58369e-07,-5.56507e-08,0.602344,0.000832503,-8.25321e-07,4.52706e-08,0.603175,0.000830988,-6.89509e-07,-6.22236e-09,0.604006,0.000829591,-7.08176e-07,-2.03811e-08,0.604834,0.000828113,-7.6932e-07,2.8142e-08,0.605662,0.000826659,-6.84894e-07,-3.25822e-08,0.606488,0.000825191,-7.8264e-07,4.25823e-08,0.607312,0.000823754,-6.54893e-07,-1.85376e-08,0.608135,0.000822389,-7.10506e-07,-2.80365e-08,0.608957,0.000820883,-7.94616e-07,7.1079e-08,0.609777,0.000819507,-5.81379e-07,-7.74655e-08,0.610596,0.000818112,-8.13775e-07,5.9969e-08,0.611413,0.000816665,-6.33868e-07,-4.32013e-08,0.612229,0.000815267,-7.63472e-07,5.32313e-08,0.613044,0.0008139,-6.03778e-07,-5.05148e-08,0.613857,0.000812541,-7.55323e-07,2.96187e-08,0.614669,0.000811119,-6.66466e-07,-8.35545e-09,0.615479,0.000809761,-6.91533e-07,3.80301e-09,0.616288,0.00080839,-6.80124e-07,-6.85666e-09,0.617096,0.000807009,-7.00694e-07,2.36237e-08,0.617903,0.000805678,-6.29822e-07,-2.80336e-08,0.618708,0.000804334,-7.13923e-07,2.8906e-08,0.619511,0.000802993,-6.27205e-07,-2.79859e-08,0.620314,0.000801655,-7.11163e-07,2.34329e-08,0.621114,0.000800303,-6.40864e-07,-6.14108e-09,0.621914,0.000799003,-6.59287e-07,1.13151e-09,0.622712,0.000797688,-6.55893e-07,1.61507e-09,0.62351,0.000796381,-6.51048e-07,-7.59186e-09,0.624305,0.000795056,-6.73823e-07,2.87524e-08,0.6251,0.000793794,-5.87566e-07,-4.7813e-08,0.625893,0.000792476,-7.31005e-07,4.32901e-08,0.626685,0.000791144,-6.01135e-07,-6.13814e-09,0.627475,0.000789923,-6.19549e-07,-1.87376e-08,0.628264,0.000788628,-6.75762e-07,2.14837e-08,0.629052,0.000787341,-6.11311e-07,-7.59265e-09,0.629839,0.000786095,-6.34089e-07,8.88692e-09,0.630625,0.000784854,-6.07428e-07,-2.7955e-08,0.631409,0.000783555,-6.91293e-07,4.33285e-08,0.632192,0.000782302,-5.61307e-07,-2.61497e-08,0.632973,0.000781101,-6.39757e-07,1.6658e-09,0.633754,0.000779827,-6.34759e-07,1.94866e-08,0.634533,0.000778616,-5.76299e-07,-2.00076e-08,0.635311,0.000777403,-6.36322e-07,9.39091e-10,0.636088,0.000776133,-6.33505e-07,1.62512e-08,0.636863,0.000774915,-5.84751e-07,-6.33937e-09,0.637638,0.000773726,-6.03769e-07,9.10609e-09,0.638411,0.000772546,-5.76451e-07,-3.00849e-08,0.639183,0.000771303,-6.66706e-07,5.1629e-08,0.639953,0.000770125,-5.11819e-07,-5.7222e-08,0.640723,0.000768929,-6.83485e-07,5.80497e-08,0.641491,0.000767736,-5.09336e-07,-5.57674e-08,0.642259,0.000766551,-6.76638e-07,4.58105e-08,0.643024,0.000765335,-5.39206e-07,-8.26541e-09,0.643789,0.000764231,-5.64002e-07,-1.27488e-08,0.644553,0.000763065,-6.02249e-07,-3.44168e-10,0.645315,0.00076186,-6.03281e-07,1.41254e-08,0.646077,0.000760695,-5.60905e-07,3.44727e-09,0.646837,0.000759584,-5.50563e-07,-2.79144e-08,0.647596,0.000758399,-6.34307e-07,4.86057e-08,0.648354,0.000757276,-4.88489e-07,-4.72989e-08,0.64911,0.000756158,-6.30386e-07,2.13807e-08,0.649866,0.000754961,-5.66244e-07,2.13808e-08,0.65062,0.000753893,-5.02102e-07,-4.7299e-08,0.651374,0.000752746,-6.43999e-07,4.86059e-08,0.652126,0.000751604,-4.98181e-07,-2.79154e-08,0.652877,0.000750524,-5.81927e-07,3.45089e-09,0.653627,0.000749371,-5.71575e-07,1.41119e-08,0.654376,0.00074827,-5.29239e-07,-2.93748e-10,0.655123,0.00074721,-5.3012e-07,-1.29368e-08,0.65587,0.000746111,-5.68931e-07,-7.56355e-09,0.656616,0.000744951,-5.91621e-07,4.3191e-08,0.65736,0.000743897,-4.62048e-07,-4.59911e-08,0.658103,0.000742835,-6.00022e-07,2.15642e-08,0.658846,0.0007417,-5.35329e-07,1.93389e-08,0.659587,0.000740687,-4.77312e-07,-3.93152e-08,0.660327,0.000739615,-5.95258e-07,1.87126e-08,0.661066,0.00073848,-5.3912e-07,2.40695e-08,0.661804,0.000737474,-4.66912e-07,-5.53859e-08,0.662541,0.000736374,-6.33069e-07,7.82648e-08,0.663277,0.000735343,-3.98275e-07,-7.88593e-08,0.664012,0.00073431,-6.34853e-07,5.83585e-08,0.664745,0.000733215,-4.59777e-07,-3.53656e-08,0.665478,0.000732189,-5.65874e-07,2.34994e-08,0.66621,0.000731128,-4.95376e-07,9.72743e-10,0.66694,0.00073014,-4.92458e-07,-2.73903e-08,0.66767,0.000729073,-5.74629e-07,4.89839e-08,0.668398,0.000728071,-4.27677e-07,-4.93359e-08,0.669126,0.000727068,-5.75685e-07,2.91504e-08,0.669853,0.000726004,-4.88234e-07,-7.66109e-09,0.670578,0.000725004,-5.11217e-07,1.49392e-09,0.671303,0.000723986,-5.06735e-07,1.68533e-09,0.672026,0.000722978,-5.01679e-07,-8.23525e-09,0.672749,0.00072195,-5.26385e-07,3.12556e-08,0.67347,0.000720991,-4.32618e-07,-5.71825e-08,0.674191,0.000719954,-6.04166e-07,7.8265e-08,0.67491,0.00071898,-3.69371e-07,-7.70634e-08,0.675628,0.00071801,-6.00561e-07,5.11747e-08,0.676346,0.000716963,-4.47037e-07,-8.42615e-09,0.677062,0.000716044,-4.72315e-07,-1.747e-08,0.677778,0.000715046,-5.24725e-07,1.87015e-08,0.678493,0.000714053,-4.68621e-07,2.26856e-09,0.679206,0.000713123,-4.61815e-07,-2.77758e-08,0.679919,0.000712116,-5.45142e-07,4.92298e-08,0.68063,0.000711173,-3.97453e-07,-4.99339e-08,0.681341,0.000710228,-5.47255e-07,3.12967e-08,0.682051,0.000709228,-4.53365e-07,-1.56481e-08,0.68276,0.000708274,-5.00309e-07,3.12958e-08,0.683467,0.000707367,-4.06422e-07,-4.99303e-08,0.684174,0.000706405,-5.56213e-07,4.9216e-08,0.68488,0.00070544,-4.08565e-07,-2.77245e-08,0.685585,0.00070454,-4.91738e-07,2.07748e-09,0.686289,0.000703562,-4.85506e-07,1.94146e-08,0.686992,0.00070265,-4.27262e-07,-2.01314e-08,0.687695,0.000701735,-4.87656e-07,1.50616e-09,0.688396,0.000700764,-4.83137e-07,1.41067e-08,0.689096,0.00069984,-4.40817e-07,1.67168e-09,0.689795,0.000698963,-4.35802e-07,-2.07934e-08,0.690494,0.000698029,-4.98182e-07,2.18972e-08,0.691192,0.000697099,-4.32491e-07,-7.19092e-09,0.691888,0.000696212,-4.54064e-07,6.86642e-09,0.692584,0.000695325,-4.33464e-07,-2.02747e-08,0.693279,0.000694397,-4.94288e-07,1.46279e-08,0.693973,0.000693452,-4.50405e-07,2.13678e-08,0.694666,0.000692616,-3.86301e-07,-4.04945e-08,0.695358,0.000691721,-5.07785e-07,2.14009e-08,0.696049,0.00069077,-4.43582e-07,1.44955e-08,0.69674,0.000689926,-4.00096e-07,-1.97783e-08,0.697429,0.000689067,-4.5943e-07,5.01296e-09,0.698118,0.000688163,-4.44392e-07,-2.73521e-10,0.698805,0.000687273,-4.45212e-07,-3.91893e-09,0.699492,0.000686371,-4.56969e-07,1.59493e-08,0.700178,0.000685505,-4.09121e-07,-2.73351e-10,0.700863,0.000684686,-4.09941e-07,-1.4856e-08,0.701548,0.000683822,-4.54509e-07,9.25979e-11,0.702231,0.000682913,-4.54231e-07,1.44855e-08,0.702913,0.000682048,-4.10775e-07,1.56992e-09,0.703595,0.000681231,-4.06065e-07,-2.07652e-08,0.704276,0.000680357,-4.68361e-07,2.18864e-08,0.704956,0.000679486,-4.02701e-07,-7.17595e-09,0.705635,0.000678659,-4.24229e-07,6.81748e-09,0.706313,0.000677831,-4.03777e-07,-2.0094e-08,0.70699,0.000676963,-4.64059e-07,1.39538e-08,0.707667,0.000676077,-4.22197e-07,2.38835e-08,0.708343,0.000675304,-3.50547e-07,-4.98831e-08,0.709018,0.000674453,-5.00196e-07,5.64395e-08,0.709692,0.000673622,-3.30878e-07,-5.66657e-08,0.710365,0.00067279,-5.00875e-07,5.1014e-08,0.711037,0.000671942,-3.47833e-07,-2.81809e-08,0.711709,0.000671161,-4.32376e-07,2.10513e-09,0.712379,0.000670303,-4.2606e-07,1.97604e-08,0.713049,0.00066951,-3.66779e-07,-2.15422e-08,0.713718,0.000668712,-4.31406e-07,6.8038e-09,0.714387,0.000667869,-4.10994e-07,-5.67295e-09,0.715054,0.00066703,-4.28013e-07,1.5888e-08,0.715721,0.000666222,-3.80349e-07,1.72576e-09,0.716387,0.000665467,-3.75172e-07,-2.27911e-08,0.717052,0.000664648,-4.43545e-07,2.9834e-08,0.717716,0.00066385,-3.54043e-07,-3.69401e-08,0.718379,0.000663031,-4.64864e-07,5.83219e-08,0.719042,0.000662277,-2.89898e-07,-7.71382e-08,0.719704,0.000661465,-5.21313e-07,7.14171e-08,0.720365,0.000660637,-3.07061e-07,-2.97161e-08,0.721025,0.000659934,-3.96209e-07,-1.21575e-08,0.721685,0.000659105,-4.32682e-07,1.87412e-08,0.722343,0.000658296,-3.76458e-07,-3.2029e-09,0.723001,0.000657533,-3.86067e-07,-5.9296e-09,0.723659,0.000656743,-4.03856e-07,2.69213e-08,0.724315,0.000656016,-3.23092e-07,-4.21511e-08,0.724971,0.000655244,-4.49545e-07,2.24737e-08,0.725625,0.000654412,-3.82124e-07,1.18611e-08,0.726279,0.000653683,-3.46541e-07,-1.03132e-08,0.726933,0.000652959,-3.7748e-07,-3.02128e-08,0.727585,0.000652114,-4.68119e-07,7.15597e-08,0.728237,0.000651392,-2.5344e-07,-7.72119e-08,0.728888,0.000650654,-4.85075e-07,5.8474e-08,0.729538,0.000649859,-3.09654e-07,-3.74746e-08,0.730188,0.000649127,-4.22077e-07,3.18197e-08,0.730837,0.000648379,-3.26618e-07,-3.01997e-08,0.731485,0.000647635,-4.17217e-07,2.93747e-08,0.732132,0.000646888,-3.29093e-07,-2.76943e-08,0.732778,0.000646147,-4.12176e-07,2.17979e-08,0.733424,0.000645388,-3.46783e-07,1.07292e-10,0.734069,0.000644695,-3.46461e-07,-2.22271e-08,0.734713,0.000643935,-4.13142e-07,2.91963e-08,0.735357,0.000643197,-3.25553e-07,-3.49536e-08,0.736,0.000642441,-4.30414e-07,5.10133e-08,0.736642,0.000641733,-2.77374e-07,-4.98904e-08,0.737283,0.000641028,-4.27045e-07,2.93392e-08,0.737924,0.000640262,-3.39028e-07,-7.86156e-09,0.738564,0.000639561,-3.62612e-07,2.10703e-09,0.739203,0.000638842,-3.56291e-07,-5.6653e-10,0.739842,0.000638128,-3.57991e-07,1.59086e-10,0.740479,0.000637412,-3.57513e-07,-6.98321e-11,0.741116,0.000636697,-3.57723e-07,1.20214e-10,0.741753,0.000635982,-3.57362e-07,-4.10987e-10,0.742388,0.000635266,-3.58595e-07,1.5237e-09,0.743023,0.000634553,-3.54024e-07,-5.68376e-09,0.743657,0.000633828,-3.71075e-07,2.12113e-08,0.744291,0.00063315,-3.07441e-07,-1.95569e-08,0.744924,0.000632476,-3.66112e-07,-2.58816e-09,0.745556,0.000631736,-3.73877e-07,2.99096e-08,0.746187,0.000631078,-2.84148e-07,-5.74454e-08,0.746818,0.000630337,-4.56484e-07,8.06629e-08,0.747448,0.000629666,-2.14496e-07,-8.63922e-08,0.748077,0.000628978,-4.73672e-07,8.60918e-08,0.748706,0.000628289,-2.15397e-07,-7.91613e-08,0.749334,0.000627621,-4.5288e-07,5.17393e-08,0.749961,0.00062687,-2.97663e-07,-8.58662e-09,0.750588,0.000626249,-3.23422e-07,-1.73928e-08,0.751214,0.00062555,-3.75601e-07,1.85532e-08,0.751839,0.000624855,-3.19941e-07,2.78479e-09,0.752463,0.000624223,-3.11587e-07,-2.96923e-08,0.753087,0.000623511,-4.00664e-07,5.63799e-08,0.75371,0.000622879,-2.31524e-07,-7.66179e-08,0.754333,0.000622186,-4.61378e-07,7.12778e-08,0.754955,0.000621477,-2.47545e-07,-2.96794e-08,0.755576,0.000620893,-3.36583e-07,-1.21648e-08,0.756196,0.000620183,-3.73077e-07,1.87339e-08,0.756816,0.000619493,-3.16875e-07,-3.16622e-09,0.757435,0.00061885,-3.26374e-07,-6.0691e-09,0.758054,0.000618179,-3.44581e-07,2.74426e-08,0.758672,0.000617572,-2.62254e-07,-4.40968e-08,0.759289,0.000616915,-3.94544e-07,2.97352e-08,0.759906,0.000616215,-3.05338e-07,-1.52393e-08,0.760522,0.000615559,-3.51056e-07,3.12221e-08,0.761137,0.000614951,-2.5739e-07,-5.00443e-08,0.761751,0.000614286,-4.07523e-07,4.9746e-08,0.762365,0.00061362,-2.58285e-07,-2.97303e-08,0.762979,0.000613014,-3.47476e-07,9.57079e-09,0.763591,0.000612348,-3.18764e-07,-8.55287e-09,0.764203,0.000611685,-3.44422e-07,2.46407e-08,0.764815,0.00061107,-2.705e-07,-3.04053e-08,0.765426,0.000610437,-3.61716e-07,3.73759e-08,0.766036,0.000609826,-2.49589e-07,-5.94935e-08,0.766645,0.000609149,-4.28069e-07,8.13889e-08,0.767254,0.000608537,-1.83902e-07,-8.72483e-08,0.767862,0.000607907,-4.45647e-07,8.87901e-08,0.76847,0.000607282,-1.79277e-07,-8.90983e-08,0.769077,0.000606656,-4.46572e-07,8.87892e-08,0.769683,0.000606029,-1.80204e-07,-8.72446e-08,0.770289,0.000605407,-4.41938e-07,8.13752e-08,0.770894,0.000604768,-1.97812e-07,-5.94423e-08,0.771498,0.000604194,-3.76139e-07,3.71848e-08,0.772102,0.000603553,-2.64585e-07,-2.96922e-08,0.772705,0.000602935,-3.53661e-07,2.19793e-08,0.773308,0.000602293,-2.87723e-07,1.37955e-09,0.77391,0.000601722,-2.83585e-07,-2.74976e-08,0.774512,0.000601072,-3.66077e-07,4.9006e-08,0.775112,0.000600487,-2.19059e-07,-4.93171e-08,0.775712,0.000599901,-3.67011e-07,2.90531e-08,0.776312,0.000599254,-2.79851e-07,-7.29081e-09,0.776911,0.000598673,-3.01724e-07,1.10077e-10,0.777509,0.00059807,-3.01393e-07,6.85053e-09,0.778107,0.000597487,-2.80842e-07,-2.75123e-08,0.778704,0.000596843,-3.63379e-07,4.35939e-08,0.779301,0.000596247,-2.32597e-07,-2.7654e-08,0.779897,0.000595699,-3.15559e-07,7.41741e-09,0.780492,0.00059509,-2.93307e-07,-2.01562e-09,0.781087,0.000594497,-2.99354e-07,6.45059e-10,0.781681,0.000593901,-2.97418e-07,-5.64635e-10,0.782275,0.000593304,-2.99112e-07,1.61347e-09,0.782868,0.000592711,-2.94272e-07,-5.88926e-09,0.78346,0.000592105,-3.1194e-07,2.19436e-08,0.784052,0.000591546,-2.46109e-07,-2.22805e-08,0.784643,0.000590987,-3.1295e-07,7.57368e-09,0.785234,0.000590384,-2.90229e-07,-8.01428e-09,0.785824,0.00058978,-3.14272e-07,2.44834e-08,0.786414,0.000589225,-2.40822e-07,-3.03148e-08,0.787003,0.000588652,-3.31766e-07,3.7171e-08,0.787591,0.0005881,-2.20253e-07,-5.87646e-08,0.788179,0.000587483,-3.96547e-07,7.86782e-08,0.788766,0.000586926,-1.60512e-07,-7.71342e-08,0.789353,0.000586374,-3.91915e-07,5.10444e-08,0.789939,0.000585743,-2.38782e-07,-7.83422e-09,0.790524,0.000585242,-2.62284e-07,-1.97076e-08,0.791109,0.000584658,-3.21407e-07,2.70598e-08,0.791693,0.000584097,-2.40228e-07,-2.89269e-08,0.792277,0.000583529,-3.27008e-07,2.90431e-08,0.792861,0.000582963,-2.39879e-07,-2.76409e-08,0.793443,0.0005824,-3.22802e-07,2.1916e-08,0.794025,0.00058182,-2.57054e-07,-4.18368e-10,0.794607,0.000581305,-2.58309e-07,-2.02425e-08,0.795188,0.000580727,-3.19036e-07,2.17838e-08,0.795768,0.000580155,-2.53685e-07,-7.28814e-09,0.796348,0.000579625,-2.75549e-07,7.36871e-09,0.796928,0.000579096,-2.53443e-07,-2.21867e-08,0.797506,0.000578523,-3.20003e-07,2.17736e-08,0.798085,0.000577948,-2.54683e-07,-5.30296e-09,0.798662,0.000577423,-2.70592e-07,-5.61698e-10,0.799239,0.00057688,-2.72277e-07,7.54977e-09,0.799816,0.000576358,-2.49627e-07,-2.96374e-08,0.800392,0.00057577,-3.38539e-07,5.1395e-08,0.800968,0.000575247,-1.84354e-07,-5.67335e-08,0.801543,0.000574708,-3.54555e-07,5.63297e-08,0.802117,0.000574168,-1.85566e-07,-4.93759e-08,0.802691,0.000573649,-3.33693e-07,2.19646e-08,0.803264,0.000573047,-2.678e-07,2.1122e-08,0.803837,0.000572575,-2.04433e-07,-4.68482e-08,0.804409,0.000572026,-3.44978e-07,4.70613e-08,0.804981,0.000571477,-2.03794e-07,-2.21877e-08,0.805552,0.000571003,-2.70357e-07,-1.79153e-08,0.806123,0.000570408,-3.24103e-07,3.42443e-08,0.806693,0.000569863,-2.2137e-07,1.47556e-10,0.807263,0.000569421,-2.20928e-07,-3.48345e-08,0.807832,0.000568874,-3.25431e-07,1.99812e-08,0.808401,0.000568283,-2.65487e-07,1.45143e-08,0.808969,0.000567796,-2.21945e-07,-1.84338e-08,0.809536,0.000567297,-2.77246e-07,-3.83608e-10,0.810103,0.000566741,-2.78397e-07,1.99683e-08,0.81067,0.000566244,-2.18492e-07,-1.98848e-08,0.811236,0.000565747,-2.78146e-07,-3.38976e-11,0.811801,0.000565191,-2.78248e-07,2.00204e-08,0.812366,0.000564695,-2.18187e-07,-2.04429e-08,0.812931,0.000564197,-2.79516e-07,2.1467e-09,0.813495,0.000563644,-2.73076e-07,1.18561e-08,0.814058,0.000563134,-2.37507e-07,1.00334e-08,0.814621,0.000562689,-2.07407e-07,-5.19898e-08,0.815183,0.000562118,-3.63376e-07,7.87163e-08,0.815745,0.000561627,-1.27227e-07,-8.40616e-08,0.816306,0.000561121,-3.79412e-07,7.87163e-08,0.816867,0.000560598,-1.43263e-07,-5.19898e-08,0.817428,0.000560156,-2.99233e-07,1.00335e-08,0.817988,0.000559587,-2.69132e-07,1.18559e-08,0.818547,0.000559085,-2.33564e-07,2.14764e-09,0.819106,0.000558624,-2.27122e-07,-2.04464e-08,0.819664,0.000558108,-2.88461e-07,2.00334e-08,0.820222,0.000557591,-2.28361e-07,-8.24277e-11,0.820779,0.000557135,-2.28608e-07,-1.97037e-08,0.821336,0.000556618,-2.87719e-07,1.92925e-08,0.821893,0.000556101,-2.29841e-07,2.13831e-09,0.822448,0.000555647,-2.23427e-07,-2.78458e-08,0.823004,0.000555117,-3.06964e-07,4.96402e-08,0.823559,0.000554652,-1.58043e-07,-5.15058e-08,0.824113,0.000554181,-3.12561e-07,3.71737e-08,0.824667,0.000553668,-2.0104e-07,-3.75844e-08,0.82522,0.000553153,-3.13793e-07,5.35592e-08,0.825773,0.000552686,-1.53115e-07,-5.74431e-08,0.826326,0.000552207,-3.25444e-07,5.7004e-08,0.826878,0.000551728,-1.54433e-07,-5.13635e-08,0.827429,0.000551265,-3.08523e-07,2.92406e-08,0.82798,0.000550735,-2.20801e-07,-5.99424e-09,0.828531,0.000550276,-2.38784e-07,-5.26363e-09,0.829081,0.000549782,-2.54575e-07,2.70488e-08,0.82963,0.000549354,-1.73429e-07,-4.33268e-08,0.83018,0.000548878,-3.03409e-07,2.7049e-08,0.830728,0.000548352,-2.22262e-07,-5.26461e-09,0.831276,0.000547892,-2.38056e-07,-5.99057e-09,0.831824,0.000547397,-2.56027e-07,2.92269e-08,0.832371,0.000546973,-1.68347e-07,-5.13125e-08,0.832918,0.000546482,-3.22284e-07,5.68139e-08,0.833464,0.000546008,-1.51843e-07,-5.67336e-08,0.83401,0.000545534,-3.22043e-07,5.09113e-08,0.834555,0.000545043,-1.6931e-07,-2.77022e-08,0.8351,0.000544621,-2.52416e-07,2.92924e-10,0.835644,0.000544117,-2.51537e-07,2.65305e-08,0.836188,0.000543694,-1.71946e-07,-4.68105e-08,0.836732,0.00054321,-3.12377e-07,4.15021e-08,0.837275,0.000542709,-1.87871e-07,1.13355e-11,0.837817,0.000542334,-1.87837e-07,-4.15474e-08,0.838359,0.000541833,-3.12479e-07,4.69691e-08,0.838901,0.000541349,-1.71572e-07,-2.71196e-08,0.839442,0.000540925,-2.52931e-07,1.90462e-09,0.839983,0.000540425,-2.47217e-07,1.95011e-08,0.840523,0.000539989,-1.88713e-07,-2.03045e-08,0.841063,0.00053955,-2.49627e-07,2.11216e-09,0.841602,0.000539057,-2.4329e-07,1.18558e-08,0.842141,0.000538606,-2.07723e-07,1.00691e-08,0.842679,0.000538221,-1.77516e-07,-5.21324e-08,0.843217,0.00053771,-3.33913e-07,7.92513e-08,0.843755,0.00053728,-9.6159e-08,-8.60587e-08,0.844292,0.000536829,-3.54335e-07,8.61696e-08,0.844828,0.000536379,-9.58263e-08,-7.98057e-08,0.845364,0.000535948,-3.35243e-07,5.42394e-08,0.8459,0.00053544,-1.72525e-07,-1.79426e-08,0.846435,0.000535041,-2.26353e-07,1.75308e-08,0.84697,0.000534641,-1.73761e-07,-5.21806e-08,0.847505,0.000534137,-3.30302e-07,7.19824e-08,0.848038,0.000533692,-1.14355e-07,-5.69349e-08,0.848572,0.000533293,-2.8516e-07,3.65479e-08,0.849105,0.000532832,-1.75516e-07,-2.96519e-08,0.849638,0.000532392,-2.64472e-07,2.2455e-08,0.85017,0.000531931,-1.97107e-07,-5.63451e-10,0.850702,0.000531535,-1.98797e-07,-2.02011e-08,0.851233,0.000531077,-2.59401e-07,2.17634e-08,0.851764,0.000530623,-1.94111e-07,-7.24794e-09,0.852294,0.000530213,-2.15854e-07,7.22832e-09,0.852824,0.000529803,-1.94169e-07,-2.16653e-08,0.853354,0.00052935,-2.59165e-07,1.98283e-08,0.853883,0.000528891,-1.9968e-07,1.95678e-09,0.854412,0.000528497,-1.9381e-07,-2.76554e-08,0.85494,0.000528027,-2.76776e-07,4.90603e-08,0.855468,0.00052762,-1.29596e-07,-4.93764e-08,0.855995,0.000527213,-2.77725e-07,2.92361e-08,0.856522,0.000526745,-1.90016e-07,-7.96341e-09,0.857049,0.000526341,-2.13907e-07,2.61752e-09,0.857575,0.000525922,-2.06054e-07,-2.50665e-09,0.8581,0.000525502,-2.13574e-07,7.40906e-09,0.858626,0.000525097,-1.91347e-07,-2.71296e-08,0.859151,0.000524633,-2.72736e-07,4.15048e-08,0.859675,0.000524212,-1.48221e-07,-1.96802e-08,0.860199,0.000523856,-2.07262e-07,-2.23886e-08,0.860723,0.000523375,-2.74428e-07,4.96299e-08,0.861246,0.000522975,-1.25538e-07,-5.69216e-08,0.861769,0.000522553,-2.96303e-07,5.88473e-08,0.862291,0.000522137,-1.19761e-07,-5.92584e-08,0.862813,0.00052172,-2.97536e-07,5.8977e-08,0.863334,0.000521301,-1.20605e-07,-5.74403e-08,0.863855,0.000520888,-2.92926e-07,5.15751e-08,0.864376,0.000520457,-1.38201e-07,-2.96506e-08,0.864896,0.000520091,-2.27153e-07,7.42277e-09,0.865416,0.000519659,-2.04885e-07,-4.05057e-11,0.865936,0.00051925,-2.05006e-07,-7.26074e-09,0.866455,0.000518818,-2.26788e-07,2.90835e-08,0.866973,0.000518451,-1.39538e-07,-4.94686e-08,0.867492,0.000518024,-2.87944e-07,4.95814e-08,0.868009,0.000517597,-1.39199e-07,-2.96479e-08,0.868527,0.000517229,-2.28143e-07,9.40539e-09,0.869044,0.000516801,-1.99927e-07,-7.9737e-09,0.86956,0.000516378,-2.23848e-07,2.24894e-08,0.870077,0.000515997,-1.5638e-07,-2.23793e-08,0.870592,0.000515617,-2.23517e-07,7.42302e-09,0.871108,0.000515193,-2.01248e-07,-7.31283e-09,0.871623,0.000514768,-2.23187e-07,2.18283e-08,0.872137,0.000514387,-1.57702e-07,-2.03959e-08,0.872652,0.000514011,-2.1889e-07,1.50711e-10,0.873165,0.000513573,-2.18437e-07,1.97931e-08,0.873679,0.000513196,-1.59058e-07,-1.97183e-08,0.874192,0.000512819,-2.18213e-07,-5.24324e-10,0.874704,0.000512381,-2.19786e-07,2.18156e-08,0.875217,0.000512007,-1.54339e-07,-2.71336e-08,0.875728,0.000511616,-2.3574e-07,2.71141e-08,0.87624,0.000511226,-1.54398e-07,-2.17182e-08,0.876751,0.000510852,-2.19552e-07,1.54131e-10,0.877262,0.000510414,-2.1909e-07,2.11017e-08,0.877772,0.000510039,-1.55785e-07,-2.49562e-08,0.878282,0.000509652,-2.30654e-07,1.91183e-08,0.878791,0.000509248,-1.73299e-07,8.08751e-09,0.8793,0.000508926,-1.49036e-07,-5.14684e-08,0.879809,0.000508474,-3.03441e-07,7.85766e-08,0.880317,0.000508103,-6.77112e-08,-8.40242e-08,0.880825,0.000507715,-3.19784e-07,7.87063e-08,0.881333,0.000507312,-8.36649e-08,-5.19871e-08,0.88184,0.000506988,-2.39626e-07,1.00327e-08,0.882346,0.000506539,-2.09528e-07,1.18562e-08,0.882853,0.000506156,-1.73959e-07,2.14703e-09,0.883359,0.000505814,-1.67518e-07,-2.04444e-08,0.883864,0.000505418,-2.28851e-07,2.00258e-08,0.88437,0.00050502,-1.68774e-07,-5.42855e-11,0.884874,0.000504682,-1.68937e-07,-1.98087e-08,0.885379,0.000504285,-2.28363e-07,1.96842e-08,0.885883,0.000503887,-1.6931e-07,6.76342e-10,0.886387,0.000503551,-1.67281e-07,-2.23896e-08,0.88689,0.000503149,-2.3445e-07,2.92774e-08,0.887393,0.000502768,-1.46618e-07,-3.51152e-08,0.887896,0.00050237,-2.51963e-07,5.15787e-08,0.888398,0.00050202,-9.72271e-08,-5.19903e-08,0.8889,0.00050167,-2.53198e-07,3.71732e-08,0.889401,0.000501275,-1.41678e-07,-3.70978e-08,0.889902,0.00050088,-2.52972e-07,5.16132e-08,0.890403,0.000500529,-9.81321e-08,-5.01459e-08,0.890903,0.000500183,-2.4857e-07,2.9761e-08,0.891403,0.000499775,-1.59287e-07,-9.29351e-09,0.891903,0.000499428,-1.87167e-07,7.41301e-09,0.892402,0.000499076,-1.64928e-07,-2.03585e-08,0.892901,0.000498685,-2.26004e-07,1.44165e-08,0.893399,0.000498276,-1.82754e-07,2.22974e-08,0.893898,0.000497978,-1.15862e-07,-4.40013e-08,0.894395,0.000497614,-2.47866e-07,3.44985e-08,0.894893,0.000497222,-1.44371e-07,-3.43882e-08,0.89539,0.00049683,-2.47535e-07,4.34497e-08,0.895886,0.000496465,-1.17186e-07,-2.02012e-08,0.896383,0.00049617,-1.7779e-07,-2.22497e-08,0.896879,0.000495748,-2.44539e-07,4.95952e-08,0.897374,0.000495408,-9.57532e-08,-5.69217e-08,0.89787,0.000495045,-2.66518e-07,5.88823e-08,0.898364,0.000494689,-8.98713e-08,-5.93983e-08,0.898859,0.000494331,-2.68066e-07,5.95017e-08,0.899353,0.000493973,-8.95613e-08,-5.9399e-08,0.899847,0.000493616,-2.67758e-07,5.8885e-08,0.90034,0.000493257,-9.11033e-08,-5.69317e-08,0.900833,0.000492904,-2.61898e-07,4.96326e-08,0.901326,0.000492529,-1.13001e-07,-2.23893e-08,0.901819,0.000492236,-1.80169e-07,-1.968e-08,0.902311,0.000491817,-2.39209e-07,4.15047e-08,0.902802,0.000491463,-1.14694e-07,-2.71296e-08,0.903293,0.000491152,-1.96083e-07,7.409e-09,0.903784,0.000490782,-1.73856e-07,-2.50645e-09,0.904275,0.000490427,-1.81376e-07,2.61679e-09,0.904765,0.000490072,-1.73525e-07,-7.96072e-09,0.905255,0.000489701,-1.97407e-07,2.92261e-08,0.905745,0.000489394,-1.09729e-07,-4.93389e-08,0.906234,0.000489027,-2.57746e-07,4.89204e-08,0.906723,0.000488658,-1.10985e-07,-2.71333e-08,0.907211,0.000488354,-1.92385e-07,8.30861e-12,0.907699,0.00048797,-1.9236e-07,2.71001e-08,0.908187,0.000487666,-1.1106e-07,-4.88041e-08,0.908675,0.000487298,-2.57472e-07,4.89069e-08,0.909162,0.000486929,-1.10751e-07,-2.76143e-08,0.909649,0.000486625,-1.93594e-07,1.9457e-09,0.910135,0.000486244,-1.87757e-07,1.98315e-08,0.910621,0.000485928,-1.28262e-07,-2.16671e-08,0.911107,0.000485606,-1.93264e-07,7.23216e-09,0.911592,0.000485241,-1.71567e-07,-7.26152e-09,0.912077,0.000484877,-1.93352e-07,2.18139e-08,0.912562,0.000484555,-1.2791e-07,-2.03895e-08,0.913047,0.000484238,-1.89078e-07,1.39494e-10,0.913531,0.000483861,-1.8866e-07,1.98315e-08,0.914014,0.000483543,-1.29165e-07,-1.98609e-08,0.914498,0.000483225,-1.88748e-07,7.39912e-12,0.914981,0.000482847,-1.88726e-07,1.98313e-08,0.915463,0.000482529,-1.29232e-07,-1.9728e-08,0.915946,0.000482212,-1.88416e-07,-5.24035e-10,0.916428,0.000481833,-1.89988e-07,2.18241e-08,0.916909,0.000481519,-1.24516e-07,-2.71679e-08,0.917391,0.000481188,-2.06019e-07,2.72427e-08,0.917872,0.000480858,-1.24291e-07,-2.21985e-08,0.918353,0.000480543,-1.90886e-07,1.94644e-09,0.918833,0.000480167,-1.85047e-07,1.44127e-08,0.919313,0.00047984,-1.41809e-07,7.39438e-12,0.919793,0.000479556,-1.41787e-07,-1.44423e-08,0.920272,0.000479229,-1.85114e-07,-1.84291e-09,0.920751,0.000478854,-1.90642e-07,2.18139e-08,0.92123,0.000478538,-1.25201e-07,-2.58081e-08,0.921708,0.00047821,-2.02625e-07,2.18139e-08,0.922186,0.00047787,-1.37183e-07,-1.84291e-09,0.922664,0.00047759,-1.42712e-07,-1.44423e-08,0.923141,0.000477262,-1.86039e-07,7.34701e-12,0.923618,0.00047689,-1.86017e-07,1.44129e-08,0.924095,0.000476561,-1.42778e-07,1.94572e-09,0.924572,0.000476281,-1.36941e-07,-2.21958e-08,0.925048,0.000475941,-2.03528e-07,2.72327e-08,0.925523,0.000475615,-1.2183e-07,-2.71304e-08,0.925999,0.00047529,-2.03221e-07,2.16843e-08,0.926474,0.000474949,-1.38168e-07,-2.16005e-12,0.926949,0.000474672,-1.38175e-07,-2.16756e-08,0.927423,0.000474331,-2.03202e-07,2.71001e-08,0.927897,0.000474006,-1.21902e-07,-2.71201e-08,0.928371,0.000473681,-2.03262e-07,2.17757e-08,0.928845,0.00047334,-1.37935e-07,-3.78028e-10,0.929318,0.000473063,-1.39069e-07,-2.02636e-08,0.929791,0.000472724,-1.9986e-07,2.18276e-08,0.930263,0.000472389,-1.34377e-07,-7.44231e-09,0.930736,0.000472098,-1.56704e-07,7.94165e-09,0.931208,0.000471809,-1.32879e-07,-2.43243e-08,0.931679,0.00047147,-2.05851e-07,2.97508e-08,0.932151,0.000471148,-1.16599e-07,-3.50742e-08,0.932622,0.000470809,-2.21822e-07,5.09414e-08,0.933092,0.000470518,-6.89976e-08,-4.94821e-08,0.933563,0.000470232,-2.17444e-07,2.77775e-08,0.934033,0.00046988,-1.34111e-07,-2.02351e-09,0.934502,0.000469606,-1.40182e-07,-1.96835e-08,0.934972,0.000469267,-1.99232e-07,2.11529e-08,0.935441,0.000468932,-1.35774e-07,-5.32332e-09,0.93591,0.000468644,-1.51743e-07,1.40413e-10,0.936378,0.000468341,-1.51322e-07,4.76166e-09,0.936846,0.000468053,-1.37037e-07,-1.9187e-08,0.937314,0.000467721,-1.94598e-07,1.23819e-08,0.937782,0.000467369,-1.57453e-07,2.92642e-08,0.938249,0.000467142,-6.96601e-08,-6.98342e-08,0.938716,0.000466793,-2.79163e-07,7.12586e-08,0.939183,0.000466449,-6.53869e-08,-3.63863e-08,0.939649,0.000466209,-1.74546e-07,1.46818e-08,0.940115,0.000465904,-1.305e-07,-2.2341e-08,0.940581,0.000465576,-1.97523e-07,1.50774e-08,0.941046,0.000465226,-1.52291e-07,2.16359e-08,0.941511,0.000464986,-8.73832e-08,-4.20162e-08,0.941976,0.000464685,-2.13432e-07,2.72198e-08,0.942441,0.00046434,-1.31773e-07,-7.2581e-09,0.942905,0.000464055,-1.53547e-07,1.81263e-09,0.943369,0.000463753,-1.48109e-07,7.58386e-12,0.943832,0.000463457,-1.48086e-07,-1.84298e-09,0.944296,0.000463155,-1.53615e-07,7.36433e-09,0.944759,0.00046287,-1.31522e-07,-2.76143e-08,0.945221,0.000462524,-2.14365e-07,4.34883e-08,0.945684,0.000462226,-8.39003e-08,-2.71297e-08,0.946146,0.000461977,-1.65289e-07,5.42595e-09,0.946608,0.000461662,-1.49012e-07,5.42593e-09,0.947069,0.000461381,-1.32734e-07,-2.71297e-08,0.94753,0.000461034,-2.14123e-07,4.34881e-08,0.947991,0.000460736,-8.36585e-08,-2.76134e-08,0.948452,0.000460486,-1.66499e-07,7.36083e-09,0.948912,0.000460175,-1.44416e-07,-1.82993e-09,0.949372,0.000459881,-1.49906e-07,-4.11073e-11,0.949832,0.000459581,-1.50029e-07,1.99434e-09,0.950291,0.000459287,-1.44046e-07,-7.93627e-09,0.950751,0.000458975,-1.67855e-07,2.97507e-08,0.951209,0.000458728,-7.86029e-08,-5.1462e-08,0.951668,0.000458417,-2.32989e-07,5.6888e-08,0.952126,0.000458121,-6.2325e-08,-5.68806e-08,0.952584,0.000457826,-2.32967e-07,5.14251e-08,0.953042,0.000457514,-7.86914e-08,-2.96107e-08,0.953499,0.000457268,-1.67523e-07,7.41296e-09,0.953956,0.000456955,-1.45285e-07,-4.11262e-11,0.954413,0.000456665,-1.45408e-07,-7.24847e-09,0.95487,0.000456352,-1.67153e-07,2.9035e-08,0.955326,0.000456105,-8.00484e-08,-4.92869e-08,0.955782,0.000455797,-2.27909e-07,4.89032e-08,0.956238,0.000455488,-8.11994e-08,-2.71166e-08,0.956693,0.000455244,-1.62549e-07,-4.13678e-11,0.957148,0.000454919,-1.62673e-07,2.72821e-08,0.957603,0.000454675,-8.0827e-08,-4.94824e-08,0.958057,0.000454365,-2.29274e-07,5.14382e-08,0.958512,0.000454061,-7.49597e-08,-3.7061e-08,0.958965,0.0004538,-1.86143e-07,3.72013e-08,0.959419,0.000453539,-7.45389e-08,-5.21396e-08,0.959873,0.000453234,-2.30958e-07,5.21476e-08,0.960326,0.000452928,-7.45146e-08,-3.72416e-08,0.960778,0.000452667,-1.8624e-07,3.72143e-08,0.961231,0.000452407,-7.45967e-08,-5.20109e-08,0.961683,0.000452101,-2.30629e-07,5.16199e-08,0.962135,0.000451795,-7.57696e-08,-3.52595e-08,0.962587,0.000451538,-1.81548e-07,2.98133e-08,0.963038,0.000451264,-9.2108e-08,-2.43892e-08,0.963489,0.000451007,-1.65276e-07,8.13892e-09,0.96394,0.000450701,-1.40859e-07,-8.16647e-09,0.964391,0.000450394,-1.65358e-07,2.45269e-08,0.964841,0.000450137,-9.17775e-08,-3.03367e-08,0.965291,0.000449863,-1.82787e-07,3.7215e-08,0.965741,0.000449609,-7.11424e-08,-5.89188e-08,0.96619,0.00044929,-2.47899e-07,7.92509e-08,0.966639,0.000449032,-1.01462e-08,-7.92707e-08,0.967088,0.000448773,-2.47958e-07,5.90181e-08,0.967537,0.000448455,-7.0904e-08,-3.75925e-08,0.967985,0.0004482,-1.83681e-07,3.17471e-08,0.968433,0.000447928,-8.84401e-08,-2.97913e-08,0.968881,0.000447662,-1.77814e-07,2.78133e-08,0.969329,0.000447389,-9.4374e-08,-2.18572e-08,0.969776,0.000447135,-1.59946e-07,1.10134e-11,0.970223,0.000446815,-1.59913e-07,2.18132e-08,0.97067,0.000446561,-9.44732e-08,-2.76591e-08,0.971116,0.000446289,-1.7745e-07,2.92185e-08,0.971562,0.000446022,-8.97948e-08,-2.96104e-08,0.972008,0.000445753,-1.78626e-07,2.96185e-08,0.972454,0.000445485,-8.97706e-08,-2.92588e-08,0.972899,0.000445218,-1.77547e-07,2.78123e-08,0.973344,0.000444946,-9.41103e-08,-2.23856e-08,0.973789,0.000444691,-1.61267e-07,2.12559e-09,0.974233,0.000444374,-1.5489e-07,1.38833e-08,0.974678,0.000444106,-1.13241e-07,1.94591e-09,0.975122,0.000443886,-1.07403e-07,-2.16669e-08,0.975565,0.000443606,-1.72404e-07,2.5117e-08,0.976009,0.000443336,-9.70526e-08,-1.91963e-08,0.976452,0.000443085,-1.54642e-07,-7.93627e-09,0.976895,0.000442752,-1.7845e-07,5.09414e-08,0.977338,0.000442548,-2.56262e-08,-7.66201e-08,0.97778,0.000442266,-2.55486e-07,7.67249e-08,0.978222,0.000441986,-2.53118e-08,-5.14655e-08,0.978664,0.000441781,-1.79708e-07,9.92773e-09,0.979106,0.000441451,-1.49925e-07,1.17546e-08,0.979547,0.000441186,-1.14661e-07,2.65868e-09,0.979988,0.000440965,-1.06685e-07,-2.23893e-08,0.980429,0.000440684,-1.73853e-07,2.72939e-08,0.980869,0.000440419,-9.19716e-08,-2.71816e-08,0.98131,0.000440153,-1.73516e-07,2.18278e-08,0.98175,0.000439872,-1.08033e-07,-5.24833e-10,0.982189,0.000439654,-1.09607e-07,-1.97284e-08,0.982629,0.000439376,-1.68793e-07,1.98339e-08,0.983068,0.000439097,-1.09291e-07,-2.62901e-12,0.983507,0.000438879,-1.09299e-07,-1.98234e-08,0.983946,0.000438601,-1.68769e-07,1.96916e-08,0.984384,0.000438322,-1.09694e-07,6.6157e-10,0.984823,0.000438105,-1.0771e-07,-2.23379e-08,0.985261,0.000437823,-1.74723e-07,2.90855e-08,0.985698,0.00043756,-8.74669e-08,-3.43992e-08,0.986136,0.000437282,-1.90665e-07,4.89068e-08,0.986573,0.000437048,-4.39442e-08,-4.20188e-08,0.98701,0.000436834,-1.7e-07,-4.11073e-11,0.987446,0.000436494,-1.70124e-07,4.21832e-08,0.987883,0.00043628,-4.35742e-08,-4.94824e-08,0.988319,0.000436044,-1.92021e-07,3.6537e-08,0.988755,0.00043577,-8.24102e-08,-3.70611e-08,0.989191,0.000435494,-1.93593e-07,5.21026e-08,0.989626,0.000435263,-3.72855e-08,-5.21402e-08,0.990061,0.000435032,-1.93706e-07,3.7249e-08,0.990496,0.000434756,-8.19592e-08,-3.72512e-08,0.990931,0.000434481,-1.93713e-07,5.21511e-08,0.991365,0.00043425,-3.72595e-08,-5.21439e-08,0.991799,0.000434019,-1.93691e-07,3.72152e-08,0.992233,0.000433743,-8.20456e-08,-3.71123e-08,0.992667,0.000433468,-1.93382e-07,5.16292e-08,0.9931,0.000433236,-3.84947e-08,-5.01953e-08,0.993533,0.000433008,-1.89081e-07,2.99427e-08,0.993966,0.00043272,-9.92525e-08,-9.9708e-09,0.994399,0.000432491,-1.29165e-07,9.94051e-09,0.994831,0.000432263,-9.93434e-08,-2.97912e-08,0.995263,0.000431975,-1.88717e-07,4.96198e-08,0.995695,0.000431746,-3.98578e-08,-4.94785e-08,0.996127,0.000431518,-1.88293e-07,2.9085e-08,0.996558,0.000431229,-1.01038e-07,-7.25675e-09,0.996989,0.000431005,-1.22809e-07,-5.79945e-11,0.99742,0.000430759,-1.22983e-07,7.48873e-09,0.997851,0.000430536,-1.00516e-07,-2.98969e-08,0.998281,0.000430245,-1.90207e-07,5.24942e-08,0.998711,0.000430022,-3.27246e-08,-6.08706e-08,0.999141,0.000429774,-2.15336e-07,7.17788e-08,0.999571,0.000429392,0.,0.}; template __device__ __forceinline__ void Lab2RGBConvert_f(const T& src, D& dst) { const float lThresh = 0.008856f * 903.3f; const float fThresh = 7.787f * 0.008856f + 16.0f / 116.0f; float Y, fy; if (src.x <= lThresh) { Y = src.x / 903.3f; fy = 7.787f * Y + 16.0f / 116.0f; } else { fy = (src.x + 16.0f) / 116.0f; Y = fy * fy * fy; } float X = src.y / 500.0f + fy; float Z = fy - src.z / 200.0f; if (X <= fThresh) X = (X - 16.0f / 116.0f) / 7.787f; else X = X * X * X; if (Z <= fThresh) Z = (Z - 16.0f / 116.0f) / 7.787f; else Z = Z * Z * Z; float B = 0.052891f * X - 0.204043f * Y + 1.151152f * Z; float G = -0.921235f * X + 1.875991f * Y + 0.045244f * Z; float R = 3.079933f * X - 1.537150f * Y - 0.542782f * Z; if (srgb) { B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); } dst.x = blueIdx == 0 ? B : R; dst.y = G; dst.z = blueIdx == 0 ? R : B; setAlpha(dst, ColorChannel::max()); } template __device__ __forceinline__ void Lab2RGBConvert_b(const T& src, D& dst) { float3 srcf, dstf; srcf.x = src.x * (100.f / 255.f); srcf.y = src.y - 128; srcf.z = src.z - 128; Lab2RGBConvert_f(srcf, dstf); dst.x = saturate_cast(dstf.x * 255.f); dst.y = saturate_cast(dstf.y * 255.f); dst.z = saturate_cast(dstf.z * 255.f); setAlpha(dst, ColorChannel::max()); } template struct Lab2RGB; template struct Lab2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; Lab2RGBConvert_b(src, dst); return dst; } __host__ __device__ __forceinline__ Lab2RGB() {} __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} }; template struct Lab2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; Lab2RGBConvert_f(src, dst); return dst; } __host__ __device__ __forceinline__ Lab2RGB() {} __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::Lab2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; ///////////////////////////////////// RGB <-> Luv ///////////////////////////////////// namespace color_detail { __constant__ float c_LabCbrtTab[] = {0.137931,0.0114066,0.,1.18859e-07,0.149338,0.011407,3.56578e-07,-5.79396e-07,0.160745,0.0114059,-1.38161e-06,2.16892e-06,0.172151,0.0114097,5.12516e-06,-8.0814e-06,0.183558,0.0113957,-1.9119e-05,3.01567e-05,0.194965,0.0114479,7.13509e-05,-0.000112545,0.206371,0.011253,-0.000266285,-0.000106493,0.217252,0.0104009,-0.000585765,7.32149e-05,0.22714,0.00944906,-0.00036612,1.21917e-05,0.236235,0.0087534,-0.000329545,2.01753e-05,0.244679,0.00815483,-0.000269019,1.24435e-05,0.252577,0.00765412,-0.000231689,1.05618e-05,0.26001,0.00722243,-0.000200003,8.26662e-06,0.267041,0.00684723,-0.000175203,6.76746e-06,0.27372,0.00651712,-0.000154901,5.61192e-06,0.280088,0.00622416,-0.000138065,4.67009e-06,0.286179,0.00596204,-0.000124055,3.99012e-06,0.292021,0.0057259,-0.000112085,3.36032e-06,0.297638,0.00551181,-0.000102004,2.95338e-06,0.30305,0.00531666,-9.31435e-05,2.52875e-06,0.308277,0.00513796,-8.55572e-05,2.22022e-06,0.313331,0.00497351,-7.88966e-05,1.97163e-06,0.318228,0.00482163,-7.29817e-05,1.7248e-06,0.322978,0.00468084,-6.78073e-05,1.55998e-06,0.327593,0.0045499,-6.31274e-05,1.36343e-06,0.332081,0.00442774,-5.90371e-05,1.27136e-06,0.336451,0.00431348,-5.5223e-05,1.09111e-06,0.34071,0.00420631,-5.19496e-05,1.0399e-06,0.344866,0.00410553,-4.88299e-05,9.18347e-07,0.348923,0.00401062,-4.60749e-05,8.29942e-07,0.352889,0.00392096,-4.35851e-05,7.98478e-07,0.356767,0.00383619,-4.11896e-05,6.84917e-07,0.360562,0.00375586,-3.91349e-05,6.63976e-07,0.36428,0.00367959,-3.7143e-05,5.93086e-07,0.367923,0.00360708,-3.53637e-05,5.6976e-07,0.371495,0.00353806,-3.36544e-05,4.95533e-07,0.375,0.00347224,-3.21678e-05,4.87951e-07,0.378441,0.00340937,-3.0704e-05,4.4349e-07,0.38182,0.00334929,-2.93735e-05,4.20297e-07,0.38514,0.0032918,-2.81126e-05,3.7872e-07,0.388404,0.00323671,-2.69764e-05,3.596e-07,0.391614,0.00318384,-2.58976e-05,3.5845e-07,0.394772,0.00313312,-2.48223e-05,2.92765e-07,0.397881,0.00308435,-2.3944e-05,3.18232e-07,0.400942,0.00303742,-2.29893e-05,2.82046e-07,0.403957,0.00299229,-2.21432e-05,2.52315e-07,0.406927,0.00294876,-2.13862e-05,2.58416e-07,0.409855,0.00290676,-2.0611e-05,2.33939e-07,0.412741,0.00286624,-1.99092e-05,2.36342e-07,0.415587,0.00282713,-1.92001e-05,1.916e-07,0.418396,0.00278931,-1.86253e-05,2.1915e-07,0.421167,0.00275271,-1.79679e-05,1.83498e-07,0.423901,0.00271733,-1.74174e-05,1.79343e-07,0.426602,0.00268303,-1.68794e-05,1.72013e-07,0.429268,0.00264979,-1.63633e-05,1.75686e-07,0.431901,0.00261759,-1.58363e-05,1.3852e-07,0.434503,0.00258633,-1.54207e-05,1.64304e-07,0.437074,0.00255598,-1.49278e-05,1.28136e-07,0.439616,0.00252651,-1.45434e-05,1.57618e-07,0.442128,0.0024979,-1.40705e-05,1.0566e-07,0.444612,0.00247007,-1.37535e-05,1.34998e-07,0.447068,0.00244297,-1.33485e-05,1.29207e-07,0.449498,0.00241666,-1.29609e-05,9.32347e-08,0.451902,0.00239102,-1.26812e-05,1.23703e-07,0.45428,0.00236603,-1.23101e-05,9.74072e-08,0.456634,0.0023417,-1.20179e-05,1.12518e-07,0.458964,0.002318,-1.16803e-05,7.83681e-08,0.46127,0.00229488,-1.14452e-05,1.10452e-07,0.463554,0.00227232,-1.11139e-05,7.58719e-08,0.465815,0.00225032,-1.08863e-05,9.2699e-08,0.468055,0.00222882,-1.06082e-05,8.97738e-08,0.470273,0.00220788,-1.03388e-05,5.4845e-08,0.47247,0.00218736,-1.01743e-05,1.0808e-07,0.474648,0.00216734,-9.85007e-06,4.9277e-08,0.476805,0.00214779,-9.70224e-06,8.22408e-08,0.478943,0.00212863,-9.45551e-06,6.87942e-08,0.481063,0.00210993,-9.24913e-06,5.98144e-08,0.483163,0.00209161,-9.06969e-06,7.93789e-08,0.485246,0.00207371,-8.83155e-06,3.99032e-08,0.487311,0.00205616,-8.71184e-06,8.88325e-08,0.489358,0.002039,-8.44534e-06,2.20004e-08,0.491389,0.00202218,-8.37934e-06,9.13872e-08,0.493403,0.0020057,-8.10518e-06,2.96829e-08,0.495401,0.00198957,-8.01613e-06,5.81028e-08,0.497382,0.00197372,-7.84183e-06,6.5731e-08,0.499348,0.00195823,-7.64463e-06,3.66019e-08,0.501299,0.00194305,-7.53483e-06,2.62811e-08,0.503234,0.00192806,-7.45598e-06,9.66907e-08,0.505155,0.00191344,-7.16591e-06,4.18928e-09,0.507061,0.00189912,-7.15334e-06,6.53665e-08,0.508953,0.00188501,-6.95724e-06,3.23686e-08,0.510831,0.00187119,-6.86014e-06,4.35774e-08,0.512696,0.0018576,-6.72941e-06,3.17406e-08,0.514547,0.00184424,-6.63418e-06,6.78785e-08,0.516384,0.00183117,-6.43055e-06,-5.23126e-09,0.518209,0.0018183,-6.44624e-06,7.22562e-08,0.520021,0.00180562,-6.22947e-06,1.42292e-08,0.52182,0.0017932,-6.18679e-06,4.9641e-08,0.523607,0.00178098,-6.03786e-06,2.56259e-08,0.525382,0.00176898,-5.96099e-06,2.66696e-08,0.527145,0.00175714,-5.88098e-06,4.65094e-08,0.528897,0.00174552,-5.74145e-06,2.57114e-08,0.530637,0.00173411,-5.66431e-06,2.94588e-08,0.532365,0.00172287,-5.57594e-06,3.52667e-08,0.534082,0.00171182,-5.47014e-06,8.28868e-09,0.535789,0.00170091,-5.44527e-06,5.07871e-08,0.537484,0.00169017,-5.29291e-06,2.69817e-08,0.539169,0.00167967,-5.21197e-06,2.01009e-08,0.540844,0.0016693,-5.15166e-06,1.18237e-08,0.542508,0.00165903,-5.11619e-06,5.18135e-08,0.544162,0.00164896,-4.96075e-06,1.9341e-08,0.545806,0.00163909,-4.90273e-06,-9.96867e-09,0.54744,0.00162926,-4.93263e-06,8.01382e-08,0.549064,0.00161963,-4.69222e-06,-1.25601e-08,0.550679,0.00161021,-4.7299e-06,2.97067e-08,0.552285,0.00160084,-4.64078e-06,1.29426e-08,0.553881,0.0015916,-4.60195e-06,3.77327e-08,0.555468,0.00158251,-4.48875e-06,1.49412e-08,0.557046,0.00157357,-4.44393e-06,2.17118e-08,0.558615,0.00156475,-4.3788e-06,1.74206e-08,0.560176,0.00155605,-4.32653e-06,2.78152e-08,0.561727,0.00154748,-4.24309e-06,-9.47239e-09,0.563271,0.00153896,-4.27151e-06,6.9679e-08,0.564805,0.00153063,-4.06247e-06,-3.08246e-08,0.566332,0.00152241,-4.15494e-06,5.36188e-08,0.56785,0.00151426,-3.99409e-06,-4.83594e-09,0.56936,0.00150626,-4.00859e-06,2.53293e-08,0.570863,0.00149832,-3.93261e-06,2.27286e-08,0.572357,0.00149052,-3.86442e-06,2.96541e-09,0.573844,0.0014828,-3.85552e-06,2.50147e-08,0.575323,0.00147516,-3.78048e-06,1.61842e-08,0.576794,0.00146765,-3.73193e-06,2.94582e-08,0.578258,0.00146028,-3.64355e-06,-1.48076e-08,0.579715,0.00145295,-3.68798e-06,2.97724e-08,0.581164,0.00144566,-3.59866e-06,1.49272e-08,0.582606,0.00143851,-3.55388e-06,2.97285e-08,0.584041,0.00143149,-3.46469e-06,-1.46323e-08,0.585469,0.00142451,-3.50859e-06,2.88004e-08,0.58689,0.00141758,-3.42219e-06,1.864e-08,0.588304,0.00141079,-3.36627e-06,1.58482e-08,0.589712,0.00140411,-3.31872e-06,-2.24279e-08,0.591112,0.00139741,-3.38601e-06,7.38639e-08,0.592507,0.00139085,-3.16441e-06,-3.46088e-08,0.593894,0.00138442,-3.26824e-06,4.96675e-09,0.595275,0.0013779,-3.25334e-06,7.4346e-08,0.59665,0.00137162,-3.0303e-06,-6.39319e-08,0.598019,0.00136536,-3.2221e-06,6.21725e-08,0.599381,0.00135911,-3.03558e-06,-5.94423e-09,0.600737,0.00135302,-3.05341e-06,2.12091e-08,0.602087,0.00134697,-2.98979e-06,-1.92876e-08,0.603431,0.00134094,-3.04765e-06,5.5941e-08,0.604769,0.00133501,-2.87983e-06,-2.56622e-08,0.606101,0.00132917,-2.95681e-06,4.67078e-08,0.607427,0.0013234,-2.81669e-06,-4.19592e-08,0.608748,0.00131764,-2.94257e-06,6.15243e-08,0.610062,0.00131194,-2.75799e-06,-2.53244e-08,0.611372,0.00130635,-2.83397e-06,3.97739e-08,0.612675,0.0013008,-2.71465e-06,-1.45618e-08,0.613973,0.00129533,-2.75833e-06,1.84733e-08,0.615266,0.00128986,-2.70291e-06,2.73606e-10,0.616553,0.00128446,-2.70209e-06,4.00367e-08,0.617835,0.00127918,-2.58198e-06,-4.12113e-08,0.619111,0.00127389,-2.70561e-06,6.52039e-08,0.620383,0.00126867,-2.51e-06,-4.07901e-08,0.621649,0.00126353,-2.63237e-06,3.83516e-08,0.62291,0.00125838,-2.51732e-06,6.59315e-09,0.624166,0.00125337,-2.49754e-06,-5.11939e-09,0.625416,0.00124836,-2.5129e-06,1.38846e-08,0.626662,0.00124337,-2.47124e-06,9.18514e-09,0.627903,0.00123846,-2.44369e-06,8.97952e-09,0.629139,0.0012336,-2.41675e-06,1.45012e-08,0.63037,0.00122881,-2.37325e-06,-7.37949e-09,0.631597,0.00122404,-2.39538e-06,1.50169e-08,0.632818,0.00121929,-2.35033e-06,6.91648e-09,0.634035,0.00121461,-2.32958e-06,1.69219e-08,0.635248,0.00121,-2.27882e-06,-1.49997e-08,0.636455,0.0012054,-2.32382e-06,4.30769e-08,0.637659,0.00120088,-2.19459e-06,-3.80986e-08,0.638857,0.00119638,-2.30888e-06,4.97134e-08,0.640051,0.00119191,-2.15974e-06,-4.15463e-08,0.641241,0.00118747,-2.28438e-06,5.68667e-08,0.642426,0.00118307,-2.11378e-06,-7.10641e-09,0.643607,0.00117882,-2.1351e-06,-2.8441e-08,0.644784,0.00117446,-2.22042e-06,6.12658e-08,0.645956,0.00117021,-2.03663e-06,-3.78083e-08,0.647124,0.00116602,-2.15005e-06,3.03627e-08,0.648288,0.00116181,-2.05896e-06,-2.40379e-08,0.649448,0.00115762,-2.13108e-06,6.57887e-08,0.650603,0.00115356,-1.93371e-06,-6.03028e-08,0.651755,0.00114951,-2.11462e-06,5.62134e-08,0.652902,0.00114545,-1.94598e-06,-4.53417e-08,0.654046,0.00114142,-2.082e-06,6.55489e-08,0.655185,0.00113745,-1.88536e-06,-3.80396e-08,0.656321,0.00113357,-1.99948e-06,2.70049e-08,0.657452,0.00112965,-1.91846e-06,-1.03755e-08,0.65858,0.00112578,-1.94959e-06,1.44973e-08,0.659704,0.00112192,-1.9061e-06,1.1991e-08,0.660824,0.00111815,-1.87012e-06,-2.85634e-09,0.66194,0.0011144,-1.87869e-06,-5.65782e-10,0.663053,0.00111064,-1.88039e-06,5.11947e-09,0.664162,0.0011069,-1.86503e-06,3.96924e-08,0.665267,0.00110328,-1.74595e-06,-4.46795e-08,0.666368,0.00109966,-1.87999e-06,1.98161e-08,0.667466,0.00109596,-1.82054e-06,2.502e-08,0.66856,0.00109239,-1.74548e-06,-6.86593e-10,0.669651,0.0010889,-1.74754e-06,-2.22739e-08,0.670738,0.00108534,-1.81437e-06,3.01776e-08,0.671821,0.0010818,-1.72383e-06,2.07732e-08,0.672902,0.00107841,-1.66151e-06,-5.36658e-08,0.673978,0.00107493,-1.82251e-06,7.46802e-08,0.675051,0.00107151,-1.59847e-06,-6.62411e-08,0.676121,0.00106811,-1.79719e-06,7.10748e-08,0.677188,0.00106473,-1.58397e-06,-3.92441e-08,0.678251,0.00106145,-1.7017e-06,2.62973e-08,0.679311,0.00105812,-1.62281e-06,-6.34035e-09,0.680367,0.00105486,-1.64183e-06,-9.36249e-10,0.68142,0.00105157,-1.64464e-06,1.00854e-08,0.68247,0.00104831,-1.61438e-06,2.01995e-08,0.683517,0.00104514,-1.55378e-06,-3.1279e-08,0.68456,0.00104194,-1.64762e-06,4.53114e-08,0.685601,0.00103878,-1.51169e-06,-3.07573e-08,0.686638,0.00103567,-1.60396e-06,1.81133e-08,0.687672,0.00103251,-1.54962e-06,1.79085e-08,0.688703,0.00102947,-1.49589e-06,-3.01428e-08,0.689731,0.00102639,-1.58632e-06,4.30583e-08,0.690756,0.00102334,-1.45715e-06,-2.28814e-08,0.691778,0.00102036,-1.52579e-06,-1.11373e-08,0.692797,0.00101727,-1.5592e-06,6.74305e-08,0.693812,0.00101436,-1.35691e-06,-7.97709e-08,0.694825,0.0010114,-1.59622e-06,7.28391e-08,0.695835,0.00100843,-1.37771e-06,-3.27715e-08,0.696842,0.00100558,-1.47602e-06,-1.35807e-09,0.697846,0.00100262,-1.48009e-06,3.82037e-08,0.698847,0.000999775,-1.36548e-06,-3.22474e-08,0.699846,0.000996948,-1.46223e-06,3.11809e-08,0.700841,0.000994117,-1.36868e-06,-3.28714e-08,0.701834,0.000991281,-1.4673e-06,4.07001e-08,0.702824,0.000988468,-1.3452e-06,-1.07197e-08,0.703811,0.000985746,-1.37736e-06,2.17866e-09,0.704795,0.000982998,-1.37082e-06,2.00521e-09,0.705777,0.000980262,-1.3648e-06,-1.01996e-08,0.706756,0.000977502,-1.3954e-06,3.87931e-08,0.707732,0.000974827,-1.27902e-06,-2.57632e-08,0.708706,0.000972192,-1.35631e-06,4.65513e-09,0.709676,0.000969493,-1.34235e-06,7.14257e-09,0.710645,0.00096683,-1.32092e-06,2.63791e-08,0.71161,0.000964267,-1.24178e-06,-5.30543e-08,0.712573,0.000961625,-1.40095e-06,6.66289e-08,0.713533,0.000959023,-1.20106e-06,-3.46474e-08,0.714491,0.000956517,-1.305e-06,1.23559e-08,0.715446,0.000953944,-1.26793e-06,-1.47763e-08,0.716399,0.000951364,-1.31226e-06,4.67494e-08,0.717349,0.000948879,-1.17201e-06,-5.3012e-08,0.718297,0.000946376,-1.33105e-06,4.60894e-08,0.719242,0.000943852,-1.19278e-06,-1.21366e-08,0.720185,0.00094143,-1.22919e-06,2.45673e-09,0.721125,0.000938979,-1.22182e-06,2.30966e-09,0.722063,0.000936543,-1.21489e-06,-1.16954e-08,0.722998,0.000934078,-1.24998e-06,4.44718e-08,0.723931,0.000931711,-1.11656e-06,-4.69823e-08,0.724861,0.000929337,-1.25751e-06,2.4248e-08,0.725789,0.000926895,-1.18477e-06,9.5949e-09,0.726715,0.000924554,-1.15598e-06,-3.02286e-09,0.727638,0.000922233,-1.16505e-06,2.49649e-09,0.72856,0.00091991,-1.15756e-06,-6.96321e-09,0.729478,0.000917575,-1.17845e-06,2.53564e-08,0.730395,0.000915294,-1.10238e-06,-3.48578e-08,0.731309,0.000912984,-1.20695e-06,5.44704e-08,0.732221,0.000910734,-1.04354e-06,-6.38144e-08,0.73313,0.000908455,-1.23499e-06,8.15781e-08,0.734038,0.00090623,-9.90253e-07,-8.3684e-08,0.734943,0.000903999,-1.2413e-06,7.43441e-08,0.735846,0.000901739,-1.01827e-06,-3.48787e-08,0.736746,0.000899598,-1.12291e-06,5.56596e-09,0.737645,0.000897369,-1.10621e-06,1.26148e-08,0.738541,0.000895194,-1.06837e-06,3.57935e-09,0.739435,0.000893068,-1.05763e-06,-2.69322e-08,0.740327,0.000890872,-1.13842e-06,4.45448e-08,0.741217,0.000888729,-1.00479e-06,-3.20376e-08,0.742105,0.000886623,-1.1009e-06,2.40011e-08,0.74299,0.000884493,-1.0289e-06,-4.36209e-09,0.743874,0.000882422,-1.04199e-06,-6.55268e-09,0.744755,0.000880319,-1.06164e-06,3.05728e-08,0.745634,0.000878287,-9.69926e-07,-5.61338e-08,0.746512,0.000876179,-1.13833e-06,7.4753e-08,0.747387,0.000874127,-9.14068e-07,-6.40644e-08,0.74826,0.000872106,-1.10626e-06,6.22955e-08,0.749131,0.000870081,-9.19375e-07,-6.59083e-08,0.75,0.000868044,-1.1171e-06,8.21284e-08,0.750867,0.000866056,-8.70714e-07,-8.37915e-08,0.751732,0.000864064,-1.12209e-06,7.42237e-08,0.752595,0.000862042,-8.99418e-07,-3.42894e-08,0.753456,0.00086014,-1.00229e-06,3.32955e-09,0.754315,0.000858146,-9.92297e-07,2.09712e-08,0.755173,0.000856224,-9.29384e-07,-2.76096e-08,0.756028,0.000854282,-1.01221e-06,2.98627e-08,0.756881,0.000852348,-9.22625e-07,-3.22365e-08,0.757733,0.000850406,-1.01933e-06,3.94786e-08,0.758582,0.000848485,-9.00898e-07,-6.46833e-09,0.75943,0.000846664,-9.20303e-07,-1.36052e-08,0.760275,0.000844783,-9.61119e-07,1.28447e-09,0.761119,0.000842864,-9.57266e-07,8.4674e-09,0.761961,0.000840975,-9.31864e-07,2.44506e-08,0.762801,0.000839185,-8.58512e-07,-4.6665e-08,0.763639,0.000837328,-9.98507e-07,4.30001e-08,0.764476,0.00083546,-8.69507e-07,-6.12609e-09,0.76531,0.000833703,-8.87885e-07,-1.84959e-08,0.766143,0.000831871,-9.43372e-07,2.05052e-08,0.766974,0.000830046,-8.81857e-07,-3.92026e-09,0.767803,0.000828271,-8.93618e-07,-4.82426e-09,0.768631,0.000826469,-9.0809e-07,2.32172e-08,0.769456,0.000824722,-8.38439e-07,-2.84401e-08,0.77028,0.00082296,-9.23759e-07,3.09386e-08,0.771102,0.000821205,-8.30943e-07,-3.57099e-08,0.771922,0.000819436,-9.38073e-07,5.22963e-08,0.772741,0.000817717,-7.81184e-07,-5.42658e-08,0.773558,0.000815992,-9.43981e-07,4.55579e-08,0.774373,0.000814241,-8.07308e-07,-8.75656e-09,0.775186,0.0008126,-8.33578e-07,-1.05315e-08,0.775998,0.000810901,-8.65172e-07,-8.72188e-09,0.776808,0.000809145,-8.91338e-07,4.54191e-08,0.777616,0.000807498,-7.5508e-07,-5.37454e-08,0.778423,0.000805827,-9.16317e-07,5.03532e-08,0.779228,0.000804145,-7.65257e-07,-2.84584e-08,0.780031,0.000802529,-8.50632e-07,3.87579e-09,0.780833,0.00080084,-8.39005e-07,1.29552e-08,0.781633,0.0007992,-8.00139e-07,3.90804e-09,0.782432,0.000797612,-7.88415e-07,-2.85874e-08,0.783228,0.000795949,-8.74177e-07,5.0837e-08,0.784023,0.000794353,-7.21666e-07,-5.55513e-08,0.784817,0.000792743,-8.8832e-07,5.21587e-08,0.785609,0.000791123,-7.31844e-07,-3.38744e-08,0.786399,0.000789558,-8.33467e-07,2.37342e-08,0.787188,0.000787962,-7.62264e-07,-1.45775e-09,0.787975,0.000786433,-7.66638e-07,-1.79034e-08,0.788761,0.000784846,-8.20348e-07,1.34665e-08,0.789545,0.000783246,-7.79948e-07,2.3642e-08,0.790327,0.000781757,-7.09022e-07,-4.84297e-08,0.791108,0.000780194,-8.54311e-07,5.08674e-08,0.791888,0.000778638,-7.01709e-07,-3.58303e-08,0.792666,0.000777127,-8.092e-07,3.28493e-08,0.793442,0.000775607,-7.10652e-07,-3.59624e-08,0.794217,0.000774078,-8.1854e-07,5.13959e-08,0.79499,0.000772595,-6.64352e-07,-5.04121e-08,0.795762,0.000771115,-8.15588e-07,3.10431e-08,0.796532,0.000769577,-7.22459e-07,-1.41557e-08,0.797301,0.00076809,-7.64926e-07,2.55795e-08,0.798069,0.000766636,-6.88187e-07,-2.85578e-08,0.798835,0.000765174,-7.73861e-07,2.90472e-08,0.799599,0.000763714,-6.86719e-07,-2.80262e-08,0.800362,0.000762256,-7.70798e-07,2.34531e-08,0.801123,0.000760785,-7.00438e-07,-6.18144e-09,0.801884,0.000759366,-7.18983e-07,1.27263e-09,0.802642,0.000757931,-7.15165e-07,1.09101e-09,0.803399,0.000756504,-7.11892e-07,-5.63675e-09,0.804155,0.000755064,-7.28802e-07,2.14559e-08,0.80491,0.00075367,-6.64434e-07,-2.05821e-08,0.805663,0.00075228,-7.26181e-07,1.26812e-09,0.806414,0.000750831,-7.22377e-07,1.55097e-08,0.807164,0.000749433,-6.75848e-07,-3.70216e-09,0.807913,0.00074807,-6.86954e-07,-7.0105e-10,0.80866,0.000746694,-6.89057e-07,6.5063e-09,0.809406,0.000745336,-6.69538e-07,-2.53242e-08,0.810151,0.000743921,-7.45511e-07,3.51858e-08,0.810894,0.000742535,-6.39953e-07,3.79034e-09,0.811636,0.000741267,-6.28582e-07,-5.03471e-08,0.812377,0.000739858,-7.79624e-07,7.83886e-08,0.813116,0.000738534,-5.44458e-07,-8.43935e-08,0.813854,0.000737192,-7.97638e-07,8.03714e-08,0.81459,0.000735838,-5.56524e-07,-5.82784e-08,0.815325,0.00073455,-7.31359e-07,3.35329e-08,0.816059,0.000733188,-6.3076e-07,-1.62486e-08,0.816792,0.000731878,-6.79506e-07,3.14614e-08,0.817523,0.000730613,-5.85122e-07,-4.99925e-08,0.818253,0.000729293,-7.35099e-07,4.92994e-08,0.818982,0.000727971,-5.87201e-07,-2.79959e-08,0.819709,0.000726712,-6.71189e-07,3.07959e-09,0.820435,0.000725379,-6.6195e-07,1.56777e-08,0.82116,0.000724102,-6.14917e-07,-6.18564e-09,0.821883,0.000722854,-6.33474e-07,9.06488e-09,0.822606,0.000721614,-6.06279e-07,-3.00739e-08,0.823327,0.000720311,-6.96501e-07,5.16262e-08,0.824046,0.000719073,-5.41623e-07,-5.72214e-08,0.824765,0.000717818,-7.13287e-07,5.80503e-08,0.825482,0.000716566,-5.39136e-07,-5.57703e-08,0.826198,0.00071532,-7.06447e-07,4.58215e-08,0.826912,0.000714045,-5.68983e-07,-8.30636e-09,0.827626,0.000712882,-5.93902e-07,-1.25961e-08,0.828338,0.000711656,-6.3169e-07,-9.13985e-10,0.829049,0.00071039,-6.34432e-07,1.62519e-08,0.829759,0.00070917,-5.85676e-07,-4.48904e-09,0.830468,0.000707985,-5.99143e-07,1.70418e-09,0.831175,0.000706792,-5.9403e-07,-2.32768e-09,0.831881,0.000705597,-6.01014e-07,7.60648e-09,0.832586,0.000704418,-5.78194e-07,-2.80982e-08,0.83329,0.000703177,-6.62489e-07,4.51817e-08,0.833993,0.000701988,-5.26944e-07,-3.34192e-08,0.834694,0.000700834,-6.27201e-07,2.88904e-08,0.835394,0.000699666,-5.4053e-07,-2.25378e-08,0.836093,0.000698517,-6.08143e-07,1.65589e-09,0.836791,0.000697306,-6.03176e-07,1.59142e-08,0.837488,0.000696147,-5.55433e-07,-5.70801e-09,0.838184,0.000695019,-5.72557e-07,6.91792e-09,0.838878,0.000693895,-5.51803e-07,-2.19637e-08,0.839571,0.000692725,-6.17694e-07,2.13321e-08,0.840263,0.000691554,-5.53698e-07,-3.75996e-09,0.840954,0.000690435,-5.64978e-07,-6.29219e-09,0.841644,0.000689287,-5.83855e-07,2.89287e-08,0.842333,0.000688206,-4.97068e-07,-4.98181e-08,0.843021,0.000687062,-6.46523e-07,5.11344e-08,0.843707,0.000685922,-4.9312e-07,-3.55102e-08,0.844393,0.00068483,-5.9965e-07,3.13019e-08,0.845077,0.000683724,-5.05745e-07,-3.00925e-08,0.84576,0.000682622,-5.96022e-07,2.94636e-08,0.846442,0.000681519,-5.07631e-07,-2.81572e-08,0.847123,0.000680419,-5.92103e-07,2.35606e-08,0.847803,0.000679306,-5.21421e-07,-6.48045e-09,0.848482,0.000678243,-5.40863e-07,2.36124e-09,0.849159,0.000677169,-5.33779e-07,-2.96461e-09,0.849836,0.000676092,-5.42673e-07,9.49728e-09,0.850512,0.000675035,-5.14181e-07,-3.50245e-08,0.851186,0.000673902,-6.19254e-07,7.09959e-08,0.851859,0.000672876,-4.06267e-07,-7.01453e-08,0.852532,0.000671853,-6.16703e-07,3.07714e-08,0.853203,0.000670712,-5.24388e-07,6.66423e-09,0.853873,0.000669684,-5.04396e-07,2.17629e-09,0.854542,0.000668681,-4.97867e-07,-1.53693e-08,0.855211,0.000667639,-5.43975e-07,-3.03752e-10,0.855878,0.000666551,-5.44886e-07,1.65844e-08,0.856544,0.000665511,-4.95133e-07,-6.42907e-09,0.857209,0.000664501,-5.1442e-07,9.13195e-09,0.857873,0.0006635,-4.87024e-07,-3.00987e-08,0.858536,0.000662435,-5.7732e-07,5.16584e-08,0.859198,0.000661436,-4.22345e-07,-5.73255e-08,0.859859,0.000660419,-5.94322e-07,5.84343e-08,0.860518,0.000659406,-4.19019e-07,-5.72022e-08,0.861177,0.000658396,-5.90626e-07,5.11653e-08,0.861835,0.000657368,-4.3713e-07,-2.82495e-08,0.862492,0.000656409,-5.21878e-07,2.22788e-09,0.863148,0.000655372,-5.15195e-07,1.9338e-08,0.863803,0.0006544,-4.5718e-07,-1.99754e-08,0.864457,0.000653425,-5.17107e-07,9.59024e-10,0.86511,0.000652394,-5.1423e-07,1.61393e-08,0.865762,0.000651414,-4.65812e-07,-5.91149e-09,0.866413,0.000650465,-4.83546e-07,7.50665e-09,0.867063,0.00064952,-4.61026e-07,-2.4115e-08,0.867712,0.000648526,-5.33371e-07,2.93486e-08,0.86836,0.000647547,-4.45325e-07,-3.36748e-08,0.869007,0.000646555,-5.4635e-07,4.57461e-08,0.869653,0.0006456,-4.09112e-07,-3.01002e-08,0.870298,0.000644691,-4.99412e-07,1.50501e-08,0.870942,0.000643738,-4.54262e-07,-3.01002e-08,0.871585,0.000642739,-5.44563e-07,4.57461e-08,0.872228,0.000641787,-4.07324e-07,-3.36748e-08,0.872869,0.000640871,-5.08349e-07,2.93486e-08,0.873509,0.000639943,-4.20303e-07,-2.4115e-08,0.874149,0.00063903,-4.92648e-07,7.50655e-09,0.874787,0.000638067,-4.70128e-07,-5.91126e-09,0.875425,0.000637109,-4.87862e-07,1.61385e-08,0.876062,0.000636182,-4.39447e-07,9.61961e-10,0.876697,0.000635306,-4.36561e-07,-1.99863e-08,0.877332,0.000634373,-4.9652e-07,1.93785e-08,0.877966,0.000633438,-4.38384e-07,2.07697e-09,0.878599,0.000632567,-4.32153e-07,-2.76864e-08,0.879231,0.00063162,-5.15212e-07,4.90641e-08,0.879862,0.000630737,-3.6802e-07,-4.93606e-08,0.880493,0.000629852,-5.16102e-07,2.9169e-08,0.881122,0.000628908,-4.28595e-07,-7.71083e-09,0.881751,0.000628027,-4.51727e-07,1.6744e-09,0.882378,0.000627129,-4.46704e-07,1.01317e-09,0.883005,0.000626239,-4.43665e-07,-5.72703e-09,0.883631,0.000625334,-4.60846e-07,2.1895e-08,0.884255,0.000624478,-3.95161e-07,-2.22481e-08,0.88488,0.000623621,-4.61905e-07,7.4928e-09,0.885503,0.00062272,-4.39427e-07,-7.72306e-09,0.886125,0.000621818,-4.62596e-07,2.33995e-08,0.886746,0.000620963,-3.92398e-07,-2.62704e-08,0.887367,0.000620099,-4.71209e-07,2.20775e-08,0.887987,0.000619223,-4.04976e-07,-2.43496e-09,0.888605,0.000618406,-4.12281e-07,-1.23377e-08,0.889223,0.000617544,-4.49294e-07,-7.81876e-09,0.88984,0.000616622,-4.72751e-07,4.36128e-08,0.890457,0.000615807,-3.41912e-07,-4.7423e-08,0.891072,0.000614981,-4.84181e-07,2.68698e-08,0.891687,0.000614093,-4.03572e-07,-4.51384e-10,0.8923,0.000613285,-4.04926e-07,-2.50643e-08,0.892913,0.0006124,-4.80119e-07,4.11038e-08,0.893525,0.000611563,-3.56808e-07,-2.01414e-08,0.894136,0.000610789,-4.17232e-07,-2.01426e-08,0.894747,0.000609894,-4.7766e-07,4.11073e-08,0.895356,0.000609062,-3.54338e-07,-2.50773e-08,0.895965,0.000608278,-4.2957e-07,-4.02954e-10,0.896573,0.000607418,-4.30779e-07,2.66891e-08,0.89718,0.000606636,-3.50711e-07,-4.67489e-08,0.897786,0.000605795,-4.90958e-07,4.10972e-08,0.898391,0.000604936,-3.67666e-07,1.56948e-09,0.898996,0.000604205,-3.62958e-07,-4.73751e-08,0.8996,0.000603337,-5.05083e-07,6.87214e-08,0.900202,0.000602533,-2.98919e-07,-4.86966e-08,0.900805,0.000601789,-4.45009e-07,6.85589e-09,0.901406,0.00060092,-4.24441e-07,2.1273e-08,0.902007,0.000600135,-3.60622e-07,-3.23434e-08,0.902606,0.000599317,-4.57652e-07,4.84959e-08,0.903205,0.000598547,-3.12164e-07,-4.24309e-08,0.903803,0.000597795,-4.39457e-07,2.01844e-09,0.904401,0.000596922,-4.33402e-07,3.43571e-08,0.904997,0.000596159,-3.30331e-07,-2.02374e-08,0.905593,0.000595437,-3.91043e-07,-1.30123e-08,0.906188,0.000594616,-4.3008e-07,1.26819e-08,0.906782,0.000593794,-3.92034e-07,2.18894e-08,0.907376,0.000593076,-3.26366e-07,-4.06349e-08,0.907968,0.000592301,-4.4827e-07,2.1441e-08,0.90856,0.000591469,-3.83947e-07,1.44754e-08,0.909151,0.000590744,-3.40521e-07,-1.97379e-08,0.909742,0.000590004,-3.99735e-07,4.87161e-09,0.910331,0.000589219,-3.8512e-07,2.51532e-10,0.91092,0.00058845,-3.84366e-07,-5.87776e-09,0.911508,0.000587663,-4.01999e-07,2.32595e-08,0.912096,0.000586929,-3.3222e-07,-2.75554e-08,0.912682,0.000586182,-4.14887e-07,2.73573e-08,0.913268,0.000585434,-3.32815e-07,-2.22692e-08,0.913853,0.000584702,-3.99622e-07,2.11486e-09,0.914437,0.000583909,-3.93278e-07,1.38098e-08,0.915021,0.000583164,-3.51848e-07,2.25042e-09,0.915604,0.000582467,-3.45097e-07,-2.28115e-08,0.916186,0.000581708,-4.13531e-07,2.93911e-08,0.916767,0.000580969,-3.25358e-07,-3.51481e-08,0.917348,0.000580213,-4.30803e-07,5.15967e-08,0.917928,0.000579506,-2.76012e-07,-5.20296e-08,0.918507,0.000578798,-4.32101e-07,3.73124e-08,0.919085,0.000578046,-3.20164e-07,-3.76154e-08,0.919663,0.000577293,-4.3301e-07,5.35447e-08,0.92024,0.000576587,-2.72376e-07,-5.7354e-08,0.920816,0.000575871,-4.44438e-07,5.66621e-08,0.921391,0.000575152,-2.74452e-07,-5.00851e-08,0.921966,0.000574453,-4.24707e-07,2.4469e-08,0.92254,0.000573677,-3.513e-07,1.18138e-08,0.923114,0.000573009,-3.15859e-07,-1.21195e-08,0.923686,0.000572341,-3.52217e-07,-2.29403e-08,0.924258,0.000571568,-4.21038e-07,4.4276e-08,0.924829,0.000570859,-2.8821e-07,-3.49546e-08,0.9254,0.000570178,-3.93074e-07,3.59377e-08,0.92597,0.000569499,-2.85261e-07,-4.91915e-08,0.926539,0.000568781,-4.32835e-07,4.16189e-08,0.927107,0.00056804,-3.07979e-07,1.92523e-09,0.927675,0.00056743,-3.02203e-07,-4.93198e-08,0.928242,0.000566678,-4.50162e-07,7.61447e-08,0.928809,0.000566006,-2.21728e-07,-7.6445e-08,0.929374,0.000565333,-4.51063e-07,5.08216e-08,0.929939,0.000564583,-2.98599e-07,-7.63212e-09,0.930503,0.000563963,-3.21495e-07,-2.02931e-08,0.931067,0.000563259,-3.82374e-07,2.92001e-08,0.93163,0.000562582,-2.94774e-07,-3.69025e-08,0.932192,0.000561882,-4.05482e-07,5.88053e-08,0.932754,0.000561247,-2.29066e-07,-7.91094e-08,0.933315,0.000560552,-4.66394e-07,7.88184e-08,0.933875,0.000559856,-2.29939e-07,-5.73501e-08,0.934434,0.000559224,-4.01989e-07,3.13727e-08,0.934993,0.000558514,-3.07871e-07,-8.53611e-09,0.935551,0.000557873,-3.33479e-07,2.77175e-09,0.936109,0.000557214,-3.25164e-07,-2.55091e-09,0.936666,0.000556556,-3.32817e-07,7.43188e-09,0.937222,0.000555913,-3.10521e-07,-2.71766e-08,0.937778,0.00055521,-3.92051e-07,4.167e-08,0.938333,0.000554551,-2.67041e-07,-2.02941e-08,0.938887,0.000553956,-3.27923e-07,-2.00984e-08,0.93944,0.00055324,-3.88218e-07,4.10828e-08,0.939993,0.000552587,-2.6497e-07,-2.50237e-08,0.940546,0.000551982,-3.40041e-07,-5.92583e-10,0.941097,0.0005513,-3.41819e-07,2.7394e-08,0.941648,0.000550698,-2.59637e-07,-4.93788e-08,0.942199,0.000550031,-4.07773e-07,5.09119e-08,0.942748,0.000549368,-2.55038e-07,-3.50595e-08,0.943297,0.000548753,-3.60216e-07,2.97214e-08,0.943846,0.000548122,-2.71052e-07,-2.42215e-08,0.944394,0.000547507,-3.43716e-07,7.55985e-09,0.944941,0.000546842,-3.21037e-07,-6.01796e-09,0.945487,0.000546182,-3.3909e-07,1.65119e-08,0.946033,0.000545553,-2.89555e-07,-4.2498e-10,0.946578,0.000544973,-2.9083e-07,-1.4812e-08,0.947123,0.000544347,-3.35266e-07,6.83068e-11,0.947667,0.000543676,-3.35061e-07,1.45388e-08,0.94821,0.00054305,-2.91444e-07,1.38123e-09,0.948753,0.000542471,-2.87301e-07,-2.00637e-08,0.949295,0.000541836,-3.47492e-07,1.92688e-08,0.949837,0.000541199,-2.89685e-07,2.59298e-09,0.950378,0.000540628,-2.81906e-07,-2.96407e-08,0.950918,0.000539975,-3.70829e-07,5.63652e-08,0.951458,0.000539402,-2.01733e-07,-7.66107e-08,0.951997,0.000538769,-4.31565e-07,7.12638e-08,0.952535,0.00053812,-2.17774e-07,-2.96305e-08,0.953073,0.000537595,-3.06665e-07,-1.23464e-08,0.95361,0.000536945,-3.43704e-07,1.94114e-08,0.954147,0.000536316,-2.8547e-07,-5.69451e-09,0.954683,0.000535728,-3.02554e-07,3.36666e-09,0.955219,0.000535133,-2.92454e-07,-7.77208e-09,0.955753,0.000534525,-3.1577e-07,2.77216e-08,0.956288,0.000533976,-2.32605e-07,-4.35097e-08,0.956821,0.00053338,-3.63134e-07,2.7108e-08,0.957354,0.000532735,-2.8181e-07,-5.31772e-09,0.957887,0.000532156,-2.97764e-07,-5.83718e-09,0.958419,0.000531543,-3.15275e-07,2.86664e-08,0.95895,0.000530998,-2.29276e-07,-4.9224e-08,0.959481,0.000530392,-3.76948e-07,4.90201e-08,0.960011,0.000529785,-2.29887e-07,-2.76471e-08,0.96054,0.000529243,-3.12829e-07,1.96385e-09,0.961069,0.000528623,-3.06937e-07,1.97917e-08,0.961598,0.000528068,-2.47562e-07,-2.15261e-08,0.962125,0.000527508,-3.1214e-07,6.70795e-09,0.962653,0.000526904,-2.92016e-07,-5.30573e-09,0.963179,0.000526304,-3.07934e-07,1.4515e-08,0.963705,0.000525732,-2.64389e-07,6.85048e-09,0.964231,0.000525224,-2.43837e-07,-4.19169e-08,0.964756,0.00052461,-3.69588e-07,4.1608e-08,0.96528,0.000523996,-2.44764e-07,-5.30598e-09,0.965804,0.000523491,-2.60682e-07,-2.03841e-08,0.966327,0.000522908,-3.21834e-07,2.72378e-08,0.966849,0.000522346,-2.40121e-07,-2.89625e-08,0.967371,0.000521779,-3.27008e-07,2.90075e-08,0.967893,0.000521212,-2.39986e-07,-2.74629e-08,0.968414,0.00052065,-3.22374e-07,2.12396e-08,0.968934,0.000520069,-2.58656e-07,2.10922e-09,0.969454,0.000519558,-2.52328e-07,-2.96765e-08,0.969973,0.000518964,-3.41357e-07,5.6992e-08,0.970492,0.000518452,-1.70382e-07,-7.90821e-08,0.97101,0.000517874,-4.07628e-07,8.05224e-08,0.971528,0.000517301,-1.66061e-07,-6.41937e-08,0.972045,0.000516776,-3.58642e-07,5.70429e-08,0.972561,0.00051623,-1.87513e-07,-4.47686e-08,0.973077,0.00051572,-3.21819e-07,2.82237e-09,0.973593,0.000515085,-3.13352e-07,3.34792e-08,0.974108,0.000514559,-2.12914e-07,-1.75298e-08,0.974622,0.000514081,-2.65503e-07,-2.29648e-08,0.975136,0.000513481,-3.34398e-07,4.97843e-08,0.975649,0.000512961,-1.85045e-07,-5.6963e-08,0.976162,0.00051242,-3.55934e-07,5.88585e-08,0.976674,0.000511885,-1.79359e-07,-5.92616e-08,0.977185,0.000511348,-3.57143e-07,5.89785e-08,0.977696,0.000510811,-1.80208e-07,-5.74433e-08,0.978207,0.000510278,-3.52538e-07,5.15854e-08,0.978717,0.000509728,-1.97781e-07,-2.9689e-08,0.979226,0.000509243,-2.86848e-07,7.56591e-09,0.979735,0.000508692,-2.64151e-07,-5.74649e-10,0.980244,0.000508162,-2.65875e-07,-5.26732e-09,0.980752,0.000507615,-2.81677e-07,2.16439e-08,0.981259,0.000507116,-2.16745e-07,-2.17037e-08,0.981766,0.000506618,-2.81856e-07,5.56636e-09,0.982272,0.000506071,-2.65157e-07,-5.61689e-10,0.982778,0.000505539,-2.66842e-07,-3.31963e-09,0.983283,0.000504995,-2.76801e-07,1.38402e-08,0.983788,0.000504483,-2.3528e-07,7.56339e-09,0.984292,0.000504035,-2.1259e-07,-4.40938e-08,0.984796,0.000503478,-3.44871e-07,4.96026e-08,0.985299,0.000502937,-1.96064e-07,-3.51071e-08,0.985802,0.000502439,-3.01385e-07,3.12212e-08,0.986304,0.00050193,-2.07721e-07,-3.0173e-08,0.986806,0.000501424,-2.9824e-07,2.9866e-08,0.987307,0.000500917,-2.08642e-07,-2.96865e-08,0.987808,0.000500411,-2.97702e-07,2.92753e-08,0.988308,0.000499903,-2.09876e-07,-2.78101e-08,0.988807,0.0004994,-2.93306e-07,2.23604e-08,0.989307,0.000498881,-2.26225e-07,-2.02681e-09,0.989805,0.000498422,-2.32305e-07,-1.42531e-08,0.990303,0.000497915,-2.75065e-07,-5.65232e-10,0.990801,0.000497363,-2.76761e-07,1.65141e-08,0.991298,0.000496859,-2.27218e-07,-5.88639e-09,0.991795,0.000496387,-2.44878e-07,7.0315e-09,0.992291,0.000495918,-2.23783e-07,-2.22396e-08,0.992787,0.000495404,-2.90502e-07,2.23224e-08,0.993282,0.00049489,-2.23535e-07,-7.44543e-09,0.993776,0.000494421,-2.45871e-07,7.45924e-09,0.994271,0.000493951,-2.23493e-07,-2.23915e-08,0.994764,0.000493437,-2.90668e-07,2.25021e-08,0.995257,0.000492923,-2.23161e-07,-8.01218e-09,0.99575,0.000492453,-2.47198e-07,9.54669e-09,0.996242,0.000491987,-2.18558e-07,-3.01746e-08,0.996734,0.000491459,-3.09082e-07,5.1547e-08,0.997225,0.000490996,-1.54441e-07,-5.68039e-08,0.997716,0.000490517,-3.24853e-07,5.64594e-08,0.998206,0.000490036,-1.55474e-07,-4.98245e-08,0.998696,0.000489576,-3.04948e-07,2.36292e-08,0.999186,0.000489037,-2.3406e-07,1.49121e-08,0.999674,0.000488613,-1.89324e-07,-2.3673e-08,1.00016,0.000488164,-2.60343e-07,2.01754e-08,1.00065,0.000487704,-1.99816e-07,-5.70288e-08,1.00114,0.000487133,-3.70903e-07,8.87303e-08,1.00162,0.000486657,-1.04712e-07,-5.94737e-08,1.00211,0.000486269,-2.83133e-07,2.99553e-08,1.0026,0.000485793,-1.93267e-07,-6.03474e-08,1.00308,0.000485225,-3.74309e-07,9.2225e-08,1.00357,0.000484754,-9.76345e-08,-7.0134e-08,1.00405,0.000484348,-3.08036e-07,6.91016e-08,1.00454,0.000483939,-1.00731e-07,-8.70633e-08,1.00502,0.000483476,-3.61921e-07,4.07328e-08,1.0055,0.000482875,-2.39723e-07,4.33413e-08,1.00599,0.000482525,-1.09699e-07,-9.48886e-08,1.00647,0.000482021,-3.94365e-07,9.77947e-08,1.00695,0.000481526,-1.00981e-07,-5.78713e-08,1.00743,0.00048115,-2.74595e-07,1.44814e-08,1.00791,0.000480645,-2.31151e-07,-5.42665e-11,1.00839,0.000480182,-2.31314e-07,-1.42643e-08,1.00887,0.000479677,-2.74106e-07,5.71115e-08,1.00935,0.0004793,-1.02772e-07,-9.49724e-08,1.00983,0.000478809,-3.87689e-07,8.43596e-08,1.01031,0.000478287,-1.3461e-07,-4.04755e-09,1.01079,0.000478006,-1.46753e-07,-6.81694e-08,1.01127,0.000477508,-3.51261e-07,3.83067e-08,1.01174,0.00047692,-2.36341e-07,3.41521e-08,1.01222,0.00047655,-1.33885e-07,-5.57058e-08,1.0127,0.000476115,-3.01002e-07,6.94616e-08,1.01317,0.000475721,-9.26174e-08,-1.02931e-07,1.01365,0.000475227,-4.01412e-07,1.03846e-07,1.01412,0.000474736,-8.98751e-08,-7.40321e-08,1.0146,0.000474334,-3.11971e-07,7.30735e-08,1.01507,0.00047393,-9.27508e-08,-9.90527e-08,1.01554,0.000473447,-3.89909e-07,8.47188e-08,1.01602,0.000472921,-1.35753e-07,-1.40381e-09,1.01649,0.000472645,-1.39964e-07,-7.91035e-08,1.01696,0.000472128,-3.77275e-07,7.93993e-08,1.01744,0.000471612,-1.39077e-07,-7.52607e-11,1.01791,0.000471334,-1.39302e-07,-7.90983e-08,1.01838,0.000470818,-3.76597e-07,7.80499e-08,1.01885,0.000470299,-1.42448e-07,5.31733e-09,1.01932,0.00047003,-1.26496e-07,-9.93193e-08,1.01979,0.000469479,-4.24453e-07,1.53541e-07,1.02026,0.00046909,3.617e-08,-1.57217e-07,1.02073,0.000468691,-4.35482e-07,1.177e-07,1.02119,0.000468173,-8.23808e-08,-7.51659e-08,1.02166,0.000467783,-3.07878e-07,6.37538e-08,1.02213,0.000467358,-1.16617e-07,-6.064e-08,1.0226,0.000466943,-2.98537e-07,5.9597e-08,1.02306,0.000466525,-1.19746e-07,-5.85386e-08,1.02353,0.00046611,-2.95362e-07,5.53482e-08,1.024,0.000465685,-1.29317e-07,-4.36449e-08,1.02446,0.000465296,-2.60252e-07,2.20268e-11,1.02493,0.000464775,-2.60186e-07,4.35568e-08,1.02539,0.000464386,-1.29516e-07,-5.50398e-08,1.02586,0.000463961,-2.94635e-07,5.73932e-08,1.02632,0.000463544,-1.22456e-07,-5.53236e-08,1.02678,0.000463133,-2.88426e-07,4.46921e-08,1.02725,0.000462691,-1.5435e-07,-4.23534e-09,1.02771,0.000462369,-1.67056e-07,-2.77507e-08,1.02817,0.000461952,-2.50308e-07,-3.97101e-09,1.02863,0.000461439,-2.62221e-07,4.36348e-08,1.02909,0.000461046,-1.31317e-07,-5.13589e-08,1.02955,0.000460629,-2.85394e-07,4.25913e-08,1.03001,0.000460186,-1.5762e-07,2.0285e-10,1.03047,0.000459871,-1.57011e-07,-4.34027e-08,1.03093,0.000459427,-2.87219e-07,5.41987e-08,1.03139,0.000459015,-1.24623e-07,-5.4183e-08,1.03185,0.000458604,-2.87172e-07,4.33239e-08,1.03231,0.000458159,-1.572e-07,9.65817e-11,1.03277,0.000457845,-1.56911e-07,-4.37103e-08,1.03323,0.0004574,-2.88041e-07,5.55351e-08,1.03368,0.000456991,-1.21436e-07,-5.9221e-08,1.03414,0.00045657,-2.99099e-07,6.21394e-08,1.0346,0.000456158,-1.1268e-07,-7.01275e-08,1.03505,0.000455723,-3.23063e-07,9.91614e-08,1.03551,0.000455374,-2.55788e-08,-8.80996e-08,1.03596,0.000455058,-2.89878e-07,1.48184e-08,1.03642,0.000454523,-2.45422e-07,2.88258e-08,1.03687,0.000454119,-1.58945e-07,-1.09125e-08,1.03733,0.000453768,-1.91682e-07,1.48241e-08,1.03778,0.000453429,-1.4721e-07,-4.83838e-08,1.03823,0.00045299,-2.92361e-07,5.95019e-08,1.03869,0.000452584,-1.13856e-07,-7.04146e-08,1.03914,0.000452145,-3.25099e-07,1.02947e-07,1.03959,0.000451803,-1.62583e-08,-1.02955e-07,1.04004,0.000451462,-3.25123e-07,7.04544e-08,1.04049,0.000451023,-1.1376e-07,-5.96534e-08,1.04094,0.000450616,-2.9272e-07,4.89499e-08,1.04139,0.000450178,-1.45871e-07,-1.69369e-08,1.04184,0.000449835,-1.96681e-07,1.87977e-08,1.04229,0.000449498,-1.40288e-07,-5.82539e-08,1.04274,0.000449043,-3.1505e-07,9.50087e-08,1.04319,0.000448698,-3.00238e-08,-8.33623e-08,1.04364,0.000448388,-2.80111e-07,2.20363e-11,1.04409,0.000447828,-2.80045e-07,8.32742e-08,1.04454,0.000447517,-3.02221e-08,-9.47002e-08,1.04498,0.000447173,-3.14323e-07,5.7108e-08,1.04543,0.000446716,-1.42999e-07,-1.45225e-08,1.04588,0.000446386,-1.86566e-07,9.82022e-10,1.04632,0.000446016,-1.8362e-07,1.05944e-08,1.04677,0.00044568,-1.51837e-07,-4.33597e-08,1.04721,0.000445247,-2.81916e-07,4.36352e-08,1.04766,0.000444814,-1.51011e-07,-1.19717e-08,1.0481,0.000444476,-1.86926e-07,4.25158e-09,1.04855,0.000444115,-1.74171e-07,-5.03461e-09,1.04899,0.000443751,-1.89275e-07,1.58868e-08,1.04944,0.00044342,-1.41614e-07,-5.85127e-08,1.04988,0.000442961,-3.17152e-07,9.89548e-08,1.05032,0.000442624,-2.0288e-08,-9.88878e-08,1.05076,0.000442287,-3.16951e-07,5.81779e-08,1.05121,0.000441827,-1.42418e-07,-1.46144e-08,1.05165,0.000441499,-1.86261e-07,2.79892e-10,1.05209,0.000441127,-1.85421e-07,1.34949e-08,1.05253,0.000440797,-1.44937e-07,-5.42594e-08,1.05297,0.000440344,-3.07715e-07,8.43335e-08,1.05341,0.000439982,-5.47146e-08,-4.46558e-08,1.05385,0.000439738,-1.88682e-07,-2.49193e-08,1.05429,0.000439286,-2.6344e-07,2.5124e-08,1.05473,0.000438835,-1.88068e-07,4.36328e-08,1.05517,0.000438589,-5.71699e-08,-8.04459e-08,1.05561,0.000438234,-2.98508e-07,3.97324e-08,1.05605,0.000437756,-1.79311e-07,4.07258e-08,1.05648,0.000437519,-5.71332e-08,-8.34263e-08,1.05692,0.000437155,-3.07412e-07,5.45608e-08,1.05736,0.000436704,-1.4373e-07,-1.56078e-08,1.05779,0.000436369,-1.90553e-07,7.87043e-09,1.05823,0.000436012,-1.66942e-07,-1.58739e-08,1.05867,0.00043563,-2.14563e-07,5.56251e-08,1.0591,0.000435368,-4.76881e-08,-8.74172e-08,1.05954,0.000435011,-3.0994e-07,5.56251e-08,1.05997,0.000434558,-1.43064e-07,-1.58739e-08,1.06041,0.000434224,-1.90686e-07,7.87042e-09,1.06084,0.000433866,-1.67075e-07,-1.56078e-08,1.06127,0.000433485,-2.13898e-07,5.45609e-08,1.06171,0.000433221,-5.02157e-08,-8.34263e-08,1.06214,0.00043287,-3.00495e-07,4.07258e-08,1.06257,0.000432391,-1.78317e-07,3.97325e-08,1.063,0.000432154,-5.91198e-08,-8.04464e-08,1.06344,0.000431794,-3.00459e-07,4.36347e-08,1.06387,0.000431324,-1.69555e-07,2.5117e-08,1.0643,0.000431061,-9.42041e-08,-2.48934e-08,1.06473,0.000430798,-1.68884e-07,-4.47527e-08,1.06516,0.000430326,-3.03142e-07,8.46951e-08,1.06559,0.000429973,-4.90573e-08,-5.56089e-08,1.06602,0.000429708,-2.15884e-07,1.85314e-08,1.06645,0.000429332,-1.6029e-07,-1.85166e-08,1.06688,0.000428956,-2.1584e-07,5.5535e-08,1.06731,0.000428691,-4.92347e-08,-8.44142e-08,1.06774,0.000428339,-3.02477e-07,4.37032e-08,1.06816,0.000427865,-1.71368e-07,2.88107e-08,1.06859,0.000427609,-8.49356e-08,-3.97367e-08,1.06902,0.00042732,-2.04146e-07,1.09267e-08,1.06945,0.000426945,-1.71365e-07,-3.97023e-09,1.06987,0.00042659,-1.83276e-07,4.9542e-09,1.0703,0.000426238,-1.68414e-07,-1.58466e-08,1.07073,0.000425854,-2.15953e-07,5.84321e-08,1.07115,0.000425597,-4.0657e-08,-9.86725e-08,1.07158,0.00042522,-3.36674e-07,9.78392e-08,1.072,0.00042484,-4.31568e-08,-5.42658e-08,1.07243,0.000424591,-2.05954e-07,1.45377e-11,1.07285,0.000424179,-2.0591e-07,5.42076e-08,1.07328,0.00042393,-4.32877e-08,-9.76357e-08,1.0737,0.00042355,-3.36195e-07,9.79165e-08,1.07412,0.000423172,-4.24451e-08,-5.56118e-08,1.07455,0.00042292,-2.09281e-07,5.32143e-09,1.07497,0.000422518,-1.93316e-07,3.43261e-08,1.07539,0.000422234,-9.0338e-08,-2.34165e-08,1.07581,0.000421983,-1.60588e-07,-5.98692e-08,1.07623,0.000421482,-3.40195e-07,1.43684e-07,1.07666,0.000421233,9.08574e-08,-1.5724e-07,1.07708,0.000420943,-3.80862e-07,1.27647e-07,1.0775,0.000420564,2.0791e-09,-1.1493e-07,1.07792,0.000420223,-3.4271e-07,9.36534e-08,1.07834,0.000419819,-6.17499e-08,-2.12653e-08,1.07876,0.000419632,-1.25546e-07,-8.59219e-09,1.07918,0.000419355,-1.51322e-07,-6.35752e-08,1.0796,0.000418861,-3.42048e-07,1.43684e-07,1.08002,0.000418608,8.90034e-08,-1.53532e-07,1.08043,0.000418326,-3.71593e-07,1.12817e-07,1.08085,0.000417921,-3.31414e-08,-5.93184e-08,1.08127,0.000417677,-2.11097e-07,5.24697e-09,1.08169,0.00041727,-1.95356e-07,3.83305e-08,1.0821,0.000416995,-8.03642e-08,-3.93597e-08,1.08252,0.000416716,-1.98443e-07,-1.0094e-10,1.08294,0.000416319,-1.98746e-07,3.97635e-08,1.08335,0.00041604,-7.94557e-08,-3.97437e-08,1.08377,0.000415762,-1.98687e-07,1.94215e-12,1.08419,0.000415365,-1.98681e-07,3.97359e-08,1.0846,0.000415087,-7.94732e-08,-3.97362e-08,1.08502,0.000414809,-1.98682e-07,-4.31063e-13,1.08543,0.000414411,-1.98683e-07,3.97379e-08,1.08584,0.000414133,-7.94694e-08,-3.97418e-08,1.08626,0.000413855,-1.98695e-07,2.00563e-11,1.08667,0.000413458,-1.98635e-07,3.96616e-08,1.08709,0.000413179,-7.965e-08,-3.9457e-08,1.0875,0.000412902,-1.98021e-07,-1.04281e-09,1.08791,0.000412502,-2.01149e-07,4.36282e-08,1.08832,0.000412231,-7.02648e-08,-5.42608e-08,1.08874,0.000411928,-2.33047e-07,5.42057e-08,1.08915,0.000411624,-7.04301e-08,-4.33527e-08,1.08956,0.000411353,-2.00488e-07,-4.07378e-12,1.08997,0.000410952,-2.005e-07,4.3369e-08,1.09038,0.000410681,-7.03934e-08,-5.42627e-08,1.09079,0.000410378,-2.33182e-07,5.44726e-08,1.0912,0.000410075,-6.97637e-08,-4.44186e-08,1.09161,0.000409802,-2.03019e-07,3.99235e-09,1.09202,0.000409408,-1.91042e-07,2.84491e-08,1.09243,0.000409111,-1.05695e-07,1.42043e-09,1.09284,0.000408904,-1.01434e-07,-3.41308e-08,1.09325,0.000408599,-2.03826e-07,1.58937e-08,1.09366,0.000408239,-1.56145e-07,-2.94438e-08,1.09406,0.000407838,-2.44476e-07,1.01881e-07,1.09447,0.000407655,6.11676e-08,-1.39663e-07,1.09488,0.000407358,-3.57822e-07,9.91432e-08,1.09529,0.00040694,-6.03921e-08,-1.84912e-08,1.09569,0.000406764,-1.15866e-07,-2.51785e-08,1.0961,0.000406457,-1.91401e-07,-4.03115e-12,1.09651,0.000406074,-1.91413e-07,2.51947e-08,1.09691,0.000405767,-1.15829e-07,1.84346e-08,1.09732,0.00040559,-6.05254e-08,-9.89332e-08,1.09772,0.000405172,-3.57325e-07,1.3888e-07,1.09813,0.000404874,5.93136e-08,-9.8957e-08,1.09853,0.000404696,-2.37557e-07,1.853e-08,1.09894,0.000404277,-1.81968e-07,2.48372e-08,1.09934,0.000403987,-1.07456e-07,1.33047e-09,1.09975,0.000403776,-1.03465e-07,-3.01591e-08,1.10015,0.000403479,-1.93942e-07,9.66054e-11,1.10055,0.000403091,-1.93652e-07,2.97727e-08,1.10096,0.000402793,-1.04334e-07,2.19273e-11,1.10136,0.000402585,-1.04268e-07,-2.98604e-08,1.10176,0.000402287,-1.93849e-07,2.10325e-10,1.10216,0.0004019,-1.93218e-07,2.90191e-08,1.10256,0.0004016,-1.06161e-07,2.92264e-09,1.10297,0.000401397,-9.73931e-08,-4.07096e-08,1.10337,0.00040108,-2.19522e-07,4.07067e-08,1.10377,0.000400763,-9.7402e-08,-2.90783e-09,1.10417,0.000400559,-1.06126e-07,-2.90754e-08,1.10457,0.00040026,-1.93352e-07,9.00021e-14,1.10497,0.000399873,-1.93351e-07,2.9075e-08,1.10537,0.000399574,-1.06126e-07,2.90902e-09,1.10577,0.00039937,-9.73992e-08,-4.07111e-08,1.10617,0.000399053,-2.19533e-07,4.07262e-08,1.10657,0.000398736,-9.73541e-08,-2.98424e-09,1.10697,0.000398533,-1.06307e-07,-2.87892e-08,1.10736,0.000398234,-1.92674e-07,-1.06824e-09,1.10776,0.000397845,-1.95879e-07,3.30622e-08,1.10816,0.000397552,-9.66926e-08,-1.19712e-08,1.10856,0.000397323,-1.32606e-07,1.48225e-08,1.10895,0.000397102,-8.81387e-08,-4.73187e-08,1.10935,0.000396784,-2.30095e-07,5.52429e-08,1.10975,0.00039649,-6.4366e-08,-5.44437e-08,1.11014,0.000396198,-2.27697e-07,4.33226e-08,1.11054,0.000395872,-9.77293e-08,3.62656e-10,1.11094,0.000395678,-9.66414e-08,-4.47732e-08,1.11133,0.00039535,-2.30961e-07,5.95208e-08,1.11173,0.000395067,-5.23985e-08,-7.41008e-08,1.11212,0.00039474,-2.74701e-07,1.17673e-07,1.11252,0.000394543,7.83181e-08,-1.58172e-07,1.11291,0.000394225,-3.96199e-07,1.57389e-07,1.1133,0.000393905,7.59679e-08,-1.13756e-07,1.1137,0.000393716,-2.653e-07,5.92165e-08,1.11409,0.000393363,-8.76507e-08,-3.90074e-09,1.11449,0.000393176,-9.93529e-08,-4.36136e-08,1.11488,0.000392846,-2.30194e-07,5.91457e-08,1.11527,0.000392563,-5.27564e-08,-7.376e-08,1.11566,0.000392237,-2.74037e-07,1.16685e-07,1.11606,0.000392039,7.60189e-08,-1.54562e-07,1.11645,0.000391727,-3.87667e-07,1.43935e-07,1.11684,0.000391384,4.4137e-08,-6.35487e-08,1.11723,0.000391281,-1.46509e-07,-8.94896e-09,1.11762,0.000390961,-1.73356e-07,-1.98647e-08,1.11801,0.000390555,-2.3295e-07,8.8408e-08,1.1184,0.000390354,3.22736e-08,-9.53486e-08,1.11879,0.000390133,-2.53772e-07,5.45677e-08,1.11918,0.000389789,-9.0069e-08,-3.71296e-09,1.11957,0.000389598,-1.01208e-07,-3.97159e-08,1.11996,0.000389276,-2.20355e-07,4.33671e-08,1.12035,0.000388966,-9.02542e-08,-1.45431e-08,1.12074,0.000388741,-1.33883e-07,1.48052e-08,1.12113,0.000388518,-8.94678e-08,-4.46778e-08,1.12152,0.000388205,-2.23501e-07,4.46966e-08,1.12191,0.000387892,-8.94114e-08,-1.48992e-08,1.12229,0.000387669,-1.34109e-07,1.49003e-08,1.12268,0.000387445,-8.94082e-08,-4.47019e-08,1.12307,0.000387132,-2.23514e-07,4.4698e-08,1.12345,0.000386819,-8.942e-08,-1.48806e-08,1.12384,0.000386596,-1.34062e-07,1.48245e-08,1.12423,0.000386372,-8.95885e-08,-4.44172e-08,1.12461,0.00038606,-2.2284e-07,4.36351e-08,1.125,0.000385745,-9.19348e-08,-1.09139e-08,1.12539,0.000385528,-1.24677e-07,2.05584e-11,1.12577,0.000385279,-1.24615e-07,1.08317e-08,1.12616,0.000385062,-9.21198e-08,-4.33473e-08,1.12654,0.000384748,-2.22162e-07,4.33481e-08,1.12693,0.000384434,-9.21174e-08,-1.08356e-08,1.12731,0.000384217,-1.24624e-07,-5.50907e-12,1.12769,0.000383968,-1.24641e-07,1.08577e-08,1.12808,0.000383751,-9.20679e-08,-4.34252e-08,1.12846,0.000383437,-2.22343e-07,4.36337e-08,1.12884,0.000383123,-9.14422e-08,-1.19005e-08,1.12923,0.000382904,-1.27144e-07,3.96813e-09,1.12961,0.000382662,-1.15239e-07,-3.97207e-09,1.12999,0.000382419,-1.27155e-07,1.19201e-08,1.13038,0.000382201,-9.1395e-08,-4.37085e-08,1.13076,0.000381887,-2.2252e-07,4.37046e-08,1.13114,0.000381573,-9.14068e-08,-1.19005e-08,1.13152,0.000381355,-1.27108e-07,3.89734e-09,1.1319,0.000381112,-1.15416e-07,-3.68887e-09,1.13228,0.00038087,-1.26483e-07,1.08582e-08,1.13266,0.00038065,-9.39083e-08,-3.97438e-08,1.13304,0.000380343,-2.1314e-07,2.89076e-08,1.13342,0.000380003,-1.26417e-07,4.33225e-08,1.1338,0.00037988,3.55072e-09,-8.29883e-08,1.13418,0.000379638,-2.45414e-07,5.0212e-08,1.13456,0.000379298,-9.47781e-08,1.34964e-09,1.13494,0.000379113,-9.07292e-08,-5.56105e-08,1.13532,0.000378764,-2.57561e-07,1.01883e-07,1.1357,0.000378555,4.80889e-08,-1.13504e-07,1.13608,0.000378311,-2.92423e-07,1.13713e-07,1.13646,0.000378067,4.87176e-08,-1.02931e-07,1.13683,0.000377856,-2.60076e-07,5.95923e-08,1.13721,0.000377514,-8.12988e-08,-1.62288e-08,1.13759,0.000377303,-1.29985e-07,5.32278e-09,1.13797,0.000377059,-1.14017e-07,-5.06237e-09,1.13834,0.000376816,-1.29204e-07,1.49267e-08,1.13872,0.000376602,-8.44237e-08,-5.46444e-08,1.1391,0.000376269,-2.48357e-07,8.44417e-08,1.13947,0.000376026,4.96815e-09,-4.47039e-08,1.13985,0.000375902,-1.29143e-07,-2.48355e-08,1.14023,0.000375569,-2.0365e-07,2.48368e-08,1.1406,0.000375236,-1.2914e-07,4.46977e-08,1.14098,0.000375112,4.95341e-09,-8.44184e-08,1.14135,0.000374869,-2.48302e-07,5.45572e-08,1.14173,0.000374536,-8.463e-08,-1.46013e-08,1.1421,0.000374323,-1.28434e-07,3.8478e-09,1.14247,0.000374077,-1.1689e-07,-7.89941e-10,1.14285,0.000373841,-1.1926e-07,-6.88042e-10,1.14322,0.0003736,-1.21324e-07,3.54213e-09,1.1436,0.000373368,-1.10698e-07,-1.34805e-08,1.14397,0.000373107,-1.51139e-07,5.03798e-08,1.14434,0.000372767,0.,0.}; template __device__ __forceinline__ void RGB2LuvConvert_f(const T& src, D& dst) { const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); const float _un = 13 * (4 * 0.950456f * _d); const float _vn = 13 * (9 * _d); float B = blueIdx == 0 ? src.x : src.z; float G = src.y; float R = blueIdx == 0 ? src.z : src.x; if (srgb) { B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); } float X = R * 0.412453f + G * 0.357580f + B * 0.180423f; float Y = R * 0.212671f + G * 0.715160f + B * 0.072169f; float Z = R * 0.019334f + G * 0.119193f + B * 0.950227f; float L = splineInterpolate(Y * (LAB_CBRT_TAB_SIZE / 1.5f), c_LabCbrtTab, LAB_CBRT_TAB_SIZE); L = 116.f * L - 16.f; const float d = (4 * 13) / ::fmaxf(X + 15 * Y + 3 * Z, numeric_limits::epsilon()); float u = L * (X * d - _un); float v = L * ((9 * 0.25f) * Y * d - _vn); dst.x = L; dst.y = u; dst.z = v; } template __device__ __forceinline__ void RGB2LuvConvert_b(const T& src, D& dst) { float3 srcf, dstf; srcf.x = src.x * (1.f / 255.f); srcf.y = src.y * (1.f / 255.f); srcf.z = src.z * (1.f / 255.f); RGB2LuvConvert_f(srcf, dstf); dst.x = saturate_cast(dstf.x * 2.55f); dst.y = saturate_cast(dstf.y * 0.72033898305084743f + 96.525423728813564f); dst.z = saturate_cast(dstf.z * 0.9732824427480916f + 136.259541984732824f); } template struct RGB2Luv; template struct RGB2Luv : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2LuvConvert_b(src, dst); return dst; } __host__ __device__ __forceinline__ RGB2Luv() {} __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} }; template struct RGB2Luv : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; RGB2LuvConvert_f(src, dst); return dst; } __host__ __device__ __forceinline__ RGB2Luv() {} __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} }; } #define OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(name, scn, dcn, srgb, blueIdx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::RGB2Luv functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; namespace color_detail { template __device__ __forceinline__ void Luv2RGBConvert_f(const T& src, D& dst) { const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); const float _un = 4 * 0.950456f * _d; const float _vn = 9 * _d; float L = src.x; float u = src.y; float v = src.z; float Y = (L + 16.f) * (1.f / 116.f); Y = Y * Y * Y; float d = (1.f / 13.f) / L; u = u * d + _un; v = v * d + _vn; float iv = 1.f / v; float X = 2.25f * u * Y * iv; float Z = (12 - 3 * u - 20 * v) * Y * 0.25f * iv; float B = 0.055648f * X - 0.204043f * Y + 1.057311f * Z; float G = -0.969256f * X + 1.875991f * Y + 0.041556f * Z; float R = 3.240479f * X - 1.537150f * Y - 0.498535f * Z; if (srgb) { B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); } dst.x = blueIdx == 0 ? B : R; dst.y = G; dst.z = blueIdx == 0 ? R : B; setAlpha(dst, ColorChannel::max()); } template __device__ __forceinline__ void Luv2RGBConvert_b(const T& src, D& dst) { float3 srcf, dstf; srcf.x = src.x * (100.f / 255.f); srcf.y = src.y * 1.388235294117647f - 134.f; srcf.z = src.z * 1.027450980392157f - 140.f; Luv2RGBConvert_f(srcf, dstf); dst.x = saturate_cast(dstf.x * 255.f); dst.y = saturate_cast(dstf.y * 255.f); dst.z = saturate_cast(dstf.z * 255.f); setAlpha(dst, ColorChannel::max()); } template struct Luv2RGB; template struct Luv2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; Luv2RGBConvert_b(src, dst); return dst; } __host__ __device__ __forceinline__ Luv2RGB() {} __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} }; template struct Luv2RGB : unary_function::vec_type, typename TypeVec::vec_type> { __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const { typename TypeVec::vec_type dst; Luv2RGBConvert_f(src, dst); return dst; } __host__ __device__ __forceinline__ Luv2RGB() {} __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} }; } #define OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ template struct name ## _traits \ { \ typedef ::cv::cuda::device::color_detail::Luv2RGB functor_type; \ static __host__ __device__ __forceinline__ functor_type create_functor() \ { \ return functor_type(); \ } \ }; #undef CV_DESCALE }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_COLOR_DETAIL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/detail/reduce.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_REDUCE_DETAIL_HPP__ #define __OPENCV_CUDA_REDUCE_DETAIL_HPP__ #include #include "../warp.hpp" #include "../warp_shuffle.hpp" //! @cond IGNORED namespace cv { namespace cuda { namespace device { namespace reduce_detail { template struct GetType; template struct GetType { typedef T type; }; template struct GetType { typedef T type; }; template struct GetType { typedef T type; }; template struct For { template static __device__ void loadToSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) { thrust::get(smem)[tid] = thrust::get(val); For::loadToSmem(smem, val, tid); } template static __device__ void loadFromSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) { thrust::get(val) = thrust::get(smem)[tid]; For::loadFromSmem(smem, val, tid); } template static __device__ void merge(const PointerTuple& smem, const ValTuple& val, unsigned int tid, unsigned int delta, const OpTuple& op) { typename GetType::type>::type reg = thrust::get(smem)[tid + delta]; thrust::get(smem)[tid] = thrust::get(val) = thrust::get(op)(thrust::get(val), reg); For::merge(smem, val, tid, delta, op); } template static __device__ void mergeShfl(const ValTuple& val, unsigned int delta, unsigned int width, const OpTuple& op) { typename GetType::type>::type reg = shfl_down(thrust::get(val), delta, width); thrust::get(val) = thrust::get(op)(thrust::get(val), reg); For::mergeShfl(val, delta, width, op); } }; template struct For { template static __device__ void loadToSmem(const PointerTuple&, const ValTuple&, unsigned int) { } template static __device__ void loadFromSmem(const PointerTuple&, const ValTuple&, unsigned int) { } template static __device__ void merge(const PointerTuple&, const ValTuple&, unsigned int, unsigned int, const OpTuple&) { } template static __device__ void mergeShfl(const ValTuple&, unsigned int, unsigned int, const OpTuple&) { } }; template __device__ __forceinline__ void loadToSmem(volatile T* smem, T& val, unsigned int tid) { smem[tid] = val; } template __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& val, unsigned int tid) { val = smem[tid]; } template __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) { For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); } template __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) { For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); } template __device__ __forceinline__ void merge(volatile T* smem, T& val, unsigned int tid, unsigned int delta, const Op& op) { T reg = smem[tid + delta]; smem[tid] = val = op(val, reg); } template __device__ __forceinline__ void mergeShfl(T& val, unsigned int delta, unsigned int width, const Op& op) { T reg = shfl_down(val, delta, width); val = op(val, reg); } template __device__ __forceinline__ void merge(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, unsigned int delta, const thrust::tuple& op) { For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); } template __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, unsigned int delta, unsigned int width, const thrust::tuple& op) { For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); } template struct Generic { template static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) { loadToSmem(smem, val, tid); if (N >= 32) __syncthreads(); if (N >= 2048) { if (tid < 1024) merge(smem, val, tid, 1024, op); __syncthreads(); } if (N >= 1024) { if (tid < 512) merge(smem, val, tid, 512, op); __syncthreads(); } if (N >= 512) { if (tid < 256) merge(smem, val, tid, 256, op); __syncthreads(); } if (N >= 256) { if (tid < 128) merge(smem, val, tid, 128, op); __syncthreads(); } if (N >= 128) { if (tid < 64) merge(smem, val, tid, 64, op); __syncthreads(); } if (N >= 64) { if (tid < 32) merge(smem, val, tid, 32, op); } if (tid < 16) { merge(smem, val, tid, 16, op); merge(smem, val, tid, 8, op); merge(smem, val, tid, 4, op); merge(smem, val, tid, 2, op); merge(smem, val, tid, 1, op); } } }; template struct Unroll { static __device__ void loopShfl(Reference val, Op op, unsigned int N) { mergeShfl(val, I, N, op); Unroll::loopShfl(val, op, N); } static __device__ void loop(Pointer smem, Reference val, unsigned int tid, Op op) { merge(smem, val, tid, I, op); Unroll::loop(smem, val, tid, op); } }; template struct Unroll<0, Pointer, Reference, Op> { static __device__ void loopShfl(Reference, Op, unsigned int) { } static __device__ void loop(Pointer, Reference, unsigned int, Op) { } }; template struct WarpOptimized { template static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) { #if __CUDA_ARCH__ >= 300 (void) smem; (void) tid; Unroll::loopShfl(val, op, N); #else loadToSmem(smem, val, tid); if (tid < N / 2) Unroll::loop(smem, val, tid, op); #endif } }; template struct GenericOptimized32 { enum { M = N / 32 }; template static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) { const unsigned int laneId = Warp::laneId(); #if __CUDA_ARCH__ >= 300 Unroll<16, Pointer, Reference, Op>::loopShfl(val, op, warpSize); if (laneId == 0) loadToSmem(smem, val, tid / 32); #else loadToSmem(smem, val, tid); if (laneId < 16) Unroll<16, Pointer, Reference, Op>::loop(smem, val, tid, op); __syncthreads(); if (laneId == 0) loadToSmem(smem, val, tid / 32); #endif __syncthreads(); loadFromSmem(smem, val, tid); if (tid < 32) { #if __CUDA_ARCH__ >= 300 Unroll::loopShfl(val, op, M); #else Unroll::loop(smem, val, tid, op); #endif } } }; template struct StaticIf; template struct StaticIf { typedef T1 type; }; template struct StaticIf { typedef T2 type; }; template struct IsPowerOf2 { enum { value = ((N != 0) && !(N & (N - 1))) }; }; template struct Dispatcher { typedef typename StaticIf< (N <= 32) && IsPowerOf2::value, WarpOptimized, typename StaticIf< (N <= 1024) && IsPowerOf2::value, GenericOptimized32, Generic >::type >::type reductor; }; } }}} //! @endcond #endif // __OPENCV_CUDA_REDUCE_DETAIL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/detail/reduce_key_val.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP__ #define __OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP__ #include #include "../warp.hpp" #include "../warp_shuffle.hpp" //! @cond IGNORED namespace cv { namespace cuda { namespace device { namespace reduce_key_val_detail { template struct GetType; template struct GetType { typedef T type; }; template struct GetType { typedef T type; }; template struct GetType { typedef T type; }; template struct For { template static __device__ void loadToSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) { thrust::get(smem)[tid] = thrust::get(data); For::loadToSmem(smem, data, tid); } template static __device__ void loadFromSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) { thrust::get(data) = thrust::get(smem)[tid]; For::loadFromSmem(smem, data, tid); } template static __device__ void copyShfl(const ReferenceTuple& val, unsigned int delta, int width) { thrust::get(val) = shfl_down(thrust::get(val), delta, width); For::copyShfl(val, delta, width); } template static __device__ void copy(const PointerTuple& svals, const ReferenceTuple& val, unsigned int tid, unsigned int delta) { thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; For::copy(svals, val, tid, delta); } template static __device__ void mergeShfl(const KeyReferenceTuple& key, const ValReferenceTuple& val, const CmpTuple& cmp, unsigned int delta, int width) { typename GetType::type>::type reg = shfl_down(thrust::get(key), delta, width); if (thrust::get(cmp)(reg, thrust::get(key))) { thrust::get(key) = reg; thrust::get(val) = shfl_down(thrust::get(val), delta, width); } For::mergeShfl(key, val, cmp, delta, width); } template static __device__ void merge(const KeyPointerTuple& skeys, const KeyReferenceTuple& key, const ValPointerTuple& svals, const ValReferenceTuple& val, const CmpTuple& cmp, unsigned int tid, unsigned int delta) { typename GetType::type>::type reg = thrust::get(skeys)[tid + delta]; if (thrust::get(cmp)(reg, thrust::get(key))) { thrust::get(skeys)[tid] = thrust::get(key) = reg; thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; } For::merge(skeys, key, svals, val, cmp, tid, delta); } }; template struct For { template static __device__ void loadToSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) { } template static __device__ void loadFromSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) { } template static __device__ void copyShfl(const ReferenceTuple&, unsigned int, int) { } template static __device__ void copy(const PointerTuple&, const ReferenceTuple&, unsigned int, unsigned int) { } template static __device__ void mergeShfl(const KeyReferenceTuple&, const ValReferenceTuple&, const CmpTuple&, unsigned int, int) { } template static __device__ void merge(const KeyPointerTuple&, const KeyReferenceTuple&, const ValPointerTuple&, const ValReferenceTuple&, const CmpTuple&, unsigned int, unsigned int) { } }; ////////////////////////////////////////////////////// // loadToSmem template __device__ __forceinline__ void loadToSmem(volatile T* smem, T& data, unsigned int tid) { smem[tid] = data; } template __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& data, unsigned int tid) { data = smem[tid]; } template __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) { For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); } template __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) { For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); } ////////////////////////////////////////////////////// // copyVals template __device__ __forceinline__ void copyValsShfl(V& val, unsigned int delta, int width) { val = shfl_down(val, delta, width); } template __device__ __forceinline__ void copyVals(volatile V* svals, V& val, unsigned int tid, unsigned int delta) { svals[tid] = val = svals[tid + delta]; } template __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, unsigned int delta, int width) { For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); } template __device__ __forceinline__ void copyVals(const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, unsigned int delta) { For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); } ////////////////////////////////////////////////////// // merge template __device__ __forceinline__ void mergeShfl(K& key, V& val, const Cmp& cmp, unsigned int delta, int width) { K reg = shfl_down(key, delta, width); if (cmp(reg, key)) { key = reg; copyValsShfl(val, delta, width); } } template __device__ __forceinline__ void merge(volatile K* skeys, K& key, volatile V* svals, V& val, const Cmp& cmp, unsigned int tid, unsigned int delta) { K reg = skeys[tid + delta]; if (cmp(reg, key)) { skeys[tid] = key = reg; copyVals(svals, val, tid, delta); } } template __device__ __forceinline__ void mergeShfl(K& key, const thrust::tuple& val, const Cmp& cmp, unsigned int delta, int width) { K reg = shfl_down(key, delta, width); if (cmp(reg, key)) { key = reg; copyValsShfl(val, delta, width); } } template __device__ __forceinline__ void merge(volatile K* skeys, K& key, const thrust::tuple& svals, const thrust::tuple& val, const Cmp& cmp, unsigned int tid, unsigned int delta) { K reg = skeys[tid + delta]; if (cmp(reg, key)) { skeys[tid] = key = reg; copyVals(svals, val, tid, delta); } } template __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, const thrust::tuple& val, const thrust::tuple& cmp, unsigned int delta, int width) { For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); } template __device__ __forceinline__ void merge(const thrust::tuple& skeys, const thrust::tuple& key, const thrust::tuple& svals, const thrust::tuple& val, const thrust::tuple& cmp, unsigned int tid, unsigned int delta) { For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); } ////////////////////////////////////////////////////// // Generic template struct Generic { template static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) { loadToSmem(skeys, key, tid); loadValsToSmem(svals, val, tid); if (N >= 32) __syncthreads(); if (N >= 2048) { if (tid < 1024) merge(skeys, key, svals, val, cmp, tid, 1024); __syncthreads(); } if (N >= 1024) { if (tid < 512) merge(skeys, key, svals, val, cmp, tid, 512); __syncthreads(); } if (N >= 512) { if (tid < 256) merge(skeys, key, svals, val, cmp, tid, 256); __syncthreads(); } if (N >= 256) { if (tid < 128) merge(skeys, key, svals, val, cmp, tid, 128); __syncthreads(); } if (N >= 128) { if (tid < 64) merge(skeys, key, svals, val, cmp, tid, 64); __syncthreads(); } if (N >= 64) { if (tid < 32) merge(skeys, key, svals, val, cmp, tid, 32); } if (tid < 16) { merge(skeys, key, svals, val, cmp, tid, 16); merge(skeys, key, svals, val, cmp, tid, 8); merge(skeys, key, svals, val, cmp, tid, 4); merge(skeys, key, svals, val, cmp, tid, 2); merge(skeys, key, svals, val, cmp, tid, 1); } } }; template struct Unroll { static __device__ void loopShfl(KR key, VR val, Cmp cmp, unsigned int N) { mergeShfl(key, val, cmp, I, N); Unroll::loopShfl(key, val, cmp, N); } static __device__ void loop(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) { merge(skeys, key, svals, val, cmp, tid, I); Unroll::loop(skeys, key, svals, val, tid, cmp); } }; template struct Unroll<0, KP, KR, VP, VR, Cmp> { static __device__ void loopShfl(KR, VR, Cmp, unsigned int) { } static __device__ void loop(KP, KR, VP, VR, unsigned int, Cmp) { } }; template struct WarpOptimized { template static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) { #if 0 // __CUDA_ARCH__ >= 300 (void) skeys; (void) svals; (void) tid; Unroll::loopShfl(key, val, cmp, N); #else loadToSmem(skeys, key, tid); loadToSmem(svals, val, tid); if (tid < N / 2) Unroll::loop(skeys, key, svals, val, tid, cmp); #endif } }; template struct GenericOptimized32 { enum { M = N / 32 }; template static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) { const unsigned int laneId = Warp::laneId(); #if 0 // __CUDA_ARCH__ >= 300 Unroll<16, KP, KR, VP, VR, Cmp>::loopShfl(key, val, cmp, warpSize); if (laneId == 0) { loadToSmem(skeys, key, tid / 32); loadToSmem(svals, val, tid / 32); } #else loadToSmem(skeys, key, tid); loadToSmem(svals, val, tid); if (laneId < 16) Unroll<16, KP, KR, VP, VR, Cmp>::loop(skeys, key, svals, val, tid, cmp); __syncthreads(); if (laneId == 0) { loadToSmem(skeys, key, tid / 32); loadToSmem(svals, val, tid / 32); } #endif __syncthreads(); loadFromSmem(skeys, key, tid); if (tid < 32) { #if 0 // __CUDA_ARCH__ >= 300 loadFromSmem(svals, val, tid); Unroll::loopShfl(key, val, cmp, M); #else Unroll::loop(skeys, key, svals, val, tid, cmp); #endif } } }; template struct StaticIf; template struct StaticIf { typedef T1 type; }; template struct StaticIf { typedef T2 type; }; template struct IsPowerOf2 { enum { value = ((N != 0) && !(N & (N - 1))) }; }; template struct Dispatcher { typedef typename StaticIf< (N <= 32) && IsPowerOf2::value, WarpOptimized, typename StaticIf< (N <= 1024) && IsPowerOf2::value, GenericOptimized32, Generic >::type >::type reductor; }; } }}} //! @endcond #endif // __OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/detail/transform_detail.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_TRANSFORM_DETAIL_HPP__ #define __OPENCV_CUDA_TRANSFORM_DETAIL_HPP__ #include "../common.hpp" #include "../vec_traits.hpp" #include "../functional.hpp" //! @cond IGNORED namespace cv { namespace cuda { namespace device { namespace transform_detail { //! Read Write Traits template struct UnaryReadWriteTraits { typedef typename TypeVec::vec_type read_type; typedef typename TypeVec::vec_type write_type; }; template struct BinaryReadWriteTraits { typedef typename TypeVec::vec_type read_type1; typedef typename TypeVec::vec_type read_type2; typedef typename TypeVec::vec_type write_type; }; //! Transform kernels template struct OpUnroller; template <> struct OpUnroller<1> { template static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src.x); } template static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src1.x, src2.x); } }; template <> struct OpUnroller<2> { template static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src.x); if (mask(y, x_shifted + 1)) dst.y = op(src.y); } template static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src1.x, src2.x); if (mask(y, x_shifted + 1)) dst.y = op(src1.y, src2.y); } }; template <> struct OpUnroller<3> { template static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src.x); if (mask(y, x_shifted + 1)) dst.y = op(src.y); if (mask(y, x_shifted + 2)) dst.z = op(src.z); } template static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src1.x, src2.x); if (mask(y, x_shifted + 1)) dst.y = op(src1.y, src2.y); if (mask(y, x_shifted + 2)) dst.z = op(src1.z, src2.z); } }; template <> struct OpUnroller<4> { template static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src.x); if (mask(y, x_shifted + 1)) dst.y = op(src.y); if (mask(y, x_shifted + 2)) dst.z = op(src.z); if (mask(y, x_shifted + 3)) dst.w = op(src.w); } template static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.x = op(src1.x, src2.x); if (mask(y, x_shifted + 1)) dst.y = op(src1.y, src2.y); if (mask(y, x_shifted + 2)) dst.z = op(src1.z, src2.z); if (mask(y, x_shifted + 3)) dst.w = op(src1.w, src2.w); } }; template <> struct OpUnroller<8> { template static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.a0 = op(src.a0); if (mask(y, x_shifted + 1)) dst.a1 = op(src.a1); if (mask(y, x_shifted + 2)) dst.a2 = op(src.a2); if (mask(y, x_shifted + 3)) dst.a3 = op(src.a3); if (mask(y, x_shifted + 4)) dst.a4 = op(src.a4); if (mask(y, x_shifted + 5)) dst.a5 = op(src.a5); if (mask(y, x_shifted + 6)) dst.a6 = op(src.a6); if (mask(y, x_shifted + 7)) dst.a7 = op(src.a7); } template static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) { if (mask(y, x_shifted)) dst.a0 = op(src1.a0, src2.a0); if (mask(y, x_shifted + 1)) dst.a1 = op(src1.a1, src2.a1); if (mask(y, x_shifted + 2)) dst.a2 = op(src1.a2, src2.a2); if (mask(y, x_shifted + 3)) dst.a3 = op(src1.a3, src2.a3); if (mask(y, x_shifted + 4)) dst.a4 = op(src1.a4, src2.a4); if (mask(y, x_shifted + 5)) dst.a5 = op(src1.a5, src2.a5); if (mask(y, x_shifted + 6)) dst.a6 = op(src1.a6, src2.a6); if (mask(y, x_shifted + 7)) dst.a7 = op(src1.a7, src2.a7); } }; template static __global__ void transformSmart(const PtrStepSz src_, PtrStep dst_, const Mask mask, const UnOp op) { typedef TransformFunctorTraits ft; typedef typename UnaryReadWriteTraits::read_type read_type; typedef typename UnaryReadWriteTraits::write_type write_type; const int x = threadIdx.x + blockIdx.x * blockDim.x; const int y = threadIdx.y + blockIdx.y * blockDim.y; const int x_shifted = x * ft::smart_shift; if (y < src_.rows) { const T* src = src_.ptr(y); D* dst = dst_.ptr(y); if (x_shifted + ft::smart_shift - 1 < src_.cols) { const read_type src_n_el = ((const read_type*)src)[x]; write_type dst_n_el = ((const write_type*)dst)[x]; OpUnroller::unroll(src_n_el, dst_n_el, mask, op, x_shifted, y); ((write_type*)dst)[x] = dst_n_el; } else { for (int real_x = x_shifted; real_x < src_.cols; ++real_x) { if (mask(y, real_x)) dst[real_x] = op(src[real_x]); } } } } template __global__ static void transformSimple(const PtrStepSz src, PtrStep dst, const Mask mask, const UnOp op) { const int x = blockDim.x * blockIdx.x + threadIdx.x; const int y = blockDim.y * blockIdx.y + threadIdx.y; if (x < src.cols && y < src.rows && mask(y, x)) { dst.ptr(y)[x] = op(src.ptr(y)[x]); } } template static __global__ void transformSmart(const PtrStepSz src1_, const PtrStep src2_, PtrStep dst_, const Mask mask, const BinOp op) { typedef TransformFunctorTraits ft; typedef typename BinaryReadWriteTraits::read_type1 read_type1; typedef typename BinaryReadWriteTraits::read_type2 read_type2; typedef typename BinaryReadWriteTraits::write_type write_type; const int x = threadIdx.x + blockIdx.x * blockDim.x; const int y = threadIdx.y + blockIdx.y * blockDim.y; const int x_shifted = x * ft::smart_shift; if (y < src1_.rows) { const T1* src1 = src1_.ptr(y); const T2* src2 = src2_.ptr(y); D* dst = dst_.ptr(y); if (x_shifted + ft::smart_shift - 1 < src1_.cols) { const read_type1 src1_n_el = ((const read_type1*)src1)[x]; const read_type2 src2_n_el = ((const read_type2*)src2)[x]; write_type dst_n_el = ((const write_type*)dst)[x]; OpUnroller::unroll(src1_n_el, src2_n_el, dst_n_el, mask, op, x_shifted, y); ((write_type*)dst)[x] = dst_n_el; } else { for (int real_x = x_shifted; real_x < src1_.cols; ++real_x) { if (mask(y, real_x)) dst[real_x] = op(src1[real_x], src2[real_x]); } } } } template static __global__ void transformSimple(const PtrStepSz src1, const PtrStep src2, PtrStep dst, const Mask mask, const BinOp op) { const int x = blockDim.x * blockIdx.x + threadIdx.x; const int y = blockDim.y * blockIdx.y + threadIdx.y; if (x < src1.cols && y < src1.rows && mask(y, x)) { const T1 src1_data = src1.ptr(y)[x]; const T2 src2_data = src2.ptr(y)[x]; dst.ptr(y)[x] = op(src1_data, src2_data); } } template struct TransformDispatcher; template<> struct TransformDispatcher { template static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) { typedef TransformFunctorTraits ft; const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); const dim3 grid(divUp(src.cols, threads.x), divUp(src.rows, threads.y), 1); transformSimple<<>>(src, dst, mask, op); cudaSafeCall( cudaGetLastError() ); if (stream == 0) cudaSafeCall( cudaDeviceSynchronize() ); } template static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) { typedef TransformFunctorTraits ft; const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); const dim3 grid(divUp(src1.cols, threads.x), divUp(src1.rows, threads.y), 1); transformSimple<<>>(src1, src2, dst, mask, op); cudaSafeCall( cudaGetLastError() ); if (stream == 0) cudaSafeCall( cudaDeviceSynchronize() ); } }; template<> struct TransformDispatcher { template static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) { typedef TransformFunctorTraits ft; CV_StaticAssert(ft::smart_shift != 1, ""); if (!isAligned(src.data, ft::smart_shift * sizeof(T)) || !isAligned(src.step, ft::smart_shift * sizeof(T)) || !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) { TransformDispatcher::call(src, dst, op, mask, stream); return; } const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); const dim3 grid(divUp(src.cols, threads.x * ft::smart_shift), divUp(src.rows, threads.y), 1); transformSmart<<>>(src, dst, mask, op); cudaSafeCall( cudaGetLastError() ); if (stream == 0) cudaSafeCall( cudaDeviceSynchronize() ); } template static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) { typedef TransformFunctorTraits ft; CV_StaticAssert(ft::smart_shift != 1, ""); if (!isAligned(src1.data, ft::smart_shift * sizeof(T1)) || !isAligned(src1.step, ft::smart_shift * sizeof(T1)) || !isAligned(src2.data, ft::smart_shift * sizeof(T2)) || !isAligned(src2.step, ft::smart_shift * sizeof(T2)) || !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) { TransformDispatcher::call(src1, src2, dst, op, mask, stream); return; } const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); const dim3 grid(divUp(src1.cols, threads.x * ft::smart_shift), divUp(src1.rows, threads.y), 1); transformSmart<<>>(src1, src2, dst, mask, op); cudaSafeCall( cudaGetLastError() ); if (stream == 0) cudaSafeCall( cudaDeviceSynchronize() ); } }; } // namespace transform_detail }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_TRANSFORM_DETAIL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/detail/type_traits_detail.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP__ #define __OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP__ #include "../common.hpp" #include "../vec_traits.hpp" //! @cond IGNORED namespace cv { namespace cuda { namespace device { namespace type_traits_detail { template struct Select { typedef T1 type; }; template struct Select { typedef T2 type; }; template struct IsSignedIntergral { enum {value = 0}; }; template <> struct IsSignedIntergral { enum {value = 1}; }; template <> struct IsSignedIntergral { enum {value = 1}; }; template <> struct IsSignedIntergral { enum {value = 1}; }; template <> struct IsSignedIntergral { enum {value = 1}; }; template <> struct IsSignedIntergral { enum {value = 1}; }; template <> struct IsSignedIntergral { enum {value = 1}; }; template struct IsUnsignedIntegral { enum {value = 0}; }; template <> struct IsUnsignedIntegral { enum {value = 1}; }; template <> struct IsUnsignedIntegral { enum {value = 1}; }; template <> struct IsUnsignedIntegral { enum {value = 1}; }; template <> struct IsUnsignedIntegral { enum {value = 1}; }; template <> struct IsUnsignedIntegral { enum {value = 1}; }; template <> struct IsUnsignedIntegral { enum {value = 1}; }; template struct IsIntegral { enum {value = IsSignedIntergral::value || IsUnsignedIntegral::value}; }; template <> struct IsIntegral { enum {value = 1}; }; template <> struct IsIntegral { enum {value = 1}; }; template struct IsFloat { enum {value = 0}; }; template <> struct IsFloat { enum {value = 1}; }; template <> struct IsFloat { enum {value = 1}; }; template struct IsVec { enum {value = 0}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template <> struct IsVec { enum {value = 1}; }; template struct AddParameterType { typedef const U& type; }; template struct AddParameterType { typedef U& type; }; template <> struct AddParameterType { typedef void type; }; template struct ReferenceTraits { enum { value = false }; typedef U type; }; template struct ReferenceTraits { enum { value = true }; typedef U type; }; template struct PointerTraits { enum { value = false }; typedef void type; }; template struct PointerTraits { enum { value = true }; typedef U type; }; template struct PointerTraits { enum { value = true }; typedef U type; }; template struct UnConst { typedef U type; enum { value = 0 }; }; template struct UnConst { typedef U type; enum { value = 1 }; }; template struct UnConst { typedef U& type; enum { value = 1 }; }; template struct UnVolatile { typedef U type; enum { value = 0 }; }; template struct UnVolatile { typedef U type; enum { value = 1 }; }; template struct UnVolatile { typedef U& type; enum { value = 1 }; }; } // namespace type_traits_detail }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/detail/vec_distance_detail.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP__ #define __OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP__ #include "../datamov_utils.hpp" //! @cond IGNORED namespace cv { namespace cuda { namespace device { namespace vec_distance_detail { template struct UnrollVecDiffCached { template static __device__ void calcCheck(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int ind) { if (ind < len) { T1 val1 = *vecCached++; T2 val2; ForceGlob::Load(vecGlob, ind, val2); dist.reduceIter(val1, val2); UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, ind + THREAD_DIM); } } template static __device__ void calcWithoutCheck(const T1* vecCached, const T2* vecGlob, Dist& dist) { T1 val1 = *vecCached++; T2 val2; ForceGlob::Load(vecGlob, 0, val2); vecGlob += THREAD_DIM; dist.reduceIter(val1, val2); UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob, dist); } }; template struct UnrollVecDiffCached { template static __device__ __forceinline__ void calcCheck(const T1*, const T2*, int, Dist&, int) { } template static __device__ __forceinline__ void calcWithoutCheck(const T1*, const T2*, Dist&) { } }; template struct VecDiffCachedCalculator; template struct VecDiffCachedCalculator { template static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) { UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, tid); } }; template struct VecDiffCachedCalculator { template static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) { UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob + tid, dist); } }; } // namespace vec_distance_detail }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/dynamic_smem.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_DYNAMIC_SMEM_HPP__ #define __OPENCV_CUDA_DYNAMIC_SMEM_HPP__ /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template struct DynamicSharedMem { __device__ __forceinline__ operator T*() { extern __shared__ int __smem[]; return (T*)__smem; } __device__ __forceinline__ operator const T*() const { extern __shared__ int __smem[]; return (T*)__smem; } }; // specialize for double to avoid unaligned memory access compile errors template<> struct DynamicSharedMem { __device__ __forceinline__ operator double*() { extern __shared__ double __smem_d[]; return (double*)__smem_d; } __device__ __forceinline__ operator const double*() const { extern __shared__ double __smem_d[]; return (double*)__smem_d; } }; }}} //! @endcond #endif // __OPENCV_CUDA_DYNAMIC_SMEM_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/emulation.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_CUDA_EMULATION_HPP_ #define OPENCV_CUDA_EMULATION_HPP_ #include "common.hpp" #include "warp_reduce.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { struct Emulation { static __device__ __forceinline__ int syncthreadsOr(int pred) { #if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 200) // just campilation stab return 0; #else return __syncthreads_or(pred); #endif } template static __forceinline__ __device__ int Ballot(int predicate) { #if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ >= 200) return __ballot(predicate); #else __shared__ volatile int cta_buffer[CTA_SIZE]; int tid = threadIdx.x; cta_buffer[tid] = predicate ? (1 << (tid & 31)) : 0; return warp_reduce(cta_buffer); #endif } struct smem { enum { TAG_MASK = (1U << ( (sizeof(unsigned int) << 3) - 5U)) - 1U }; template static __device__ __forceinline__ T atomicInc(T* address, T val) { #if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) T count; unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); do { count = *address & TAG_MASK; count = tag | (count + 1); *address = count; } while (*address != count); return (count & TAG_MASK) - 1; #else return ::atomicInc(address, val); #endif } template static __device__ __forceinline__ T atomicAdd(T* address, T val) { #if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) T count; unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); do { count = *address & TAG_MASK; count = tag | (count + val); *address = count; } while (*address != count); return (count & TAG_MASK) - val; #else return ::atomicAdd(address, val); #endif } template static __device__ __forceinline__ T atomicMin(T* address, T val) { #if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) T count = ::min(*address, val); do { *address = count; } while (*address > count); return count; #else return ::atomicMin(address, val); #endif } }; // struct cmem struct glob { static __device__ __forceinline__ int atomicAdd(int* address, int val) { return ::atomicAdd(address, val); } static __device__ __forceinline__ unsigned int atomicAdd(unsigned int* address, unsigned int val) { return ::atomicAdd(address, val); } static __device__ __forceinline__ float atomicAdd(float* address, float val) { #if __CUDA_ARCH__ >= 200 return ::atomicAdd(address, val); #else int* address_as_i = (int*) address; int old = *address_as_i, assumed; do { assumed = old; old = ::atomicCAS(address_as_i, assumed, __float_as_int(val + __int_as_float(assumed))); } while (assumed != old); return __int_as_float(old); #endif } static __device__ __forceinline__ double atomicAdd(double* address, double val) { #if __CUDA_ARCH__ >= 130 unsigned long long int* address_as_ull = (unsigned long long int*) address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = ::atomicCAS(address_as_ull, assumed, __double_as_longlong(val + __longlong_as_double(assumed))); } while (assumed != old); return __longlong_as_double(old); #else (void) address; (void) val; return 0.0; #endif } static __device__ __forceinline__ int atomicMin(int* address, int val) { return ::atomicMin(address, val); } static __device__ __forceinline__ float atomicMin(float* address, float val) { #if __CUDA_ARCH__ >= 120 int* address_as_i = (int*) address; int old = *address_as_i, assumed; do { assumed = old; old = ::atomicCAS(address_as_i, assumed, __float_as_int(::fminf(val, __int_as_float(assumed)))); } while (assumed != old); return __int_as_float(old); #else (void) address; (void) val; return 0.0f; #endif } static __device__ __forceinline__ double atomicMin(double* address, double val) { #if __CUDA_ARCH__ >= 130 unsigned long long int* address_as_ull = (unsigned long long int*) address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = ::atomicCAS(address_as_ull, assumed, __double_as_longlong(::fmin(val, __longlong_as_double(assumed)))); } while (assumed != old); return __longlong_as_double(old); #else (void) address; (void) val; return 0.0; #endif } static __device__ __forceinline__ int atomicMax(int* address, int val) { return ::atomicMax(address, val); } static __device__ __forceinline__ float atomicMax(float* address, float val) { #if __CUDA_ARCH__ >= 120 int* address_as_i = (int*) address; int old = *address_as_i, assumed; do { assumed = old; old = ::atomicCAS(address_as_i, assumed, __float_as_int(::fmaxf(val, __int_as_float(assumed)))); } while (assumed != old); return __int_as_float(old); #else (void) address; (void) val; return 0.0f; #endif } static __device__ __forceinline__ double atomicMax(double* address, double val) { #if __CUDA_ARCH__ >= 130 unsigned long long int* address_as_ull = (unsigned long long int*) address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = ::atomicCAS(address_as_ull, assumed, __double_as_longlong(::fmax(val, __longlong_as_double(assumed)))); } while (assumed != old); return __longlong_as_double(old); #else (void) address; (void) val; return 0.0; #endif } }; }; //struct Emulation }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif /* OPENCV_CUDA_EMULATION_HPP_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/filters.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_FILTERS_HPP__ #define __OPENCV_CUDA_FILTERS_HPP__ #include "saturate_cast.hpp" #include "vec_traits.hpp" #include "vec_math.hpp" #include "type_traits.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template struct PointFilter { typedef typename Ptr2D::elem_type elem_type; typedef float index_type; explicit __host__ __device__ __forceinline__ PointFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) : src(src_) { (void)fx; (void)fy; } __device__ __forceinline__ elem_type operator ()(float y, float x) const { return src(__float2int_rz(y), __float2int_rz(x)); } Ptr2D src; }; template struct LinearFilter { typedef typename Ptr2D::elem_type elem_type; typedef float index_type; explicit __host__ __device__ __forceinline__ LinearFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) : src(src_) { (void)fx; (void)fy; } __device__ __forceinline__ elem_type operator ()(float y, float x) const { typedef typename TypeVec::cn>::vec_type work_type; work_type out = VecTraits::all(0); const int x1 = __float2int_rd(x); const int y1 = __float2int_rd(y); const int x2 = x1 + 1; const int y2 = y1 + 1; elem_type src_reg = src(y1, x1); out = out + src_reg * ((x2 - x) * (y2 - y)); src_reg = src(y1, x2); out = out + src_reg * ((x - x1) * (y2 - y)); src_reg = src(y2, x1); out = out + src_reg * ((x2 - x) * (y - y1)); src_reg = src(y2, x2); out = out + src_reg * ((x - x1) * (y - y1)); return saturate_cast(out); } Ptr2D src; }; template struct CubicFilter { typedef typename Ptr2D::elem_type elem_type; typedef float index_type; typedef typename TypeVec::cn>::vec_type work_type; explicit __host__ __device__ __forceinline__ CubicFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) : src(src_) { (void)fx; (void)fy; } static __device__ __forceinline__ float bicubicCoeff(float x_) { float x = fabsf(x_); if (x <= 1.0f) { return x * x * (1.5f * x - 2.5f) + 1.0f; } else if (x < 2.0f) { return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f; } else { return 0.0f; } } __device__ elem_type operator ()(float y, float x) const { const float xmin = ::ceilf(x - 2.0f); const float xmax = ::floorf(x + 2.0f); const float ymin = ::ceilf(y - 2.0f); const float ymax = ::floorf(y + 2.0f); work_type sum = VecTraits::all(0); float wsum = 0.0f; for (float cy = ymin; cy <= ymax; cy += 1.0f) { for (float cx = xmin; cx <= xmax; cx += 1.0f) { const float w = bicubicCoeff(x - cx) * bicubicCoeff(y - cy); sum = sum + w * src(__float2int_rd(cy), __float2int_rd(cx)); wsum += w; } } work_type res = (!wsum)? VecTraits::all(0) : sum / wsum; return saturate_cast(res); } Ptr2D src; }; // for integer scaling template struct IntegerAreaFilter { typedef typename Ptr2D::elem_type elem_type; typedef float index_type; explicit __host__ __device__ __forceinline__ IntegerAreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) : src(src_), scale_x(scale_x_), scale_y(scale_y_), scale(1.f / (scale_x * scale_y)) {} __device__ __forceinline__ elem_type operator ()(float y, float x) const { float fsx1 = x * scale_x; float fsx2 = fsx1 + scale_x; int sx1 = __float2int_ru(fsx1); int sx2 = __float2int_rd(fsx2); float fsy1 = y * scale_y; float fsy2 = fsy1 + scale_y; int sy1 = __float2int_ru(fsy1); int sy2 = __float2int_rd(fsy2); typedef typename TypeVec::cn>::vec_type work_type; work_type out = VecTraits::all(0.f); for(int dy = sy1; dy < sy2; ++dy) for(int dx = sx1; dx < sx2; ++dx) { out = out + src(dy, dx) * scale; } return saturate_cast(out); } Ptr2D src; float scale_x, scale_y ,scale; }; template struct AreaFilter { typedef typename Ptr2D::elem_type elem_type; typedef float index_type; explicit __host__ __device__ __forceinline__ AreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) : src(src_), scale_x(scale_x_), scale_y(scale_y_){} __device__ __forceinline__ elem_type operator ()(float y, float x) const { float fsx1 = x * scale_x; float fsx2 = fsx1 + scale_x; int sx1 = __float2int_ru(fsx1); int sx2 = __float2int_rd(fsx2); float fsy1 = y * scale_y; float fsy2 = fsy1 + scale_y; int sy1 = __float2int_ru(fsy1); int sy2 = __float2int_rd(fsy2); float scale = 1.f / (fminf(scale_x, src.width - fsx1) * fminf(scale_y, src.height - fsy1)); typedef typename TypeVec::cn>::vec_type work_type; work_type out = VecTraits::all(0.f); for (int dy = sy1; dy < sy2; ++dy) { for (int dx = sx1; dx < sx2; ++dx) out = out + src(dy, dx) * scale; if (sx1 > fsx1) out = out + src(dy, (sx1 -1) ) * ((sx1 - fsx1) * scale); if (sx2 < fsx2) out = out + src(dy, sx2) * ((fsx2 -sx2) * scale); } if (sy1 > fsy1) for (int dx = sx1; dx < sx2; ++dx) out = out + src( (sy1 - 1) , dx) * ((sy1 -fsy1) * scale); if (sy2 < fsy2) for (int dx = sx1; dx < sx2; ++dx) out = out + src(sy2, dx) * ((fsy2 -sy2) * scale); if ((sy1 > fsy1) && (sx1 > fsx1)) out = out + src( (sy1 - 1) , (sx1 - 1)) * ((sy1 -fsy1) * (sx1 -fsx1) * scale); if ((sy1 > fsy1) && (sx2 < fsx2)) out = out + src( (sy1 - 1) , sx2) * ((sy1 -fsy1) * (fsx2 -sx2) * scale); if ((sy2 < fsy2) && (sx2 < fsx2)) out = out + src(sy2, sx2) * ((fsy2 -sy2) * (fsx2 -sx2) * scale); if ((sy2 < fsy2) && (sx1 > fsx1)) out = out + src(sy2, (sx1 - 1)) * ((fsy2 -sy2) * (sx1 -fsx1) * scale); return saturate_cast(out); } Ptr2D src; float scale_x, scale_y; int width, haight; }; }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_FILTERS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/funcattrib.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP_ #define __OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP_ #include /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template void printFuncAttrib(Func& func) { cudaFuncAttributes attrs; cudaFuncGetAttributes(&attrs, func); printf("=== Function stats ===\n"); printf("Name: \n"); printf("sharedSizeBytes = %d\n", attrs.sharedSizeBytes); printf("constSizeBytes = %d\n", attrs.constSizeBytes); printf("localSizeBytes = %d\n", attrs.localSizeBytes); printf("maxThreadsPerBlock = %d\n", attrs.maxThreadsPerBlock); printf("numRegs = %d\n", attrs.numRegs); printf("ptxVersion = %d\n", attrs.ptxVersion); printf("binaryVersion = %d\n", attrs.binaryVersion); printf("\n"); fflush(stdout); } }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif /* __OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/functional.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_FUNCTIONAL_HPP__ #define __OPENCV_CUDA_FUNCTIONAL_HPP__ #include #include "saturate_cast.hpp" #include "vec_traits.hpp" #include "type_traits.hpp" #include "device_functions.h" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { // Function Objects template struct unary_function : public std::unary_function {}; template struct binary_function : public std::binary_function {}; // Arithmetic Operations template struct plus : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a + b; } __host__ __device__ __forceinline__ plus() {} __host__ __device__ __forceinline__ plus(const plus&) {} }; template struct minus : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a - b; } __host__ __device__ __forceinline__ minus() {} __host__ __device__ __forceinline__ minus(const minus&) {} }; template struct multiplies : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a * b; } __host__ __device__ __forceinline__ multiplies() {} __host__ __device__ __forceinline__ multiplies(const multiplies&) {} }; template struct divides : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a / b; } __host__ __device__ __forceinline__ divides() {} __host__ __device__ __forceinline__ divides(const divides&) {} }; template struct modulus : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a % b; } __host__ __device__ __forceinline__ modulus() {} __host__ __device__ __forceinline__ modulus(const modulus&) {} }; template struct negate : unary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a) const { return -a; } __host__ __device__ __forceinline__ negate() {} __host__ __device__ __forceinline__ negate(const negate&) {} }; // Comparison Operations template struct equal_to : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a == b; } __host__ __device__ __forceinline__ equal_to() {} __host__ __device__ __forceinline__ equal_to(const equal_to&) {} }; template struct not_equal_to : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a != b; } __host__ __device__ __forceinline__ not_equal_to() {} __host__ __device__ __forceinline__ not_equal_to(const not_equal_to&) {} }; template struct greater : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a > b; } __host__ __device__ __forceinline__ greater() {} __host__ __device__ __forceinline__ greater(const greater&) {} }; template struct less : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a < b; } __host__ __device__ __forceinline__ less() {} __host__ __device__ __forceinline__ less(const less&) {} }; template struct greater_equal : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a >= b; } __host__ __device__ __forceinline__ greater_equal() {} __host__ __device__ __forceinline__ greater_equal(const greater_equal&) {} }; template struct less_equal : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a <= b; } __host__ __device__ __forceinline__ less_equal() {} __host__ __device__ __forceinline__ less_equal(const less_equal&) {} }; // Logical Operations template struct logical_and : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a && b; } __host__ __device__ __forceinline__ logical_and() {} __host__ __device__ __forceinline__ logical_and(const logical_and&) {} }; template struct logical_or : binary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a || b; } __host__ __device__ __forceinline__ logical_or() {} __host__ __device__ __forceinline__ logical_or(const logical_or&) {} }; template struct logical_not : unary_function { __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a) const { return !a; } __host__ __device__ __forceinline__ logical_not() {} __host__ __device__ __forceinline__ logical_not(const logical_not&) {} }; // Bitwise Operations template struct bit_and : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a & b; } __host__ __device__ __forceinline__ bit_and() {} __host__ __device__ __forceinline__ bit_and(const bit_and&) {} }; template struct bit_or : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a | b; } __host__ __device__ __forceinline__ bit_or() {} __host__ __device__ __forceinline__ bit_or(const bit_or&) {} }; template struct bit_xor : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, typename TypeTraits::ParameterType b) const { return a ^ b; } __host__ __device__ __forceinline__ bit_xor() {} __host__ __device__ __forceinline__ bit_xor(const bit_xor&) {} }; template struct bit_not : unary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType v) const { return ~v; } __host__ __device__ __forceinline__ bit_not() {} __host__ __device__ __forceinline__ bit_not(const bit_not&) {} }; // Generalized Identity Operations template struct identity : unary_function { __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType x) const { return x; } __host__ __device__ __forceinline__ identity() {} __host__ __device__ __forceinline__ identity(const identity&) {} }; template struct project1st : binary_function { __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const { return lhs; } __host__ __device__ __forceinline__ project1st() {} __host__ __device__ __forceinline__ project1st(const project1st&) {} }; template struct project2nd : binary_function { __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const { return rhs; } __host__ __device__ __forceinline__ project2nd() {} __host__ __device__ __forceinline__ project2nd(const project2nd&) {} }; // Min/Max Operations #define OPENCV_CUDA_IMPLEMENT_MINMAX(name, type, op) \ template <> struct name : binary_function \ { \ __device__ __forceinline__ type operator()(type lhs, type rhs) const {return op(lhs, rhs);} \ __host__ __device__ __forceinline__ name() {}\ __host__ __device__ __forceinline__ name(const name&) {}\ }; template struct maximum : binary_function { __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const { return max(lhs, rhs); } __host__ __device__ __forceinline__ maximum() {} __host__ __device__ __forceinline__ maximum(const maximum&) {} }; OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uchar, ::max) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, schar, ::max) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, char, ::max) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, ushort, ::max) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, short, ::max) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, int, ::max) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uint, ::max) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, float, ::fmax) OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, double, ::fmax) template struct minimum : binary_function { __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const { return min(lhs, rhs); } __host__ __device__ __forceinline__ minimum() {} __host__ __device__ __forceinline__ minimum(const minimum&) {} }; OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uchar, ::min) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, schar, ::min) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, char, ::min) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, ushort, ::min) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, short, ::min) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, int, ::min) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uint, ::min) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, float, ::fmin) OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, double, ::fmin) #undef OPENCV_CUDA_IMPLEMENT_MINMAX // Math functions template struct abs_func : unary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType x) const { return abs(x); } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ unsigned char operator ()(unsigned char x) const { return x; } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ signed char operator ()(signed char x) const { return ::abs((int)x); } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ char operator ()(char x) const { return ::abs((int)x); } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ unsigned short operator ()(unsigned short x) const { return x; } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ short operator ()(short x) const { return ::abs((int)x); } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ unsigned int operator ()(unsigned int x) const { return x; } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ int operator ()(int x) const { return ::abs(x); } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ float operator ()(float x) const { return ::fabsf(x); } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; template <> struct abs_func : unary_function { __device__ __forceinline__ double operator ()(double x) const { return ::fabs(x); } __host__ __device__ __forceinline__ abs_func() {} __host__ __device__ __forceinline__ abs_func(const abs_func&) {} }; #define OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(name, func) \ template struct name ## _func : unary_function \ { \ __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v) const \ { \ return func ## f(v); \ } \ __host__ __device__ __forceinline__ name ## _func() {} \ __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ }; \ template <> struct name ## _func : unary_function \ { \ __device__ __forceinline__ double operator ()(double v) const \ { \ return func(v); \ } \ __host__ __device__ __forceinline__ name ## _func() {} \ __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ }; #define OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(name, func) \ template struct name ## _func : binary_function \ { \ __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v1, typename TypeTraits::ParameterType v2) const \ { \ return func ## f(v1, v2); \ } \ __host__ __device__ __forceinline__ name ## _func() {} \ __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ }; \ template <> struct name ## _func : binary_function \ { \ __device__ __forceinline__ double operator ()(double v1, double v2) const \ { \ return func(v1, v2); \ } \ __host__ __device__ __forceinline__ name ## _func() {} \ __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ }; OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sqrt, ::sqrt) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp, ::exp) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp2, ::exp2) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp10, ::exp10) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log, ::log) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log2, ::log2) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log10, ::log10) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sin, ::sin) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cos, ::cos) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tan, ::tan) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asin, ::asin) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acos, ::acos) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atan, ::atan) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sinh, ::sinh) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cosh, ::cosh) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tanh, ::tanh) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asinh, ::asinh) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acosh, ::acosh) OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atanh, ::atanh) OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(hypot, ::hypot) OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(atan2, ::atan2) OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(pow, ::pow) #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR_NO_DOUBLE #undef OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR template struct hypot_sqr_func : binary_function { __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType src1, typename TypeTraits::ParameterType src2) const { return src1 * src1 + src2 * src2; } __host__ __device__ __forceinline__ hypot_sqr_func() {} __host__ __device__ __forceinline__ hypot_sqr_func(const hypot_sqr_func&) {} }; // Saturate Cast Functor template struct saturate_cast_func : unary_function { __device__ __forceinline__ D operator ()(typename TypeTraits::ParameterType v) const { return saturate_cast(v); } __host__ __device__ __forceinline__ saturate_cast_func() {} __host__ __device__ __forceinline__ saturate_cast_func(const saturate_cast_func&) {} }; // Threshold Functors template struct thresh_binary_func : unary_function { __host__ __device__ __forceinline__ thresh_binary_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const { return (src > thresh) * maxVal; } __host__ __device__ __forceinline__ thresh_binary_func() {} __host__ __device__ __forceinline__ thresh_binary_func(const thresh_binary_func& other) : thresh(other.thresh), maxVal(other.maxVal) {} T thresh; T maxVal; }; template struct thresh_binary_inv_func : unary_function { __host__ __device__ __forceinline__ thresh_binary_inv_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const { return (src <= thresh) * maxVal; } __host__ __device__ __forceinline__ thresh_binary_inv_func() {} __host__ __device__ __forceinline__ thresh_binary_inv_func(const thresh_binary_inv_func& other) : thresh(other.thresh), maxVal(other.maxVal) {} T thresh; T maxVal; }; template struct thresh_trunc_func : unary_function { explicit __host__ __device__ __forceinline__ thresh_trunc_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {(void)maxVal_;} __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const { return minimum()(src, thresh); } __host__ __device__ __forceinline__ thresh_trunc_func() {} __host__ __device__ __forceinline__ thresh_trunc_func(const thresh_trunc_func& other) : thresh(other.thresh) {} T thresh; }; template struct thresh_to_zero_func : unary_function { explicit __host__ __device__ __forceinline__ thresh_to_zero_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {(void)maxVal_;} __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const { return (src > thresh) * src; } __host__ __device__ __forceinline__ thresh_to_zero_func() {} __host__ __device__ __forceinline__ thresh_to_zero_func(const thresh_to_zero_func& other) : thresh(other.thresh) {} T thresh; }; template struct thresh_to_zero_inv_func : unary_function { explicit __host__ __device__ __forceinline__ thresh_to_zero_inv_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {(void)maxVal_;} __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const { return (src <= thresh) * src; } __host__ __device__ __forceinline__ thresh_to_zero_inv_func() {} __host__ __device__ __forceinline__ thresh_to_zero_inv_func(const thresh_to_zero_inv_func& other) : thresh(other.thresh) {} T thresh; }; // Function Object Adaptors template struct unary_negate : unary_function { explicit __host__ __device__ __forceinline__ unary_negate(const Predicate& p) : pred(p) {} __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x) const { return !pred(x); } __host__ __device__ __forceinline__ unary_negate() {} __host__ __device__ __forceinline__ unary_negate(const unary_negate& other) : pred(other.pred) {} Predicate pred; }; template __host__ __device__ __forceinline__ unary_negate not1(const Predicate& pred) { return unary_negate(pred); } template struct binary_negate : binary_function { explicit __host__ __device__ __forceinline__ binary_negate(const Predicate& p) : pred(p) {} __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x, typename TypeTraits::ParameterType y) const { return !pred(x,y); } __host__ __device__ __forceinline__ binary_negate() {} __host__ __device__ __forceinline__ binary_negate(const binary_negate& other) : pred(other.pred) {} Predicate pred; }; template __host__ __device__ __forceinline__ binary_negate not2(const BinaryPredicate& pred) { return binary_negate(pred); } template struct binder1st : unary_function { __host__ __device__ __forceinline__ binder1st(const Op& op_, const typename Op::first_argument_type& arg1_) : op(op_), arg1(arg1_) {} __device__ __forceinline__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const { return op(arg1, a); } __host__ __device__ __forceinline__ binder1st() {} __host__ __device__ __forceinline__ binder1st(const binder1st& other) : op(other.op), arg1(other.arg1) {} Op op; typename Op::first_argument_type arg1; }; template __host__ __device__ __forceinline__ binder1st bind1st(const Op& op, const T& x) { return binder1st(op, typename Op::first_argument_type(x)); } template struct binder2nd : unary_function { __host__ __device__ __forceinline__ binder2nd(const Op& op_, const typename Op::second_argument_type& arg2_) : op(op_), arg2(arg2_) {} __forceinline__ __device__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const { return op(a, arg2); } __host__ __device__ __forceinline__ binder2nd() {} __host__ __device__ __forceinline__ binder2nd(const binder2nd& other) : op(other.op), arg2(other.arg2) {} Op op; typename Op::second_argument_type arg2; }; template __host__ __device__ __forceinline__ binder2nd bind2nd(const Op& op, const T& x) { return binder2nd(op, typename Op::second_argument_type(x)); } // Functor Traits template struct IsUnaryFunction { typedef char Yes; struct No {Yes a[2];}; template static Yes check(unary_function); static No check(...); static F makeF(); enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; }; template struct IsBinaryFunction { typedef char Yes; struct No {Yes a[2];}; template static Yes check(binary_function); static No check(...); static F makeF(); enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; }; namespace functional_detail { template struct UnOpShift { enum { shift = 1 }; }; template struct UnOpShift { enum { shift = 4 }; }; template struct UnOpShift { enum { shift = 2 }; }; template struct DefaultUnaryShift { enum { shift = UnOpShift::shift }; }; template struct BinOpShift { enum { shift = 1 }; }; template struct BinOpShift { enum { shift = 4 }; }; template struct BinOpShift { enum { shift = 2 }; }; template struct DefaultBinaryShift { enum { shift = BinOpShift::shift }; }; template ::value> struct ShiftDispatcher; template struct ShiftDispatcher { enum { shift = DefaultUnaryShift::shift }; }; template struct ShiftDispatcher { enum { shift = DefaultBinaryShift::shift }; }; } template struct DefaultTransformShift { enum { shift = functional_detail::ShiftDispatcher::shift }; }; template struct DefaultTransformFunctorTraits { enum { simple_block_dim_x = 16 }; enum { simple_block_dim_y = 16 }; enum { smart_block_dim_x = 16 }; enum { smart_block_dim_y = 16 }; enum { smart_shift = DefaultTransformShift::shift }; }; template struct TransformFunctorTraits : DefaultTransformFunctorTraits {}; #define OPENCV_CUDA_TRANSFORM_FUNCTOR_TRAITS(type) \ template <> struct TransformFunctorTraits< type > : DefaultTransformFunctorTraits< type > }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_FUNCTIONAL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/limits.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_LIMITS_HPP__ #define __OPENCV_CUDA_LIMITS_HPP__ #include #include #include "common.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template struct numeric_limits; template <> struct numeric_limits { __device__ __forceinline__ static bool min() { return false; } __device__ __forceinline__ static bool max() { return true; } static const bool is_signed = false; }; template <> struct numeric_limits { __device__ __forceinline__ static signed char min() { return SCHAR_MIN; } __device__ __forceinline__ static signed char max() { return SCHAR_MAX; } static const bool is_signed = true; }; template <> struct numeric_limits { __device__ __forceinline__ static unsigned char min() { return 0; } __device__ __forceinline__ static unsigned char max() { return UCHAR_MAX; } static const bool is_signed = false; }; template <> struct numeric_limits { __device__ __forceinline__ static short min() { return SHRT_MIN; } __device__ __forceinline__ static short max() { return SHRT_MAX; } static const bool is_signed = true; }; template <> struct numeric_limits { __device__ __forceinline__ static unsigned short min() { return 0; } __device__ __forceinline__ static unsigned short max() { return USHRT_MAX; } static const bool is_signed = false; }; template <> struct numeric_limits { __device__ __forceinline__ static int min() { return INT_MIN; } __device__ __forceinline__ static int max() { return INT_MAX; } static const bool is_signed = true; }; template <> struct numeric_limits { __device__ __forceinline__ static unsigned int min() { return 0; } __device__ __forceinline__ static unsigned int max() { return UINT_MAX; } static const bool is_signed = false; }; template <> struct numeric_limits { __device__ __forceinline__ static float min() { return FLT_MIN; } __device__ __forceinline__ static float max() { return FLT_MAX; } __device__ __forceinline__ static float epsilon() { return FLT_EPSILON; } static const bool is_signed = true; }; template <> struct numeric_limits { __device__ __forceinline__ static double min() { return DBL_MIN; } __device__ __forceinline__ static double max() { return DBL_MAX; } __device__ __forceinline__ static double epsilon() { return DBL_EPSILON; } static const bool is_signed = true; }; }}} // namespace cv { namespace cuda { namespace cudev { //! @endcond #endif // __OPENCV_CUDA_LIMITS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/reduce.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_REDUCE_HPP__ #define __OPENCV_CUDA_REDUCE_HPP__ #include #include "detail/reduce.hpp" #include "detail/reduce_key_val.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template __device__ __forceinline__ void reduce(volatile T* smem, T& val, unsigned int tid, const Op& op) { reduce_detail::Dispatcher::reductor::template reduce(smem, val, tid, op); } template __device__ __forceinline__ void reduce(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, const thrust::tuple& op) { reduce_detail::Dispatcher::reductor::template reduce< const thrust::tuple&, const thrust::tuple&, const thrust::tuple&>(smem, val, tid, op); } template __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, volatile V* svals, V& val, unsigned int tid, const Cmp& cmp) { reduce_key_val_detail::Dispatcher::reductor::template reduce(skeys, key, svals, val, tid, cmp); } template __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const Cmp& cmp) { reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const Cmp&>(skeys, key, svals, val, tid, cmp); } template __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, const thrust::tuple& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const thrust::tuple& cmp) { reduce_key_val_detail::Dispatcher::reductor::template reduce< const thrust::tuple&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple& >(skeys, key, svals, val, tid, cmp); } // smem_tuple template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0) { return thrust::make_tuple((volatile T0*) t0); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8); } template __device__ __forceinline__ thrust::tuple smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8, T9* t9) { return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8, (volatile T9*) t9); } }}} //! @endcond #endif // __OPENCV_CUDA_UTILITY_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/saturate_cast.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_SATURATE_CAST_HPP__ #define __OPENCV_CUDA_SATURATE_CAST_HPP__ #include "common.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template __device__ __forceinline__ _Tp saturate_cast(uchar v) { return _Tp(v); } template __device__ __forceinline__ _Tp saturate_cast(schar v) { return _Tp(v); } template __device__ __forceinline__ _Tp saturate_cast(ushort v) { return _Tp(v); } template __device__ __forceinline__ _Tp saturate_cast(short v) { return _Tp(v); } template __device__ __forceinline__ _Tp saturate_cast(uint v) { return _Tp(v); } template __device__ __forceinline__ _Tp saturate_cast(int v) { return _Tp(v); } template __device__ __forceinline__ _Tp saturate_cast(float v) { return _Tp(v); } template __device__ __forceinline__ _Tp saturate_cast(double v) { return _Tp(v); } template<> __device__ __forceinline__ uchar saturate_cast(schar v) { uint res = 0; int vi = v; asm("cvt.sat.u8.s8 %0, %1;" : "=r"(res) : "r"(vi)); return res; } template<> __device__ __forceinline__ uchar saturate_cast(short v) { uint res = 0; asm("cvt.sat.u8.s16 %0, %1;" : "=r"(res) : "h"(v)); return res; } template<> __device__ __forceinline__ uchar saturate_cast(ushort v) { uint res = 0; asm("cvt.sat.u8.u16 %0, %1;" : "=r"(res) : "h"(v)); return res; } template<> __device__ __forceinline__ uchar saturate_cast(int v) { uint res = 0; asm("cvt.sat.u8.s32 %0, %1;" : "=r"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ uchar saturate_cast(uint v) { uint res = 0; asm("cvt.sat.u8.u32 %0, %1;" : "=r"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ uchar saturate_cast(float v) { uint res = 0; asm("cvt.rni.sat.u8.f32 %0, %1;" : "=r"(res) : "f"(v)); return res; } template<> __device__ __forceinline__ uchar saturate_cast(double v) { #if __CUDA_ARCH__ >= 130 uint res = 0; asm("cvt.rni.sat.u8.f64 %0, %1;" : "=r"(res) : "d"(v)); return res; #else return saturate_cast((float)v); #endif } template<> __device__ __forceinline__ schar saturate_cast(uchar v) { uint res = 0; uint vi = v; asm("cvt.sat.s8.u8 %0, %1;" : "=r"(res) : "r"(vi)); return res; } template<> __device__ __forceinline__ schar saturate_cast(short v) { uint res = 0; asm("cvt.sat.s8.s16 %0, %1;" : "=r"(res) : "h"(v)); return res; } template<> __device__ __forceinline__ schar saturate_cast(ushort v) { uint res = 0; asm("cvt.sat.s8.u16 %0, %1;" : "=r"(res) : "h"(v)); return res; } template<> __device__ __forceinline__ schar saturate_cast(int v) { uint res = 0; asm("cvt.sat.s8.s32 %0, %1;" : "=r"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ schar saturate_cast(uint v) { uint res = 0; asm("cvt.sat.s8.u32 %0, %1;" : "=r"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ schar saturate_cast(float v) { uint res = 0; asm("cvt.rni.sat.s8.f32 %0, %1;" : "=r"(res) : "f"(v)); return res; } template<> __device__ __forceinline__ schar saturate_cast(double v) { #if __CUDA_ARCH__ >= 130 uint res = 0; asm("cvt.rni.sat.s8.f64 %0, %1;" : "=r"(res) : "d"(v)); return res; #else return saturate_cast((float)v); #endif } template<> __device__ __forceinline__ ushort saturate_cast(schar v) { ushort res = 0; int vi = v; asm("cvt.sat.u16.s8 %0, %1;" : "=h"(res) : "r"(vi)); return res; } template<> __device__ __forceinline__ ushort saturate_cast(short v) { ushort res = 0; asm("cvt.sat.u16.s16 %0, %1;" : "=h"(res) : "h"(v)); return res; } template<> __device__ __forceinline__ ushort saturate_cast(int v) { ushort res = 0; asm("cvt.sat.u16.s32 %0, %1;" : "=h"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ ushort saturate_cast(uint v) { ushort res = 0; asm("cvt.sat.u16.u32 %0, %1;" : "=h"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ ushort saturate_cast(float v) { ushort res = 0; asm("cvt.rni.sat.u16.f32 %0, %1;" : "=h"(res) : "f"(v)); return res; } template<> __device__ __forceinline__ ushort saturate_cast(double v) { #if __CUDA_ARCH__ >= 130 ushort res = 0; asm("cvt.rni.sat.u16.f64 %0, %1;" : "=h"(res) : "d"(v)); return res; #else return saturate_cast((float)v); #endif } template<> __device__ __forceinline__ short saturate_cast(ushort v) { short res = 0; asm("cvt.sat.s16.u16 %0, %1;" : "=h"(res) : "h"(v)); return res; } template<> __device__ __forceinline__ short saturate_cast(int v) { short res = 0; asm("cvt.sat.s16.s32 %0, %1;" : "=h"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ short saturate_cast(uint v) { short res = 0; asm("cvt.sat.s16.u32 %0, %1;" : "=h"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ short saturate_cast(float v) { short res = 0; asm("cvt.rni.sat.s16.f32 %0, %1;" : "=h"(res) : "f"(v)); return res; } template<> __device__ __forceinline__ short saturate_cast(double v) { #if __CUDA_ARCH__ >= 130 short res = 0; asm("cvt.rni.sat.s16.f64 %0, %1;" : "=h"(res) : "d"(v)); return res; #else return saturate_cast((float)v); #endif } template<> __device__ __forceinline__ int saturate_cast(uint v) { int res = 0; asm("cvt.sat.s32.u32 %0, %1;" : "=r"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ int saturate_cast(float v) { return __float2int_rn(v); } template<> __device__ __forceinline__ int saturate_cast(double v) { #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 return __double2int_rn(v); #else return saturate_cast((float)v); #endif } template<> __device__ __forceinline__ uint saturate_cast(schar v) { uint res = 0; int vi = v; asm("cvt.sat.u32.s8 %0, %1;" : "=r"(res) : "r"(vi)); return res; } template<> __device__ __forceinline__ uint saturate_cast(short v) { uint res = 0; asm("cvt.sat.u32.s16 %0, %1;" : "=r"(res) : "h"(v)); return res; } template<> __device__ __forceinline__ uint saturate_cast(int v) { uint res = 0; asm("cvt.sat.u32.s32 %0, %1;" : "=r"(res) : "r"(v)); return res; } template<> __device__ __forceinline__ uint saturate_cast(float v) { return __float2uint_rn(v); } template<> __device__ __forceinline__ uint saturate_cast(double v) { #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 return __double2uint_rn(v); #else return saturate_cast((float)v); #endif } }}} //! @endcond #endif /* __OPENCV_CUDA_SATURATE_CAST_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/scan.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_SCAN_HPP__ #define __OPENCV_CUDA_SCAN_HPP__ #include "opencv2/core/cuda/common.hpp" #include "opencv2/core/cuda/utility.hpp" #include "opencv2/core/cuda/warp.hpp" #include "opencv2/core/cuda/warp_shuffle.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { enum ScanKind { EXCLUSIVE = 0, INCLUSIVE = 1 }; template struct WarpScan { __device__ __forceinline__ WarpScan() {} __device__ __forceinline__ WarpScan(const WarpScan& other) { (void)other; } __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) { const unsigned int lane = idx & 31; F op; if ( lane >= 1) ptr [idx ] = op(ptr [idx - 1], ptr [idx]); if ( lane >= 2) ptr [idx ] = op(ptr [idx - 2], ptr [idx]); if ( lane >= 4) ptr [idx ] = op(ptr [idx - 4], ptr [idx]); if ( lane >= 8) ptr [idx ] = op(ptr [idx - 8], ptr [idx]); if ( lane >= 16) ptr [idx ] = op(ptr [idx - 16], ptr [idx]); if( Kind == INCLUSIVE ) return ptr [idx]; else return (lane > 0) ? ptr [idx - 1] : 0; } __device__ __forceinline__ unsigned int index(const unsigned int tid) { return tid; } __device__ __forceinline__ void init(volatile T *ptr){} static const int warp_offset = 0; typedef WarpScan merge; }; template struct WarpScanNoComp { __device__ __forceinline__ WarpScanNoComp() {} __device__ __forceinline__ WarpScanNoComp(const WarpScanNoComp& other) { (void)other; } __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) { const unsigned int lane = threadIdx.x & 31; F op; ptr [idx ] = op(ptr [idx - 1], ptr [idx]); ptr [idx ] = op(ptr [idx - 2], ptr [idx]); ptr [idx ] = op(ptr [idx - 4], ptr [idx]); ptr [idx ] = op(ptr [idx - 8], ptr [idx]); ptr [idx ] = op(ptr [idx - 16], ptr [idx]); if( Kind == INCLUSIVE ) return ptr [idx]; else return (lane > 0) ? ptr [idx - 1] : 0; } __device__ __forceinline__ unsigned int index(const unsigned int tid) { return (tid >> warp_log) * warp_smem_stride + 16 + (tid & warp_mask); } __device__ __forceinline__ void init(volatile T *ptr) { ptr[threadIdx.x] = 0; } static const int warp_smem_stride = 32 + 16 + 1; static const int warp_offset = 16; static const int warp_log = 5; static const int warp_mask = 31; typedef WarpScanNoComp merge; }; template struct BlockScan { __device__ __forceinline__ BlockScan() {} __device__ __forceinline__ BlockScan(const BlockScan& other) { (void)other; } __device__ __forceinline__ T operator()(volatile T *ptr) { const unsigned int tid = threadIdx.x; const unsigned int lane = tid & warp_mask; const unsigned int warp = tid >> warp_log; Sc scan; typename Sc::merge merge_scan; const unsigned int idx = scan.index(tid); T val = scan(ptr, idx); __syncthreads (); if( warp == 0) scan.init(ptr); __syncthreads (); if( lane == 31 ) ptr [scan.warp_offset + warp ] = (Kind == INCLUSIVE) ? val : ptr [idx]; __syncthreads (); if( warp == 0 ) merge_scan(ptr, idx); __syncthreads(); if ( warp > 0) val = ptr [scan.warp_offset + warp - 1] + val; __syncthreads (); ptr[idx] = val; __syncthreads (); return val ; } static const int warp_log = 5; static const int warp_mask = 31; }; template __device__ T warpScanInclusive(T idata, volatile T* s_Data, unsigned int tid) { #if __CUDA_ARCH__ >= 300 const unsigned int laneId = cv::cuda::device::Warp::laneId(); // scan on shuffl functions #pragma unroll for (int i = 1; i <= (OPENCV_CUDA_WARP_SIZE / 2); i *= 2) { const T n = cv::cuda::device::shfl_up(idata, i); if (laneId >= i) idata += n; } return idata; #else unsigned int pos = 2 * tid - (tid & (OPENCV_CUDA_WARP_SIZE - 1)); s_Data[pos] = 0; pos += OPENCV_CUDA_WARP_SIZE; s_Data[pos] = idata; s_Data[pos] += s_Data[pos - 1]; s_Data[pos] += s_Data[pos - 2]; s_Data[pos] += s_Data[pos - 4]; s_Data[pos] += s_Data[pos - 8]; s_Data[pos] += s_Data[pos - 16]; return s_Data[pos]; #endif } template __device__ __forceinline__ T warpScanExclusive(T idata, volatile T* s_Data, unsigned int tid) { return warpScanInclusive(idata, s_Data, tid) - idata; } template __device__ T blockScanInclusive(T idata, volatile T* s_Data, unsigned int tid) { if (tiNumScanThreads > OPENCV_CUDA_WARP_SIZE) { //Bottom-level inclusive warp scan T warpResult = warpScanInclusive(idata, s_Data, tid); //Save top elements of each warp for exclusive warp scan //sync to wait for warp scans to complete (because s_Data is being overwritten) __syncthreads(); if ((tid & (OPENCV_CUDA_WARP_SIZE - 1)) == (OPENCV_CUDA_WARP_SIZE - 1)) { s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE] = warpResult; } //wait for warp scans to complete __syncthreads(); if (tid < (tiNumScanThreads / OPENCV_CUDA_WARP_SIZE) ) { //grab top warp elements T val = s_Data[tid]; //calculate exclusive scan and write back to shared memory s_Data[tid] = warpScanExclusive(val, s_Data, tid); } //return updated warp scans with exclusive scan results __syncthreads(); return warpResult + s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE]; } else { return warpScanInclusive(idata, s_Data, tid); } } }}} //! @endcond #endif // __OPENCV_CUDA_SCAN_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/simd_functions.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ /* * Copyright (c) 2013 NVIDIA Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of NVIDIA Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __OPENCV_CUDA_SIMD_FUNCTIONS_HPP__ #define __OPENCV_CUDA_SIMD_FUNCTIONS_HPP__ #include "common.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { // 2 static __device__ __forceinline__ unsigned int vadd2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vadd2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vadd.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vadd.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s; s = a ^ b; // sum bits r = a + b; // actual sum s = s ^ r; // determine carry-ins for each bit position s = s & 0x00010000; // carry-in to high word (= carry-out from low word) r = r - s; // subtract out carry-out from low word #endif return r; } static __device__ __forceinline__ unsigned int vsub2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vsub2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vsub.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vsub.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s; s = a ^ b; // sum bits r = a - b; // actual sum s = s ^ r; // determine carry-ins for each bit position s = s & 0x00010000; // borrow to high word r = r + s; // compensate for borrow from low word #endif return r; } static __device__ __forceinline__ unsigned int vabsdiff2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vabsdiff2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vabsdiff.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vabsdiff.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s, t, u, v; s = a & 0x0000ffff; // extract low halfword r = b & 0x0000ffff; // extract low halfword u = ::max(r, s); // maximum of low halfwords v = ::min(r, s); // minimum of low halfwords s = a & 0xffff0000; // extract high halfword r = b & 0xffff0000; // extract high halfword t = ::max(r, s); // maximum of high halfwords s = ::min(r, s); // minimum of high halfwords r = u | t; // maximum of both halfwords s = v | s; // minimum of both halfwords r = r - s; // |a - b| = max(a,b) - min(a,b); #endif return r; } static __device__ __forceinline__ unsigned int vavg2(unsigned int a, unsigned int b) { unsigned int r, s; // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) s = a ^ b; r = a & b; s = s & 0xfffefffe; // ensure shift doesn't cross halfword boundaries s = s >> 1; s = r + s; return s; } static __device__ __forceinline__ unsigned int vavrg2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vavrg2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) unsigned int s; s = a ^ b; r = a | b; s = s & 0xfffefffe; // ensure shift doesn't cross half-word boundaries s = s >> 1; r = r - s; #endif return r; } static __device__ __forceinline__ unsigned int vseteq2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset2.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) unsigned int c; r = a ^ b; // 0x0000 if a == b c = r | 0x80008000; // set msbs, to catch carry out r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 c = r & ~c; // msb = 1, if r was 0x0000 r = c >> 15; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpeq2(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vseteq2(a, b); c = r << 16; // convert bool r = c - r; // into mask #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) r = a ^ b; // 0x0000 if a == b c = r | 0x80008000; // set msbs, to catch carry out r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 c = r & ~c; // msb = 1, if r was 0x0000 r = c >> 15; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetge2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset2.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(b)); c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 c = c & 0x80008000; // msb = carry-outs r = c >> 15; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpge2(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetge2(a, b); c = r << 16; // convert bool r = c - r; // into mask #else asm("not.b32 %0, %0;" : "+r"(b)); c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 c = c & 0x80008000; // msb = carry-outs r = c >> 15; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetgt2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset2.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(b)); c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] c = c & 0x80008000; // msbs = carry-outs r = c >> 15; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpgt2(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetgt2(a, b); c = r << 16; // convert bool r = c - r; // into mask #else asm("not.b32 %0, %0;" : "+r"(b)); c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] c = c & 0x80008000; // msbs = carry-outs r = c >> 15; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetle2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset2.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(a)); c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 c = c & 0x80008000; // msb = carry-outs r = c >> 15; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmple2(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetle2(a, b); c = r << 16; // convert bool r = c - r; // into mask #else asm("not.b32 %0, %0;" : "+r"(a)); c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 c = c & 0x80008000; // msb = carry-outs r = c >> 15; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetlt2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset2.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(a)); c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] c = c & 0x80008000; // msb = carry-outs r = c >> 15; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmplt2(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetlt2(a, b); c = r << 16; // convert bool r = c - r; // into mask #else asm("not.b32 %0, %0;" : "+r"(a)); c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] c = c & 0x80008000; // msb = carry-outs r = c >> 15; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetne2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm ("vset2.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) unsigned int c; r = a ^ b; // 0x0000 if a == b c = r | 0x80008000; // set msbs, to catch carry out c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 c = r | c; // msb = 1, if r was not 0x0000 c = c & 0x80008000; // extract msbs r = c >> 15; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpne2(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetne2(a, b); c = r << 16; // convert bool r = c - r; // into mask #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) r = a ^ b; // 0x0000 if a == b c = r | 0x80008000; // set msbs, to catch carry out c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 c = r | c; // msb = 1, if r was not 0x0000 c = c & 0x80008000; // extract msbs r = c >> 15; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vmax2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vmax2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vmax.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmax.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s, t, u; r = a & 0x0000ffff; // extract low halfword s = b & 0x0000ffff; // extract low halfword t = ::max(r, s); // maximum of low halfwords r = a & 0xffff0000; // extract high halfword s = b & 0xffff0000; // extract high halfword u = ::max(r, s); // maximum of high halfwords r = t | u; // combine halfword maximums #endif return r; } static __device__ __forceinline__ unsigned int vmin2(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vmin2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vmin.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmin.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s, t, u; r = a & 0x0000ffff; // extract low halfword s = b & 0x0000ffff; // extract low halfword t = ::min(r, s); // minimum of low halfwords r = a & 0xffff0000; // extract high halfword s = b & 0xffff0000; // extract high halfword u = ::min(r, s); // minimum of high halfwords r = t | u; // combine halfword minimums #endif return r; } // 4 static __device__ __forceinline__ unsigned int vadd4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vadd4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vadd.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vadd.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vadd.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vadd.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s, t; s = a ^ b; // sum bits r = a & 0x7f7f7f7f; // clear msbs t = b & 0x7f7f7f7f; // clear msbs s = s & 0x80808080; // msb sum bits r = r + t; // add without msbs, record carry-out in msbs r = r ^ s; // sum of msb sum and carry-in bits, w/o carry-out #endif /* __CUDA_ARCH__ >= 300 */ return r; } static __device__ __forceinline__ unsigned int vsub4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vsub4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vsub.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vsub.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vsub.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vsub.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s, t; s = a ^ ~b; // inverted sum bits r = a | 0x80808080; // set msbs t = b & 0x7f7f7f7f; // clear msbs s = s & 0x80808080; // inverted msb sum bits r = r - t; // subtract w/o msbs, record inverted borrows in msb r = r ^ s; // combine inverted msb sum bits and borrows #endif return r; } static __device__ __forceinline__ unsigned int vavg4(unsigned int a, unsigned int b) { unsigned int r, s; // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) s = a ^ b; r = a & b; s = s & 0xfefefefe; // ensure following shift doesn't cross byte boundaries s = s >> 1; s = r + s; return s; } static __device__ __forceinline__ unsigned int vavrg4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vavrg4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) unsigned int c; c = a ^ b; r = a | b; c = c & 0xfefefefe; // ensure following shift doesn't cross byte boundaries c = c >> 1; r = r - c; #endif return r; } static __device__ __forceinline__ unsigned int vseteq4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset4.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) unsigned int c; r = a ^ b; // 0x00 if a == b c = r | 0x80808080; // set msbs, to catch carry out r = r ^ c; // extract msbs, msb = 1 if r < 0x80 c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 c = r & ~c; // msb = 1, if r was 0x00 r = c >> 7; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpeq4(unsigned int a, unsigned int b) { unsigned int r, t; #if __CUDA_ARCH__ >= 300 r = vseteq4(a, b); t = r << 8; // convert bool r = t - r; // to mask #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) t = a ^ b; // 0x00 if a == b r = t | 0x80808080; // set msbs, to catch carry out t = t ^ r; // extract msbs, msb = 1 if t < 0x80 r = r - 0x01010101; // msb = 0, if t was 0x00 or 0x80 r = t & ~r; // msb = 1, if t was 0x00 t = r >> 7; // build mask t = r - t; // from r = t | r; // msbs #endif return r; } static __device__ __forceinline__ unsigned int vsetle4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset4.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(a)); c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 c = c & 0x80808080; // msb = carry-outs r = c >> 7; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmple4(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetle4(a, b); c = r << 8; // convert bool r = c - r; // to mask #else asm("not.b32 %0, %0;" : "+r"(a)); c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 c = c & 0x80808080; // msbs = carry-outs r = c >> 7; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetlt4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset4.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(a)); c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] c = c & 0x80808080; // msb = carry-outs r = c >> 7; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmplt4(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetlt4(a, b); c = r << 8; // convert bool r = c - r; // to mask #else asm("not.b32 %0, %0;" : "+r"(a)); c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] c = c & 0x80808080; // msbs = carry-outs r = c >> 7; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetge4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset4.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(b)); c = vavrg4(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 c = c & 0x80808080; // msb = carry-outs r = c >> 7; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpge4(unsigned int a, unsigned int b) { unsigned int r, s; #if __CUDA_ARCH__ >= 300 r = vsetge4(a, b); s = r << 8; // convert bool r = s - r; // to mask #else asm ("not.b32 %0,%0;" : "+r"(b)); r = vavrg4 (a, b); // (a + ~b + 1) / 2 = (a - b) / 2 r = r & 0x80808080; // msb = carry-outs s = r >> 7; // build mask s = r - s; // from r = s | r; // msbs #endif return r; } static __device__ __forceinline__ unsigned int vsetgt4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset4.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int c; asm("not.b32 %0, %0;" : "+r"(b)); c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] c = c & 0x80808080; // msb = carry-outs r = c >> 7; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpgt4(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetgt4(a, b); c = r << 8; // convert bool r = c - r; // to mask #else asm("not.b32 %0, %0;" : "+r"(b)); c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] c = c & 0x80808080; // msb = carry-outs r = c >> 7; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vsetne4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vset4.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) unsigned int c; r = a ^ b; // 0x00 if a == b c = r | 0x80808080; // set msbs, to catch carry out c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 c = r | c; // msb = 1, if r was not 0x00 c = c & 0x80808080; // extract msbs r = c >> 7; // convert to bool #endif return r; } static __device__ __forceinline__ unsigned int vcmpne4(unsigned int a, unsigned int b) { unsigned int r, c; #if __CUDA_ARCH__ >= 300 r = vsetne4(a, b); c = r << 8; // convert bool r = c - r; // to mask #else // inspired by Alan Mycroft's null-byte detection algorithm: // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) r = a ^ b; // 0x00 if a == b c = r | 0x80808080; // set msbs, to catch carry out c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 c = r | c; // msb = 1, if r was not 0x00 c = c & 0x80808080; // extract msbs r = c >> 7; // convert r = c - r; // msbs to r = c | r; // mask #endif return r; } static __device__ __forceinline__ unsigned int vabsdiff4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vabsdiff4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vabsdiff.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vabsdiff.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vabsdiff.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vabsdiff.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s; s = vcmpge4(a, b); // mask = 0xff if a >= b r = a ^ b; // s = (r & s) ^ b; // select a when a >= b, else select b => max(a,b) r = s ^ r; // select a when b >= a, else select b => min(a,b) r = s - r; // |a - b| = max(a,b) - min(a,b); #endif return r; } static __device__ __forceinline__ unsigned int vmax4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vmax4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vmax.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmax.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmax.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmax.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s; s = vcmpge4(a, b); // mask = 0xff if a >= b r = a & s; // select a when b >= a s = b & ~s; // select b when b < a r = r | s; // combine byte selections #endif return r; // byte-wise unsigned maximum } static __device__ __forceinline__ unsigned int vmin4(unsigned int a, unsigned int b) { unsigned int r = 0; #if __CUDA_ARCH__ >= 300 asm("vmin4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #elif __CUDA_ARCH__ >= 200 asm("vmin.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmin.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmin.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); asm("vmin.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); #else unsigned int s; s = vcmpge4(b, a); // mask = 0xff if a >= b r = a & s; // select a when b >= a s = b & ~s; // select b when b < a r = r | s; // combine byte selections #endif return r; } }}} //! @endcond #endif // __OPENCV_CUDA_SIMD_FUNCTIONS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/transform.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_TRANSFORM_HPP__ #define __OPENCV_CUDA_TRANSFORM_HPP__ #include "common.hpp" #include "utility.hpp" #include "detail/transform_detail.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template static inline void transform(PtrStepSz src, PtrStepSz dst, UnOp op, const Mask& mask, cudaStream_t stream) { typedef TransformFunctorTraits ft; transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src, dst, op, mask, stream); } template static inline void transform(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, const Mask& mask, cudaStream_t stream) { typedef TransformFunctorTraits ft; transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src1, src2, dst, op, mask, stream); } }}} //! @endcond #endif // __OPENCV_CUDA_TRANSFORM_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/type_traits.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_TYPE_TRAITS_HPP__ #define __OPENCV_CUDA_TYPE_TRAITS_HPP__ #include "detail/type_traits_detail.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template struct IsSimpleParameter { enum {value = type_traits_detail::IsIntegral::value || type_traits_detail::IsFloat::value || type_traits_detail::PointerTraits::type>::value}; }; template struct TypeTraits { typedef typename type_traits_detail::UnConst::type NonConstType; typedef typename type_traits_detail::UnVolatile::type NonVolatileType; typedef typename type_traits_detail::UnVolatile::type>::type UnqualifiedType; typedef typename type_traits_detail::PointerTraits::type PointeeType; typedef typename type_traits_detail::ReferenceTraits::type ReferredType; enum { isConst = type_traits_detail::UnConst::value }; enum { isVolatile = type_traits_detail::UnVolatile::value }; enum { isReference = type_traits_detail::ReferenceTraits::value }; enum { isPointer = type_traits_detail::PointerTraits::type>::value }; enum { isUnsignedInt = type_traits_detail::IsUnsignedIntegral::value }; enum { isSignedInt = type_traits_detail::IsSignedIntergral::value }; enum { isIntegral = type_traits_detail::IsIntegral::value }; enum { isFloat = type_traits_detail::IsFloat::value }; enum { isArith = isIntegral || isFloat }; enum { isVec = type_traits_detail::IsVec::value }; typedef typename type_traits_detail::Select::value, T, typename type_traits_detail::AddParameterType::type>::type ParameterType; }; }}} //! @endcond #endif // __OPENCV_CUDA_TYPE_TRAITS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/utility.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_UTILITY_HPP__ #define __OPENCV_CUDA_UTILITY_HPP__ #include "saturate_cast.hpp" #include "datamov_utils.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { #define OPENCV_CUDA_LOG_WARP_SIZE (5) #define OPENCV_CUDA_WARP_SIZE (1 << OPENCV_CUDA_LOG_WARP_SIZE) #define OPENCV_CUDA_LOG_MEM_BANKS ((__CUDA_ARCH__ >= 200) ? 5 : 4) // 32 banks on fermi, 16 on tesla #define OPENCV_CUDA_MEM_BANKS (1 << OPENCV_CUDA_LOG_MEM_BANKS) /////////////////////////////////////////////////////////////////////////////// // swap template void __device__ __host__ __forceinline__ swap(T& a, T& b) { const T temp = a; a = b; b = temp; } /////////////////////////////////////////////////////////////////////////////// // Mask Reader struct SingleMask { explicit __host__ __device__ __forceinline__ SingleMask(PtrStepb mask_) : mask(mask_) {} __host__ __device__ __forceinline__ SingleMask(const SingleMask& mask_): mask(mask_.mask){} __device__ __forceinline__ bool operator()(int y, int x) const { return mask.ptr(y)[x] != 0; } PtrStepb mask; }; struct SingleMaskChannels { __host__ __device__ __forceinline__ SingleMaskChannels(PtrStepb mask_, int channels_) : mask(mask_), channels(channels_) {} __host__ __device__ __forceinline__ SingleMaskChannels(const SingleMaskChannels& mask_) :mask(mask_.mask), channels(mask_.channels){} __device__ __forceinline__ bool operator()(int y, int x) const { return mask.ptr(y)[x / channels] != 0; } PtrStepb mask; int channels; }; struct MaskCollection { explicit __host__ __device__ __forceinline__ MaskCollection(PtrStepb* maskCollection_) : maskCollection(maskCollection_) {} __device__ __forceinline__ MaskCollection(const MaskCollection& masks_) : maskCollection(masks_.maskCollection), curMask(masks_.curMask){} __device__ __forceinline__ void next() { curMask = *maskCollection++; } __device__ __forceinline__ void setMask(int z) { curMask = maskCollection[z]; } __device__ __forceinline__ bool operator()(int y, int x) const { uchar val; return curMask.data == 0 || (ForceGlob::Load(curMask.ptr(y), x, val), (val != 0)); } const PtrStepb* maskCollection; PtrStepb curMask; }; struct WithOutMask { __host__ __device__ __forceinline__ WithOutMask(){} __host__ __device__ __forceinline__ WithOutMask(const WithOutMask&){} __device__ __forceinline__ void next() const { } __device__ __forceinline__ void setMask(int) const { } __device__ __forceinline__ bool operator()(int, int) const { return true; } __device__ __forceinline__ bool operator()(int, int, int) const { return true; } static __device__ __forceinline__ bool check(int, int) { return true; } static __device__ __forceinline__ bool check(int, int, int) { return true; } }; /////////////////////////////////////////////////////////////////////////////// // Solve linear system // solve 2x2 linear system Ax=b template __device__ __forceinline__ bool solve2x2(const T A[2][2], const T b[2], T x[2]) { T det = A[0][0] * A[1][1] - A[1][0] * A[0][1]; if (det != 0) { double invdet = 1.0 / det; x[0] = saturate_cast(invdet * (b[0] * A[1][1] - b[1] * A[0][1])); x[1] = saturate_cast(invdet * (A[0][0] * b[1] - A[1][0] * b[0])); return true; } return false; } // solve 3x3 linear system Ax=b template __device__ __forceinline__ bool solve3x3(const T A[3][3], const T b[3], T x[3]) { T det = A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]); if (det != 0) { double invdet = 1.0 / det; x[0] = saturate_cast(invdet * (b[0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - A[0][1] * (b[1] * A[2][2] - A[1][2] * b[2] ) + A[0][2] * (b[1] * A[2][1] - A[1][1] * b[2] ))); x[1] = saturate_cast(invdet * (A[0][0] * (b[1] * A[2][2] - A[1][2] * b[2] ) - b[0] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + A[0][2] * (A[1][0] * b[2] - b[1] * A[2][0]))); x[2] = saturate_cast(invdet * (A[0][0] * (A[1][1] * b[2] - b[1] * A[2][1]) - A[0][1] * (A[1][0] * b[2] - b[1] * A[2][0]) + b[0] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))); return true; } return false; } }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_UTILITY_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/vec_distance.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_VEC_DISTANCE_HPP__ #define __OPENCV_CUDA_VEC_DISTANCE_HPP__ #include "reduce.hpp" #include "functional.hpp" #include "detail/vec_distance_detail.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template struct L1Dist { typedef int value_type; typedef int result_type; __device__ __forceinline__ L1Dist() : mySum(0) {} __device__ __forceinline__ void reduceIter(int val1, int val2) { mySum = __sad(val1, val2, mySum); } template __device__ __forceinline__ void reduceAll(int* smem, int tid) { reduce(smem, mySum, tid, plus()); } __device__ __forceinline__ operator int() const { return mySum; } int mySum; }; template <> struct L1Dist { typedef float value_type; typedef float result_type; __device__ __forceinline__ L1Dist() : mySum(0.0f) {} __device__ __forceinline__ void reduceIter(float val1, float val2) { mySum += ::fabs(val1 - val2); } template __device__ __forceinline__ void reduceAll(float* smem, int tid) { reduce(smem, mySum, tid, plus()); } __device__ __forceinline__ operator float() const { return mySum; } float mySum; }; struct L2Dist { typedef float value_type; typedef float result_type; __device__ __forceinline__ L2Dist() : mySum(0.0f) {} __device__ __forceinline__ void reduceIter(float val1, float val2) { float reg = val1 - val2; mySum += reg * reg; } template __device__ __forceinline__ void reduceAll(float* smem, int tid) { reduce(smem, mySum, tid, plus()); } __device__ __forceinline__ operator float() const { return sqrtf(mySum); } float mySum; }; struct HammingDist { typedef int value_type; typedef int result_type; __device__ __forceinline__ HammingDist() : mySum(0) {} __device__ __forceinline__ void reduceIter(int val1, int val2) { mySum += __popc(val1 ^ val2); } template __device__ __forceinline__ void reduceAll(int* smem, int tid) { reduce(smem, mySum, tid, plus()); } __device__ __forceinline__ operator int() const { return mySum; } int mySum; }; // calc distance between two vectors in global memory template __device__ void calcVecDiffGlobal(const T1* vec1, const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) { for (int i = tid; i < len; i += THREAD_DIM) { T1 val1; ForceGlob::Load(vec1, i, val1); T2 val2; ForceGlob::Load(vec2, i, val2); dist.reduceIter(val1, val2); } dist.reduceAll(smem, tid); } // calc distance between two vectors, first vector is cached in register or shared memory, second vector is in global memory template __device__ __forceinline__ void calcVecDiffCached(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, typename Dist::result_type* smem, int tid) { vec_distance_detail::VecDiffCachedCalculator::calc(vecCached, vecGlob, len, dist, tid); dist.reduceAll(smem, tid); } // calc distance between two vectors in global memory template struct VecDiffGlobal { explicit __device__ __forceinline__ VecDiffGlobal(const T1* vec1_, int = 0, void* = 0, int = 0, int = 0) { vec1 = vec1_; } template __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const { calcVecDiffGlobal(vec1, vec2, len, dist, smem, tid); } const T1* vec1; }; // calc distance between two vectors, first vector is cached in register memory, second vector is in global memory template struct VecDiffCachedRegister { template __device__ __forceinline__ VecDiffCachedRegister(const T1* vec1, int len, U* smem, int glob_tid, int tid) { if (glob_tid < len) smem[glob_tid] = vec1[glob_tid]; __syncthreads(); U* vec1ValsPtr = vec1Vals; #pragma unroll for (int i = tid; i < MAX_LEN; i += THREAD_DIM) *vec1ValsPtr++ = smem[i]; __syncthreads(); } template __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const { calcVecDiffCached(vec1Vals, vec2, len, dist, smem, tid); } U vec1Vals[MAX_LEN / THREAD_DIM]; }; }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_VEC_DISTANCE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/vec_math.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_VECMATH_HPP__ #define __OPENCV_CUDA_VECMATH_HPP__ #include "vec_traits.hpp" #include "saturate_cast.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { // saturate_cast namespace vec_math_detail { template struct SatCastHelper; template struct SatCastHelper<1, VecD> { template static __device__ __forceinline__ VecD cast(const VecS& v) { typedef typename VecTraits::elem_type D; return VecTraits::make(saturate_cast(v.x)); } }; template struct SatCastHelper<2, VecD> { template static __device__ __forceinline__ VecD cast(const VecS& v) { typedef typename VecTraits::elem_type D; return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y)); } }; template struct SatCastHelper<3, VecD> { template static __device__ __forceinline__ VecD cast(const VecS& v) { typedef typename VecTraits::elem_type D; return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z)); } }; template struct SatCastHelper<4, VecD> { template static __device__ __forceinline__ VecD cast(const VecS& v) { typedef typename VecTraits::elem_type D; return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z), saturate_cast(v.w)); } }; template static __device__ __forceinline__ VecD saturate_cast_helper(const VecS& v) { return SatCastHelper::cn, VecD>::cast(v); } } template static __device__ __forceinline__ T saturate_cast(const uchar1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const char1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const ushort1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const short1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const uint1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const int1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const float1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const double1& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const uchar2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const char2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const ushort2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const short2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const uint2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const int2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const float2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const double2& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const uchar3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const char3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const ushort3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const short3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const uint3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const int3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const float3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const double3& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const uchar4& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const char4& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const ushort4& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const short4& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const uint4& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const int4& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const float4& v) {return vec_math_detail::saturate_cast_helper(v);} template static __device__ __forceinline__ T saturate_cast(const double4& v) {return vec_math_detail::saturate_cast_helper(v);} // unary operators #define CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(op, input_type, output_type) \ __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a) \ { \ return VecTraits::make(op (a.x)); \ } \ __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a) \ { \ return VecTraits::make(op (a.x), op (a.y)); \ } \ __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a) \ { \ return VecTraits::make(op (a.x), op (a.y), op (a.z)); \ } \ __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a) \ { \ return VecTraits::make(op (a.x), op (a.y), op (a.z), op (a.w)); \ } CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, char, char) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, short, short) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, int, int) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, char, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, short, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, int, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, float, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, double, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, char, char) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, ushort, ushort) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, short, short) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, int, int) CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uint, uint) #undef CV_CUDEV_IMPLEMENT_VEC_UNARY_OP // unary functions #define CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(func_name, func, input_type, output_type) \ __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a) \ { \ return VecTraits::make(func (a.x)); \ } \ __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a) \ { \ return VecTraits::make(func (a.x), func (a.y)); \ } \ __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a) \ { \ return VecTraits::make(func (a.x), func (a.y), func (a.z)); \ } \ __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a) \ { \ return VecTraits::make(func (a.x), func (a.y), func (a.z), func (a.w)); \ } CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, /*::abs*/, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::abs, char, char) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, /*::abs*/, ushort, ushort) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::abs, short, short) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::abs, int, int) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, /*::abs*/, uint, uint) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabsf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabs, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrt, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::exp, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::log, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sin, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cos, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tan, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asin, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acos, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atan, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinh, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::cosh, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanh, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinh, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acosh, double, double) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, char, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, short, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, int, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uint, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, float, float) CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanh, double, double) #undef CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC // binary operators (vec & vec) #define CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(op, input_type, output_type) \ __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, const input_type ## 1 & b) \ { \ return VecTraits::make(a.x op b.x); \ } \ __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, const input_type ## 2 & b) \ { \ return VecTraits::make(a.x op b.x, a.y op b.y); \ } \ __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, const input_type ## 3 & b) \ { \ return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z); \ } \ __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, const input_type ## 4 & b) \ { \ return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z, a.w op b.w); \ } CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uchar, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, char, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, ushort, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, short, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, double, double) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uchar, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, char, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, ushort, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, short, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, double, double) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uchar, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, char, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, ushort, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, short, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, double, double) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uchar, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, char, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, ushort, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, short, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, double, double) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, char, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, ushort, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, short, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, int, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uint, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, float, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, double, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, char, char) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, ushort, ushort) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, short, short) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, char, char) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, ushort, ushort) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, short, short) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, char, char) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, ushort, ushort) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, short, short) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uint, uint) #undef CV_CUDEV_IMPLEMENT_VEC_BINARY_OP // binary operators (vec & scalar) #define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(op, input_type, scalar_type, output_type) \ __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, scalar_type s) \ { \ return VecTraits::make(a.x op s); \ } \ __device__ __forceinline__ output_type ## 1 operator op(scalar_type s, const input_type ## 1 & b) \ { \ return VecTraits::make(s op b.x); \ } \ __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, scalar_type s) \ { \ return VecTraits::make(a.x op s, a.y op s); \ } \ __device__ __forceinline__ output_type ## 2 operator op(scalar_type s, const input_type ## 2 & b) \ { \ return VecTraits::make(s op b.x, s op b.y); \ } \ __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, scalar_type s) \ { \ return VecTraits::make(a.x op s, a.y op s, a.z op s); \ } \ __device__ __forceinline__ output_type ## 3 operator op(scalar_type s, const input_type ## 3 & b) \ { \ return VecTraits::make(s op b.x, s op b.y, s op b.z); \ } \ __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, scalar_type s) \ { \ return VecTraits::make(a.x op s, a.y op s, a.z op s, a.w op s); \ } \ __device__ __forceinline__ output_type ## 4 operator op(scalar_type s, const input_type ## 4 & b) \ { \ return VecTraits::make(s op b.x, s op b.y, s op b.z, s op b.w); \ } CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, double, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, double, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, double, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, double, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, char, char, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, ushort, ushort, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, short, short, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, int, int, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uint, uint, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, float, float, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, double, double, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, char, char, char) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, ushort, ushort, ushort) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, short, short, short) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, char, char, char) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, ushort, ushort, ushort) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, short, short, short) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, char, char, char) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, ushort, ushort, ushort) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, short, short, short) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uint, uint, uint) #undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP // binary function (vec & vec) #define CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(func_name, func, input_type, output_type) \ __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, const input_type ## 1 & b) \ { \ return VecTraits::make(func (a.x, b.x)); \ } \ __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, const input_type ## 2 & b) \ { \ return VecTraits::make(func (a.x, b.x), func (a.y, b.y)); \ } \ __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, const input_type ## 3 & b) \ { \ return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z)); \ } \ __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, const input_type ## 4 & b) \ { \ return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z), func (a.w, b.w)); \ } CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, char, char) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, ushort, ushort) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, short, short) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmaxf, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmax, double, double) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uchar, uchar) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, char, char) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, ushort, ushort) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, short, short) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uint, uint) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, int, int) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fminf, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fmin, double, double) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uchar, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, char, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, ushort, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, short, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uint, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, int, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypot, double, double) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uchar, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, char, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, ushort, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, short, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uint, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, int, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, float, float) CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2, double, double) #undef CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC // binary function (vec & scalar) #define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(func_name, func, input_type, scalar_type, output_type) \ __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, scalar_type s) \ { \ return VecTraits::make(func ((output_type) a.x, (output_type) s)); \ } \ __device__ __forceinline__ output_type ## 1 func_name(scalar_type s, const input_type ## 1 & b) \ { \ return VecTraits::make(func ((output_type) s, (output_type) b.x)); \ } \ __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, scalar_type s) \ { \ return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s)); \ } \ __device__ __forceinline__ output_type ## 2 func_name(scalar_type s, const input_type ## 2 & b) \ { \ return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y)); \ } \ __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, scalar_type s) \ { \ return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s)); \ } \ __device__ __forceinline__ output_type ## 3 func_name(scalar_type s, const input_type ## 3 & b) \ { \ return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z)); \ } \ __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, scalar_type s) \ { \ return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s), func ((output_type) a.w, (output_type) s)); \ } \ __device__ __forceinline__ output_type ## 4 func_name(scalar_type s, const input_type ## 4 & b) \ { \ return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z), func ((output_type) s, (output_type) b.w)); \ } CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, char, char, char) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, ushort, ushort, ushort) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, short, short, short) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, double, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uchar, uchar, uchar) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, char, char, char) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, ushort, ushort, ushort) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, short, short, short) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uint, uint, uint) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, int, int, int) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, double, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, double, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uchar, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uchar, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, char, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, char, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, ushort, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, ushort, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, short, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, short, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uint, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uint, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, int, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, int, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, float, float, float) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, float, double, double) CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, double, double, double) #undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC }}} // namespace cv { namespace cuda { namespace device //! @endcond #endif // __OPENCV_CUDA_VECMATH_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/vec_traits.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_VEC_TRAITS_HPP__ #define __OPENCV_CUDA_VEC_TRAITS_HPP__ #include "common.hpp" /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template struct TypeVec; struct __align__(8) uchar8 { uchar a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ uchar8 make_uchar8(uchar a0, uchar a1, uchar a2, uchar a3, uchar a4, uchar a5, uchar a6, uchar a7) { uchar8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } struct __align__(8) char8 { schar a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ char8 make_char8(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) { char8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } struct __align__(16) ushort8 { ushort a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ ushort8 make_ushort8(ushort a0, ushort a1, ushort a2, ushort a3, ushort a4, ushort a5, ushort a6, ushort a7) { ushort8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } struct __align__(16) short8 { short a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ short8 make_short8(short a0, short a1, short a2, short a3, short a4, short a5, short a6, short a7) { short8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } struct __align__(32) uint8 { uint a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ uint8 make_uint8(uint a0, uint a1, uint a2, uint a3, uint a4, uint a5, uint a6, uint a7) { uint8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } struct __align__(32) int8 { int a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ int8 make_int8(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7) { int8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } struct __align__(32) float8 { float a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ float8 make_float8(float a0, float a1, float a2, float a3, float a4, float a5, float a6, float a7) { float8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } struct double8 { double a0, a1, a2, a3, a4, a5, a6, a7; }; static __host__ __device__ __forceinline__ double8 make_double8(double a0, double a1, double a2, double a3, double a4, double a5, double a6, double a7) { double8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; return val; } #define OPENCV_CUDA_IMPLEMENT_TYPE_VEC(type) \ template<> struct TypeVec { typedef type vec_type; }; \ template<> struct TypeVec { typedef type ## 1 vec_type; }; \ template<> struct TypeVec { typedef type ## 2 vec_type; }; \ template<> struct TypeVec { typedef type ## 2 vec_type; }; \ template<> struct TypeVec { typedef type ## 3 vec_type; }; \ template<> struct TypeVec { typedef type ## 3 vec_type; }; \ template<> struct TypeVec { typedef type ## 4 vec_type; }; \ template<> struct TypeVec { typedef type ## 4 vec_type; }; \ template<> struct TypeVec { typedef type ## 8 vec_type; }; \ template<> struct TypeVec { typedef type ## 8 vec_type; }; OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uchar) OPENCV_CUDA_IMPLEMENT_TYPE_VEC(char) OPENCV_CUDA_IMPLEMENT_TYPE_VEC(ushort) OPENCV_CUDA_IMPLEMENT_TYPE_VEC(short) OPENCV_CUDA_IMPLEMENT_TYPE_VEC(int) OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uint) OPENCV_CUDA_IMPLEMENT_TYPE_VEC(float) OPENCV_CUDA_IMPLEMENT_TYPE_VEC(double) #undef OPENCV_CUDA_IMPLEMENT_TYPE_VEC template<> struct TypeVec { typedef schar vec_type; }; template<> struct TypeVec { typedef char2 vec_type; }; template<> struct TypeVec { typedef char3 vec_type; }; template<> struct TypeVec { typedef char4 vec_type; }; template<> struct TypeVec { typedef char8 vec_type; }; template<> struct TypeVec { typedef uchar vec_type; }; template<> struct TypeVec { typedef uchar2 vec_type; }; template<> struct TypeVec { typedef uchar3 vec_type; }; template<> struct TypeVec { typedef uchar4 vec_type; }; template<> struct TypeVec { typedef uchar8 vec_type; }; template struct VecTraits; #define OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(type) \ template<> struct VecTraits \ { \ typedef type elem_type; \ enum {cn=1}; \ static __device__ __host__ __forceinline__ type all(type v) {return v;} \ static __device__ __host__ __forceinline__ type make(type x) {return x;} \ static __device__ __host__ __forceinline__ type make(const type* v) {return *v;} \ }; \ template<> struct VecTraits \ { \ typedef type elem_type; \ enum {cn=1}; \ static __device__ __host__ __forceinline__ type ## 1 all(type v) {return make_ ## type ## 1(v);} \ static __device__ __host__ __forceinline__ type ## 1 make(type x) {return make_ ## type ## 1(x);} \ static __device__ __host__ __forceinline__ type ## 1 make(const type* v) {return make_ ## type ## 1(*v);} \ }; \ template<> struct VecTraits \ { \ typedef type elem_type; \ enum {cn=2}; \ static __device__ __host__ __forceinline__ type ## 2 all(type v) {return make_ ## type ## 2(v, v);} \ static __device__ __host__ __forceinline__ type ## 2 make(type x, type y) {return make_ ## type ## 2(x, y);} \ static __device__ __host__ __forceinline__ type ## 2 make(const type* v) {return make_ ## type ## 2(v[0], v[1]);} \ }; \ template<> struct VecTraits \ { \ typedef type elem_type; \ enum {cn=3}; \ static __device__ __host__ __forceinline__ type ## 3 all(type v) {return make_ ## type ## 3(v, v, v);} \ static __device__ __host__ __forceinline__ type ## 3 make(type x, type y, type z) {return make_ ## type ## 3(x, y, z);} \ static __device__ __host__ __forceinline__ type ## 3 make(const type* v) {return make_ ## type ## 3(v[0], v[1], v[2]);} \ }; \ template<> struct VecTraits \ { \ typedef type elem_type; \ enum {cn=4}; \ static __device__ __host__ __forceinline__ type ## 4 all(type v) {return make_ ## type ## 4(v, v, v, v);} \ static __device__ __host__ __forceinline__ type ## 4 make(type x, type y, type z, type w) {return make_ ## type ## 4(x, y, z, w);} \ static __device__ __host__ __forceinline__ type ## 4 make(const type* v) {return make_ ## type ## 4(v[0], v[1], v[2], v[3]);} \ }; \ template<> struct VecTraits \ { \ typedef type elem_type; \ enum {cn=8}; \ static __device__ __host__ __forceinline__ type ## 8 all(type v) {return make_ ## type ## 8(v, v, v, v, v, v, v, v);} \ static __device__ __host__ __forceinline__ type ## 8 make(type a0, type a1, type a2, type a3, type a4, type a5, type a6, type a7) {return make_ ## type ## 8(a0, a1, a2, a3, a4, a5, a6, a7);} \ static __device__ __host__ __forceinline__ type ## 8 make(const type* v) {return make_ ## type ## 8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} \ }; OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uchar) OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(ushort) OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(short) OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(int) OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uint) OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(float) OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(double) #undef OPENCV_CUDA_IMPLEMENT_VEC_TRAITS template<> struct VecTraits { typedef char elem_type; enum {cn=1}; static __device__ __host__ __forceinline__ char all(char v) {return v;} static __device__ __host__ __forceinline__ char make(char x) {return x;} static __device__ __host__ __forceinline__ char make(const char* x) {return *x;} }; template<> struct VecTraits { typedef schar elem_type; enum {cn=1}; static __device__ __host__ __forceinline__ schar all(schar v) {return v;} static __device__ __host__ __forceinline__ schar make(schar x) {return x;} static __device__ __host__ __forceinline__ schar make(const schar* x) {return *x;} }; template<> struct VecTraits { typedef schar elem_type; enum {cn=1}; static __device__ __host__ __forceinline__ char1 all(schar v) {return make_char1(v);} static __device__ __host__ __forceinline__ char1 make(schar x) {return make_char1(x);} static __device__ __host__ __forceinline__ char1 make(const schar* v) {return make_char1(v[0]);} }; template<> struct VecTraits { typedef schar elem_type; enum {cn=2}; static __device__ __host__ __forceinline__ char2 all(schar v) {return make_char2(v, v);} static __device__ __host__ __forceinline__ char2 make(schar x, schar y) {return make_char2(x, y);} static __device__ __host__ __forceinline__ char2 make(const schar* v) {return make_char2(v[0], v[1]);} }; template<> struct VecTraits { typedef schar elem_type; enum {cn=3}; static __device__ __host__ __forceinline__ char3 all(schar v) {return make_char3(v, v, v);} static __device__ __host__ __forceinline__ char3 make(schar x, schar y, schar z) {return make_char3(x, y, z);} static __device__ __host__ __forceinline__ char3 make(const schar* v) {return make_char3(v[0], v[1], v[2]);} }; template<> struct VecTraits { typedef schar elem_type; enum {cn=4}; static __device__ __host__ __forceinline__ char4 all(schar v) {return make_char4(v, v, v, v);} static __device__ __host__ __forceinline__ char4 make(schar x, schar y, schar z, schar w) {return make_char4(x, y, z, w);} static __device__ __host__ __forceinline__ char4 make(const schar* v) {return make_char4(v[0], v[1], v[2], v[3]);} }; template<> struct VecTraits { typedef schar elem_type; enum {cn=8}; static __device__ __host__ __forceinline__ char8 all(schar v) {return make_char8(v, v, v, v, v, v, v, v);} static __device__ __host__ __forceinline__ char8 make(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) {return make_char8(a0, a1, a2, a3, a4, a5, a6, a7);} static __device__ __host__ __forceinline__ char8 make(const schar* v) {return make_char8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} }; }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif // __OPENCV_CUDA_VEC_TRAITS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/warp.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_DEVICE_WARP_HPP__ #define __OPENCV_CUDA_DEVICE_WARP_HPP__ /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { struct Warp { enum { LOG_WARP_SIZE = 5, WARP_SIZE = 1 << LOG_WARP_SIZE, STRIDE = WARP_SIZE }; /** \brief Returns the warp lane ID of the calling thread. */ static __device__ __forceinline__ unsigned int laneId() { unsigned int ret; asm("mov.u32 %0, %laneid;" : "=r"(ret) ); return ret; } template static __device__ __forceinline__ void fill(It beg, It end, const T& value) { for(It t = beg + laneId(); t < end; t += STRIDE) *t = value; } template static __device__ __forceinline__ OutIt copy(InIt beg, InIt end, OutIt out) { for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) *out = *t; return out; } template static __device__ __forceinline__ OutIt transform(InIt beg, InIt end, OutIt out, UnOp op) { for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) *out = op(*t); return out; } template static __device__ __forceinline__ OutIt transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) { unsigned int lane = laneId(); InIt1 t1 = beg1 + lane; InIt2 t2 = beg2 + lane; for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, out += STRIDE) *out = op(*t1, *t2); return out; } template static __device__ __forceinline__ T reduce(volatile T *ptr, BinOp op) { const unsigned int lane = laneId(); if (lane < 16) { T partial = ptr[lane]; ptr[lane] = partial = op(partial, ptr[lane + 16]); ptr[lane] = partial = op(partial, ptr[lane + 8]); ptr[lane] = partial = op(partial, ptr[lane + 4]); ptr[lane] = partial = op(partial, ptr[lane + 2]); ptr[lane] = partial = op(partial, ptr[lane + 1]); } return *ptr; } template static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) { unsigned int lane = laneId(); value += lane; for(OutIt t = beg + lane; t < end; t += STRIDE, value += STRIDE) *t = value; } }; }}} // namespace cv { namespace cuda { namespace cudev //! @endcond #endif /* __OPENCV_CUDA_DEVICE_WARP_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/warp_reduce.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_CUDA_WARP_REDUCE_HPP__ #define OPENCV_CUDA_WARP_REDUCE_HPP__ /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template __device__ __forceinline__ T warp_reduce(volatile T *ptr , const unsigned int tid = threadIdx.x) { const unsigned int lane = tid & 31; // index of thread in warp (0..31) if (lane < 16) { T partial = ptr[tid]; ptr[tid] = partial = partial + ptr[tid + 16]; ptr[tid] = partial = partial + ptr[tid + 8]; ptr[tid] = partial = partial + ptr[tid + 4]; ptr[tid] = partial = partial + ptr[tid + 2]; ptr[tid] = partial = partial + ptr[tid + 1]; } return ptr[tid - lane]; } }}} // namespace cv { namespace cuda { namespace cudev { //! @endcond #endif /* OPENCV_CUDA_WARP_REDUCE_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda/warp_shuffle.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CUDA_WARP_SHUFFLE_HPP__ #define __OPENCV_CUDA_WARP_SHUFFLE_HPP__ /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED namespace cv { namespace cuda { namespace device { template __device__ __forceinline__ T shfl(T val, int srcLane, int width = warpSize) { #if __CUDA_ARCH__ >= 300 return __shfl(val, srcLane, width); #else return T(); #endif } __device__ __forceinline__ unsigned int shfl(unsigned int val, int srcLane, int width = warpSize) { #if __CUDA_ARCH__ >= 300 return (unsigned int) __shfl((int) val, srcLane, width); #else return 0; #endif } __device__ __forceinline__ double shfl(double val, int srcLane, int width = warpSize) { #if __CUDA_ARCH__ >= 300 int lo = __double2loint(val); int hi = __double2hiint(val); lo = __shfl(lo, srcLane, width); hi = __shfl(hi, srcLane, width); return __hiloint2double(hi, lo); #else return 0.0; #endif } template __device__ __forceinline__ T shfl_down(T val, unsigned int delta, int width = warpSize) { #if __CUDA_ARCH__ >= 300 return __shfl_down(val, delta, width); #else return T(); #endif } __device__ __forceinline__ unsigned int shfl_down(unsigned int val, unsigned int delta, int width = warpSize) { #if __CUDA_ARCH__ >= 300 return (unsigned int) __shfl_down((int) val, delta, width); #else return 0; #endif } __device__ __forceinline__ double shfl_down(double val, unsigned int delta, int width = warpSize) { #if __CUDA_ARCH__ >= 300 int lo = __double2loint(val); int hi = __double2hiint(val); lo = __shfl_down(lo, delta, width); hi = __shfl_down(hi, delta, width); return __hiloint2double(hi, lo); #else return 0.0; #endif } template __device__ __forceinline__ T shfl_up(T val, unsigned int delta, int width = warpSize) { #if __CUDA_ARCH__ >= 300 return __shfl_up(val, delta, width); #else return T(); #endif } __device__ __forceinline__ unsigned int shfl_up(unsigned int val, unsigned int delta, int width = warpSize) { #if __CUDA_ARCH__ >= 300 return (unsigned int) __shfl_up((int) val, delta, width); #else return 0; #endif } __device__ __forceinline__ double shfl_up(double val, unsigned int delta, int width = warpSize) { #if __CUDA_ARCH__ >= 300 int lo = __double2loint(val); int hi = __double2hiint(val); lo = __shfl_up(lo, delta, width); hi = __shfl_up(hi, delta, width); return __hiloint2double(hi, lo); #else return 0.0; #endif } }}} //! @endcond #endif // __OPENCV_CUDA_WARP_SHUFFLE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_CUDA_HPP__ #define __OPENCV_CORE_CUDA_HPP__ #ifndef __cplusplus # error cuda.hpp header must be compiled as C++ #endif #include "opencv2/core.hpp" #include "opencv2/core/cuda_types.hpp" /** @defgroup cuda CUDA-accelerated Computer Vision @{ @defgroup cudacore Core part @{ @defgroup cudacore_init Initalization and Information @defgroup cudacore_struct Data Structures @} @} */ namespace cv { namespace cuda { //! @addtogroup cudacore_struct //! @{ //=================================================================================== // GpuMat //=================================================================================== /** @brief Base storage class for GPU memory with reference counting. Its interface matches the Mat interface with the following limitations: - no arbitrary dimensions support (only 2D) - no functions that return references to their data (because references on GPU are not valid for CPU) - no expression templates technique support Beware that the latter limitation may lead to overloaded matrix operators that cause memory allocations. The GpuMat class is convertible to cuda::PtrStepSz and cuda::PtrStep so it can be passed directly to the kernel. @note In contrast with Mat, in most cases GpuMat::isContinuous() == false . This means that rows are aligned to a size depending on the hardware. Single-row GpuMat is always a continuous matrix. @note You are not recommended to leave static or global GpuMat variables allocated, that is, to rely on its destructor. The destruction order of such variables and CUDA context is undefined. GPU memory release function returns error if the CUDA context has been destroyed before. @sa Mat */ class CV_EXPORTS GpuMat { public: class CV_EXPORTS Allocator { public: virtual ~Allocator() {} // allocator must fill data, step and refcount fields virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0; virtual void free(GpuMat* mat) = 0; }; //! default allocator static Allocator* defaultAllocator(); static void setDefaultAllocator(Allocator* allocator); //! default constructor explicit GpuMat(Allocator* allocator = defaultAllocator()); //! constructs GpuMat of the specified size and type GpuMat(int rows, int cols, int type, Allocator* allocator = defaultAllocator()); GpuMat(Size size, int type, Allocator* allocator = defaultAllocator()); //! constucts GpuMat and fills it with the specified value _s GpuMat(int rows, int cols, int type, Scalar s, Allocator* allocator = defaultAllocator()); GpuMat(Size size, int type, Scalar s, Allocator* allocator = defaultAllocator()); //! copy constructor GpuMat(const GpuMat& m); //! constructor for GpuMat headers pointing to user-allocated data GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); //! creates a GpuMat header for a part of the bigger matrix GpuMat(const GpuMat& m, Range rowRange, Range colRange); GpuMat(const GpuMat& m, Rect roi); //! builds GpuMat from host memory (Blocking call) explicit GpuMat(InputArray arr, Allocator* allocator = defaultAllocator()); //! destructor - calls release() ~GpuMat(); //! assignment operators GpuMat& operator =(const GpuMat& m); //! allocates new GpuMat data unless the GpuMat already has specified size and type void create(int rows, int cols, int type); void create(Size size, int type); //! decreases reference counter, deallocate the data when reference counter reaches 0 void release(); //! swaps with other smart pointer void swap(GpuMat& mat); //! pefroms upload data to GpuMat (Blocking call) void upload(InputArray arr); //! pefroms upload data to GpuMat (Non-Blocking call) void upload(InputArray arr, Stream& stream); //! pefroms download data from device to host memory (Blocking call) void download(OutputArray dst) const; //! pefroms download data from device to host memory (Non-Blocking call) void download(OutputArray dst, Stream& stream) const; //! returns deep copy of the GpuMat, i.e. the data is copied GpuMat clone() const; //! copies the GpuMat content to device memory (Blocking call) void copyTo(OutputArray dst) const; //! copies the GpuMat content to device memory (Non-Blocking call) void copyTo(OutputArray dst, Stream& stream) const; //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) void copyTo(OutputArray dst, InputArray mask) const; //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) void copyTo(OutputArray dst, InputArray mask, Stream& stream) const; //! sets some of the GpuMat elements to s (Blocking call) GpuMat& setTo(Scalar s); //! sets some of the GpuMat elements to s (Non-Blocking call) GpuMat& setTo(Scalar s, Stream& stream); //! sets some of the GpuMat elements to s, according to the mask (Blocking call) GpuMat& setTo(Scalar s, InputArray mask); //! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call) GpuMat& setTo(Scalar s, InputArray mask, Stream& stream); //! converts GpuMat to another datatype (Blocking call) void convertTo(OutputArray dst, int rtype) const; //! converts GpuMat to another datatype (Non-Blocking call) void convertTo(OutputArray dst, int rtype, Stream& stream) const; //! converts GpuMat to another datatype with scaling (Blocking call) void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const; //! converts GpuMat to another datatype with scaling (Non-Blocking call) void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const; //! converts GpuMat to another datatype with scaling (Non-Blocking call) void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const; void assignTo(GpuMat& m, int type=-1) const; //! returns pointer to y-th row uchar* ptr(int y = 0); const uchar* ptr(int y = 0) const; //! template version of the above method template _Tp* ptr(int y = 0); template const _Tp* ptr(int y = 0) const; template operator PtrStepSz<_Tp>() const; template operator PtrStep<_Tp>() const; //! returns a new GpuMat header for the specified row GpuMat row(int y) const; //! returns a new GpuMat header for the specified column GpuMat col(int x) const; //! ... for the specified row span GpuMat rowRange(int startrow, int endrow) const; GpuMat rowRange(Range r) const; //! ... for the specified column span GpuMat colRange(int startcol, int endcol) const; GpuMat colRange(Range r) const; //! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.) GpuMat operator ()(Range rowRange, Range colRange) const; GpuMat operator ()(Rect roi) const; //! creates alternative GpuMat header for the same data, with different //! number of channels and/or different number of rows GpuMat reshape(int cn, int rows = 0) const; //! locates GpuMat header within a parent GpuMat void locateROI(Size& wholeSize, Point& ofs) const; //! moves/resizes the current GpuMat ROI inside the parent GpuMat GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright); //! returns true iff the GpuMat data is continuous //! (i.e. when there are no gaps between successive rows) bool isContinuous() const; //! returns element size in bytes size_t elemSize() const; //! returns the size of element channel in bytes size_t elemSize1() const; //! returns element type int type() const; //! returns element type int depth() const; //! returns number of channels int channels() const; //! returns step/elemSize1() size_t step1() const; //! returns GpuMat size : width == number of columns, height == number of rows Size size() const; //! returns true if GpuMat data is NULL bool empty() const; /*! includes several bit-fields: - the magic signature - continuity flag - depth - number of channels */ int flags; //! the number of rows and columns int rows, cols; //! a distance between successive rows in bytes; includes the gap if any size_t step; //! pointer to the data uchar* data; //! pointer to the reference counter; //! when GpuMat points to user-allocated data, the pointer is NULL int* refcount; //! helper fields used in locateROI and adjustROI uchar* datastart; const uchar* dataend; //! allocator Allocator* allocator; }; /** @brief Creates a continuous matrix. @param rows Row count. @param cols Column count. @param type Type of the matrix. @param arr Destination matrix. This parameter changes only if it has a proper type and area ( \f$\texttt{rows} \times \texttt{cols}\f$ ). Matrix is called continuous if its elements are stored continuously, that is, without gaps at the end of each row. */ CV_EXPORTS void createContinuous(int rows, int cols, int type, OutputArray arr); /** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type. @param rows Minimum desired number of rows. @param cols Minimum desired number of columns. @param type Desired matrix type. @param arr Destination matrix. The function does not reallocate memory if the matrix has proper attributes already. */ CV_EXPORTS void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr); //! BufferPool management (must be called before Stream creation) CV_EXPORTS void setBufferPoolUsage(bool on); CV_EXPORTS void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount); //=================================================================================== // HostMem //=================================================================================== /** @brief Class with reference counting wrapping special memory type allocation functions from CUDA. Its interface is also Mat-like but with additional memory type parameters. - **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous uploading/downloading data from/to GPU. - **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU address space, if supported. - **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache utilization. @note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2 Pinned Memory APIs* document or *CUDA C Programming Guide*. */ class CV_EXPORTS HostMem { public: enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 }; static MatAllocator* getAllocator(AllocType alloc_type = PAGE_LOCKED); explicit HostMem(AllocType alloc_type = PAGE_LOCKED); HostMem(const HostMem& m); HostMem(int rows, int cols, int type, AllocType alloc_type = PAGE_LOCKED); HostMem(Size size, int type, AllocType alloc_type = PAGE_LOCKED); //! creates from host memory with coping data explicit HostMem(InputArray arr, AllocType alloc_type = PAGE_LOCKED); ~HostMem(); HostMem& operator =(const HostMem& m); //! swaps with other smart pointer void swap(HostMem& b); //! returns deep copy of the matrix, i.e. the data is copied HostMem clone() const; //! allocates new matrix data unless the matrix already has specified size and type. void create(int rows, int cols, int type); void create(Size size, int type); //! creates alternative HostMem header for the same data, with different //! number of channels and/or different number of rows HostMem reshape(int cn, int rows = 0) const; //! decrements reference counter and released memory if needed. void release(); //! returns matrix header with disabled reference counting for HostMem data. Mat createMatHeader() const; /** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting for it. This can be done only if memory was allocated with the SHARED flag and if it is supported by the hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which eliminates an extra copy. */ GpuMat createGpuMatHeader() const; // Please see cv::Mat for descriptions bool isContinuous() const; size_t elemSize() const; size_t elemSize1() const; int type() const; int depth() const; int channels() const; size_t step1() const; Size size() const; bool empty() const; // Please see cv::Mat for descriptions int flags; int rows, cols; size_t step; uchar* data; int* refcount; uchar* datastart; const uchar* dataend; AllocType alloc_type; }; /** @brief Page-locks the memory of matrix and maps it for the device(s). @param m Input matrix. */ CV_EXPORTS void registerPageLocked(Mat& m); /** @brief Unmaps the memory of matrix and makes it pageable again. @param m Input matrix. */ CV_EXPORTS void unregisterPageLocked(Mat& m); //=================================================================================== // Stream //=================================================================================== /** @brief This class encapsulates a queue of asynchronous calls. @note Currently, you may face problems if an operation is enqueued twice with different data. Some functions use the constant GPU memory, and next call may update the memory before the previous one has been finished. But calling different operations asynchronously is safe because each operation has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are also safe. : */ class CV_EXPORTS Stream { typedef void (Stream::*bool_type)() const; void this_type_does_not_support_comparisons() const {} public: typedef void (*StreamCallback)(int status, void* userData); //! creates a new asynchronous stream Stream(); /** @brief Returns true if the current stream queue is finished. Otherwise, it returns false. */ bool queryIfComplete() const; /** @brief Blocks the current CPU thread until all operations in the stream are complete. */ void waitForCompletion(); /** @brief Makes a compute stream wait on an event. */ void waitEvent(const Event& event); /** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have completed. @note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization that may depend on outstanding device work or other callbacks that are not mandated to run earlier. Callbacks without a mandated order (in independent streams) execute in undefined order and may be serialized. */ void enqueueHostCallback(StreamCallback callback, void* userData); //! return Stream object for default CUDA stream static Stream& Null(); //! returns true if stream object is not default (!= 0) operator bool_type() const; class Impl; private: Ptr impl_; Stream(const Ptr& impl); friend struct StreamAccessor; friend class BufferPool; friend class DefaultDeviceInitializer; }; class CV_EXPORTS Event { public: enum CreateFlags { DEFAULT = 0x00, /**< Default event flag */ BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */ DISABLE_TIMING = 0x02, /**< Event will not record timing data */ INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */ }; explicit Event(CreateFlags flags = DEFAULT); //! records an event void record(Stream& stream = Stream::Null()); //! queries an event's status bool queryIfComplete() const; //! waits for an event to complete void waitForCompletion(); //! computes the elapsed time between events static float elapsedTime(const Event& start, const Event& end); class Impl; private: Ptr impl_; Event(const Ptr& impl); friend struct EventAccessor; }; //! @} cudacore_struct //=================================================================================== // Initialization & Info //=================================================================================== //! @addtogroup cudacore_init //! @{ /** @brief Returns the number of installed CUDA-enabled devices. Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support, this function returns 0. */ CV_EXPORTS int getCudaEnabledDeviceCount(); /** @brief Sets a device and initializes it for the current thread. @param device System index of a CUDA device starting with 0. If the call of this function is omitted, a default device is initialized at the fist CUDA usage. */ CV_EXPORTS void setDevice(int device); /** @brief Returns the current device index set by cuda::setDevice or initialized by default. */ CV_EXPORTS int getDevice(); /** @brief Explicitly destroys and cleans up all resources associated with the current device in the current process. Any subsequent API call to this device will reinitialize the device. */ CV_EXPORTS void resetDevice(); /** @brief Enumeration providing CUDA computing features. */ enum FeatureSet { FEATURE_SET_COMPUTE_10 = 10, FEATURE_SET_COMPUTE_11 = 11, FEATURE_SET_COMPUTE_12 = 12, FEATURE_SET_COMPUTE_13 = 13, FEATURE_SET_COMPUTE_20 = 20, FEATURE_SET_COMPUTE_21 = 21, FEATURE_SET_COMPUTE_30 = 30, FEATURE_SET_COMPUTE_32 = 32, FEATURE_SET_COMPUTE_35 = 35, FEATURE_SET_COMPUTE_50 = 50, GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, SHARED_ATOMICS = FEATURE_SET_COMPUTE_12, NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13, WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30, DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35 }; //! checks whether current device supports the given feature CV_EXPORTS bool deviceSupports(FeatureSet feature_set); /** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was built for. According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute capability can always be compiled to binary code of greater or equal compute capability". */ class CV_EXPORTS TargetArchs { public: /** @brief The following method checks whether the module was built with the support of the given feature: @param feature_set Features to be checked. See :ocvcuda::FeatureSet. */ static bool builtWith(FeatureSet feature_set); /** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA code for the given architecture(s): @param major Major compute capability version. @param minor Minor compute capability version. */ static bool has(int major, int minor); static bool hasPtx(int major, int minor); static bool hasBin(int major, int minor); static bool hasEqualOrLessPtx(int major, int minor); static bool hasEqualOrGreater(int major, int minor); static bool hasEqualOrGreaterPtx(int major, int minor); static bool hasEqualOrGreaterBin(int major, int minor); }; /** @brief Class providing functionality for querying the specified GPU properties. */ class CV_EXPORTS DeviceInfo { public: //! creates DeviceInfo object for the current GPU DeviceInfo(); /** @brief The constructors. @param device_id System index of the CUDA device starting with 0. Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it constructs an object for the current device. */ DeviceInfo(int device_id); /** @brief Returns system index of the CUDA device starting with 0. */ int deviceID() const; //! ASCII string identifying device const char* name() const; //! global memory available on device in bytes size_t totalGlobalMem() const; //! shared memory available per block in bytes size_t sharedMemPerBlock() const; //! 32-bit registers available per block int regsPerBlock() const; //! warp size in threads int warpSize() const; //! maximum pitch in bytes allowed by memory copies size_t memPitch() const; //! maximum number of threads per block int maxThreadsPerBlock() const; //! maximum size of each dimension of a block Vec3i maxThreadsDim() const; //! maximum size of each dimension of a grid Vec3i maxGridSize() const; //! clock frequency in kilohertz int clockRate() const; //! constant memory available on device in bytes size_t totalConstMem() const; //! major compute capability int majorVersion() const; //! minor compute capability int minorVersion() const; //! alignment requirement for textures size_t textureAlignment() const; //! pitch alignment requirement for texture references bound to pitched memory size_t texturePitchAlignment() const; //! number of multiprocessors on device int multiProcessorCount() const; //! specified whether there is a run time limit on kernels bool kernelExecTimeoutEnabled() const; //! device is integrated as opposed to discrete bool integrated() const; //! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer bool canMapHostMemory() const; enum ComputeMode { ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */ ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */ ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */ ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */ }; //! compute mode ComputeMode computeMode() const; //! maximum 1D texture size int maxTexture1D() const; //! maximum 1D mipmapped texture size int maxTexture1DMipmap() const; //! maximum size for 1D textures bound to linear memory int maxTexture1DLinear() const; //! maximum 2D texture dimensions Vec2i maxTexture2D() const; //! maximum 2D mipmapped texture dimensions Vec2i maxTexture2DMipmap() const; //! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory Vec3i maxTexture2DLinear() const; //! maximum 2D texture dimensions if texture gather operations have to be performed Vec2i maxTexture2DGather() const; //! maximum 3D texture dimensions Vec3i maxTexture3D() const; //! maximum Cubemap texture dimensions int maxTextureCubemap() const; //! maximum 1D layered texture dimensions Vec2i maxTexture1DLayered() const; //! maximum 2D layered texture dimensions Vec3i maxTexture2DLayered() const; //! maximum Cubemap layered texture dimensions Vec2i maxTextureCubemapLayered() const; //! maximum 1D surface size int maxSurface1D() const; //! maximum 2D surface dimensions Vec2i maxSurface2D() const; //! maximum 3D surface dimensions Vec3i maxSurface3D() const; //! maximum 1D layered surface dimensions Vec2i maxSurface1DLayered() const; //! maximum 2D layered surface dimensions Vec3i maxSurface2DLayered() const; //! maximum Cubemap surface dimensions int maxSurfaceCubemap() const; //! maximum Cubemap layered surface dimensions Vec2i maxSurfaceCubemapLayered() const; //! alignment requirements for surfaces size_t surfaceAlignment() const; //! device can possibly execute multiple kernels concurrently bool concurrentKernels() const; //! device has ECC support enabled bool ECCEnabled() const; //! PCI bus ID of the device int pciBusID() const; //! PCI device ID of the device int pciDeviceID() const; //! PCI domain ID of the device int pciDomainID() const; //! true if device is a Tesla device using TCC driver, false otherwise bool tccDriver() const; //! number of asynchronous engines int asyncEngineCount() const; //! device shares a unified address space with the host bool unifiedAddressing() const; //! peak memory clock frequency in kilohertz int memoryClockRate() const; //! global memory bus width in bits int memoryBusWidth() const; //! size of L2 cache in bytes int l2CacheSize() const; //! maximum resident threads per multiprocessor int maxThreadsPerMultiProcessor() const; //! gets free and total device memory void queryMemory(size_t& totalMemory, size_t& freeMemory) const; size_t freeMemory() const; size_t totalMemory() const; /** @brief Provides information on CUDA feature support. @param feature_set Features to be checked. See cuda::FeatureSet. This function returns true if the device has the specified CUDA feature. Otherwise, it returns false */ bool supports(FeatureSet feature_set) const; /** @brief Checks the CUDA module and device compatibility. This function returns true if the CUDA module can be run on the specified device. Otherwise, it returns false . */ bool isCompatible() const; private: int device_id_; }; CV_EXPORTS void printCudaDeviceInfo(int device); CV_EXPORTS void printShortCudaDeviceInfo(int device); //! @} cudacore_init }} // namespace cv { namespace cuda { #include "opencv2/core/cuda.inl.hpp" #endif /* __OPENCV_CORE_CUDA_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda.inl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_CUDAINL_HPP__ #define __OPENCV_CORE_CUDAINL_HPP__ #include "opencv2/core/cuda.hpp" //! @cond IGNORED namespace cv { namespace cuda { //=================================================================================== // GpuMat //=================================================================================== inline GpuMat::GpuMat(Allocator* allocator_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) {} inline GpuMat::GpuMat(int rows_, int cols_, int type_, Allocator* allocator_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) { if (rows_ > 0 && cols_ > 0) create(rows_, cols_, type_); } inline GpuMat::GpuMat(Size size_, int type_, Allocator* allocator_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) { if (size_.height > 0 && size_.width > 0) create(size_.height, size_.width, type_); } inline GpuMat::GpuMat(int rows_, int cols_, int type_, Scalar s_, Allocator* allocator_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) { if (rows_ > 0 && cols_ > 0) { create(rows_, cols_, type_); setTo(s_); } } inline GpuMat::GpuMat(Size size_, int type_, Scalar s_, Allocator* allocator_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) { if (size_.height > 0 && size_.width > 0) { create(size_.height, size_.width, type_); setTo(s_); } } inline GpuMat::GpuMat(const GpuMat& m) : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), allocator(m.allocator) { if (refcount) CV_XADD(refcount, 1); } inline GpuMat::GpuMat(InputArray arr, Allocator* allocator_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) { upload(arr); } inline GpuMat::~GpuMat() { release(); } inline GpuMat& GpuMat::operator =(const GpuMat& m) { if (this != &m) { GpuMat temp(m); swap(temp); } return *this; } inline void GpuMat::create(Size size_, int type_) { create(size_.height, size_.width, type_); } inline void GpuMat::swap(GpuMat& b) { std::swap(flags, b.flags); std::swap(rows, b.rows); std::swap(cols, b.cols); std::swap(step, b.step); std::swap(data, b.data); std::swap(datastart, b.datastart); std::swap(dataend, b.dataend); std::swap(refcount, b.refcount); std::swap(allocator, b.allocator); } inline GpuMat GpuMat::clone() const { GpuMat m; copyTo(m); return m; } inline void GpuMat::copyTo(OutputArray dst, InputArray mask) const { copyTo(dst, mask, Stream::Null()); } inline GpuMat& GpuMat::setTo(Scalar s) { return setTo(s, Stream::Null()); } inline GpuMat& GpuMat::setTo(Scalar s, InputArray mask) { return setTo(s, mask, Stream::Null()); } inline void GpuMat::convertTo(OutputArray dst, int rtype) const { convertTo(dst, rtype, Stream::Null()); } inline void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, double beta) const { convertTo(dst, rtype, alpha, beta, Stream::Null()); } inline void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const { convertTo(dst, rtype, alpha, 0.0, stream); } inline void GpuMat::assignTo(GpuMat& m, int _type) const { if (_type < 0) m = *this; else convertTo(m, _type); } inline uchar* GpuMat::ptr(int y) { CV_DbgAssert( (unsigned)y < (unsigned)rows ); return data + step * y; } inline const uchar* GpuMat::ptr(int y) const { CV_DbgAssert( (unsigned)y < (unsigned)rows ); return data + step * y; } template inline _Tp* GpuMat::ptr(int y) { return (_Tp*)ptr(y); } template inline const _Tp* GpuMat::ptr(int y) const { return (const _Tp*)ptr(y); } template inline GpuMat::operator PtrStepSz() const { return PtrStepSz(rows, cols, (T*)data, step); } template inline GpuMat::operator PtrStep() const { return PtrStep((T*)data, step); } inline GpuMat GpuMat::row(int y) const { return GpuMat(*this, Range(y, y+1), Range::all()); } inline GpuMat GpuMat::col(int x) const { return GpuMat(*this, Range::all(), Range(x, x+1)); } inline GpuMat GpuMat::rowRange(int startrow, int endrow) const { return GpuMat(*this, Range(startrow, endrow), Range::all()); } inline GpuMat GpuMat::rowRange(Range r) const { return GpuMat(*this, r, Range::all()); } inline GpuMat GpuMat::colRange(int startcol, int endcol) const { return GpuMat(*this, Range::all(), Range(startcol, endcol)); } inline GpuMat GpuMat::colRange(Range r) const { return GpuMat(*this, Range::all(), r); } inline GpuMat GpuMat::operator ()(Range rowRange_, Range colRange_) const { return GpuMat(*this, rowRange_, colRange_); } inline GpuMat GpuMat::operator ()(Rect roi) const { return GpuMat(*this, roi); } inline bool GpuMat::isContinuous() const { return (flags & Mat::CONTINUOUS_FLAG) != 0; } inline size_t GpuMat::elemSize() const { return CV_ELEM_SIZE(flags); } inline size_t GpuMat::elemSize1() const { return CV_ELEM_SIZE1(flags); } inline int GpuMat::type() const { return CV_MAT_TYPE(flags); } inline int GpuMat::depth() const { return CV_MAT_DEPTH(flags); } inline int GpuMat::channels() const { return CV_MAT_CN(flags); } inline size_t GpuMat::step1() const { return step / elemSize1(); } inline Size GpuMat::size() const { return Size(cols, rows); } inline bool GpuMat::empty() const { return data == 0; } static inline GpuMat createContinuous(int rows, int cols, int type) { GpuMat m; createContinuous(rows, cols, type, m); return m; } static inline void createContinuous(Size size, int type, OutputArray arr) { createContinuous(size.height, size.width, type, arr); } static inline GpuMat createContinuous(Size size, int type) { GpuMat m; createContinuous(size, type, m); return m; } static inline void ensureSizeIsEnough(Size size, int type, OutputArray arr) { ensureSizeIsEnough(size.height, size.width, type, arr); } static inline void swap(GpuMat& a, GpuMat& b) { a.swap(b); } //=================================================================================== // HostMem //=================================================================================== inline HostMem::HostMem(AllocType alloc_type_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) { } inline HostMem::HostMem(const HostMem& m) : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type) { if( refcount ) CV_XADD(refcount, 1); } inline HostMem::HostMem(int rows_, int cols_, int type_, AllocType alloc_type_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) { if (rows_ > 0 && cols_ > 0) create(rows_, cols_, type_); } inline HostMem::HostMem(Size size_, int type_, AllocType alloc_type_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) { if (size_.height > 0 && size_.width > 0) create(size_.height, size_.width, type_); } inline HostMem::HostMem(InputArray arr, AllocType alloc_type_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) { arr.getMat().copyTo(*this); } inline HostMem::~HostMem() { release(); } inline HostMem& HostMem::operator =(const HostMem& m) { if (this != &m) { HostMem temp(m); swap(temp); } return *this; } inline void HostMem::swap(HostMem& b) { std::swap(flags, b.flags); std::swap(rows, b.rows); std::swap(cols, b.cols); std::swap(step, b.step); std::swap(data, b.data); std::swap(datastart, b.datastart); std::swap(dataend, b.dataend); std::swap(refcount, b.refcount); std::swap(alloc_type, b.alloc_type); } inline HostMem HostMem::clone() const { HostMem m(size(), type(), alloc_type); createMatHeader().copyTo(m); return m; } inline void HostMem::create(Size size_, int type_) { create(size_.height, size_.width, type_); } inline Mat HostMem::createMatHeader() const { return Mat(size(), type(), data, step); } inline bool HostMem::isContinuous() const { return (flags & Mat::CONTINUOUS_FLAG) != 0; } inline size_t HostMem::elemSize() const { return CV_ELEM_SIZE(flags); } inline size_t HostMem::elemSize1() const { return CV_ELEM_SIZE1(flags); } inline int HostMem::type() const { return CV_MAT_TYPE(flags); } inline int HostMem::depth() const { return CV_MAT_DEPTH(flags); } inline int HostMem::channels() const { return CV_MAT_CN(flags); } inline size_t HostMem::step1() const { return step / elemSize1(); } inline Size HostMem::size() const { return Size(cols, rows); } inline bool HostMem::empty() const { return data == 0; } static inline void swap(HostMem& a, HostMem& b) { a.swap(b); } //=================================================================================== // Stream //=================================================================================== inline Stream::Stream(const Ptr& impl) : impl_(impl) { } //=================================================================================== // Event //=================================================================================== inline Event::Event(const Ptr& impl) : impl_(impl) { } //=================================================================================== // Initialization & Info //=================================================================================== inline bool TargetArchs::has(int major, int minor) { return hasPtx(major, minor) || hasBin(major, minor); } inline bool TargetArchs::hasEqualOrGreater(int major, int minor) { return hasEqualOrGreaterPtx(major, minor) || hasEqualOrGreaterBin(major, minor); } inline DeviceInfo::DeviceInfo() { device_id_ = getDevice(); } inline DeviceInfo::DeviceInfo(int device_id) { CV_Assert( device_id >= 0 && device_id < getCudaEnabledDeviceCount() ); device_id_ = device_id; } inline int DeviceInfo::deviceID() const { return device_id_; } inline size_t DeviceInfo::freeMemory() const { size_t _totalMemory = 0, _freeMemory = 0; queryMemory(_totalMemory, _freeMemory); return _freeMemory; } inline size_t DeviceInfo::totalMemory() const { size_t _totalMemory = 0, _freeMemory = 0; queryMemory(_totalMemory, _freeMemory); return _totalMemory; } inline bool DeviceInfo::supports(FeatureSet feature_set) const { int version = majorVersion() * 10 + minorVersion(); return version >= feature_set; } }} // namespace cv { namespace cuda { //=================================================================================== // Mat //=================================================================================== namespace cv { inline Mat::Mat(const cuda::GpuMat& m) : flags(0), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { m.download(*this); } } //! @endcond #endif // __OPENCV_CORE_CUDAINL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda_stream_accessor.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP__ #define __OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP__ #ifndef __cplusplus # error cuda_stream_accessor.hpp header must be compiled as C++ #endif /** @file cuda_stream_accessor.hpp * This is only header file that depends on CUDA Runtime API. All other headers are independent. */ #include #include "opencv2/core/cuda.hpp" namespace cv { namespace cuda { //! @addtogroup cudacore_struct //! @{ /** @brief Class that enables getting cudaStream_t from cuda::Stream */ struct StreamAccessor { CV_EXPORTS static cudaStream_t getStream(const Stream& stream); CV_EXPORTS static Stream wrapStream(cudaStream_t stream); }; /** @brief Class that enables getting cudaEvent_t from cuda::Event */ struct EventAccessor { CV_EXPORTS static cudaEvent_t getEvent(const Event& event); CV_EXPORTS static Event wrapEvent(cudaEvent_t event); }; //! @} } } #endif /* __OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cuda_types.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_CUDA_TYPES_HPP__ #define __OPENCV_CORE_CUDA_TYPES_HPP__ #ifndef __cplusplus # error cuda_types.hpp header must be compiled as C++ #endif /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED #ifdef __CUDACC__ #define __CV_CUDA_HOST_DEVICE__ __host__ __device__ __forceinline__ #else #define __CV_CUDA_HOST_DEVICE__ #endif namespace cv { namespace cuda { // Simple lightweight structures that encapsulates information about an image on device. // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile template struct DevPtr { typedef T elem_type; typedef int index_type; enum { elem_size = sizeof(elem_type) }; T* data; __CV_CUDA_HOST_DEVICE__ DevPtr() : data(0) {} __CV_CUDA_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} __CV_CUDA_HOST_DEVICE__ size_t elemSize() const { return elem_size; } __CV_CUDA_HOST_DEVICE__ operator T*() { return data; } __CV_CUDA_HOST_DEVICE__ operator const T*() const { return data; } }; template struct PtrSz : public DevPtr { __CV_CUDA_HOST_DEVICE__ PtrSz() : size(0) {} __CV_CUDA_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr(data_), size(size_) {} size_t size; }; template struct PtrStep : public DevPtr { __CV_CUDA_HOST_DEVICE__ PtrStep() : step(0) {} __CV_CUDA_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr(data_), step(step_) {} size_t step; __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)DevPtr::data + y * step); } __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)DevPtr::data + y * step); } __CV_CUDA_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } __CV_CUDA_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } }; template struct PtrStepSz : public PtrStep { __CV_CUDA_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} __CV_CUDA_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) : PtrStep(data_, step_), cols(cols_), rows(rows_) {} template explicit PtrStepSz(const PtrStepSz& d) : PtrStep((T*)d.data, d.step), cols(d.cols), rows(d.rows){} int cols; int rows; }; typedef PtrStepSz PtrStepSzb; typedef PtrStepSz PtrStepSzf; typedef PtrStepSz PtrStepSzi; typedef PtrStep PtrStepb; typedef PtrStep PtrStepf; typedef PtrStep PtrStepi; } } //! @endcond #endif /* __OPENCV_CORE_CUDA_TYPES_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cvdef.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_CVDEF_H__ #define __OPENCV_CORE_CVDEF_H__ //! @addtogroup core_utils //! @{ #if !defined _CRT_SECURE_NO_DEPRECATE && defined _MSC_VER && _MSC_VER > 1300 # define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio warnings */ #endif // undef problematic defines sometimes defined by system headers (windows.h in particular) #undef small #undef min #undef max #undef abs #undef Complex #if !defined _CRT_SECURE_NO_DEPRECATE && defined _MSC_VER && _MSC_VER > 1300 # define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio warnings */ #endif #include #include "opencv2/core/hal/interface.h" #if defined __ICL # define CV_ICC __ICL #elif defined __ICC # define CV_ICC __ICC #elif defined __ECL # define CV_ICC __ECL #elif defined __ECC # define CV_ICC __ECC #elif defined __INTEL_COMPILER # define CV_ICC __INTEL_COMPILER #endif #ifndef CV_INLINE # if defined __cplusplus # define CV_INLINE static inline # elif defined _MSC_VER # define CV_INLINE __inline # else # define CV_INLINE static # endif #endif #if defined CV_ICC && !defined CV_ENABLE_UNROLLED # define CV_ENABLE_UNROLLED 0 #else # define CV_ENABLE_UNROLLED 1 #endif #ifdef __GNUC__ # define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) #elif defined _MSC_VER # define CV_DECL_ALIGNED(x) __declspec(align(x)) #else # define CV_DECL_ALIGNED(x) #endif /* CPU features and intrinsics support */ #define CV_CPU_NONE 0 #define CV_CPU_MMX 1 #define CV_CPU_SSE 2 #define CV_CPU_SSE2 3 #define CV_CPU_SSE3 4 #define CV_CPU_SSSE3 5 #define CV_CPU_SSE4_1 6 #define CV_CPU_SSE4_2 7 #define CV_CPU_POPCNT 8 #define CV_CPU_AVX 10 #define CV_CPU_AVX2 11 #define CV_CPU_FMA3 12 #define CV_CPU_AVX_512F 13 #define CV_CPU_AVX_512BW 14 #define CV_CPU_AVX_512CD 15 #define CV_CPU_AVX_512DQ 16 #define CV_CPU_AVX_512ER 17 #define CV_CPU_AVX_512IFMA512 18 #define CV_CPU_AVX_512PF 19 #define CV_CPU_AVX_512VBMI 20 #define CV_CPU_AVX_512VL 21 #define CV_CPU_NEON 100 // when adding to this list remember to update the following enum #define CV_HARDWARE_MAX_FEATURE 255 /** @brief Available CPU features. */ enum CpuFeatures { CPU_MMX = 1, CPU_SSE = 2, CPU_SSE2 = 3, CPU_SSE3 = 4, CPU_SSSE3 = 5, CPU_SSE4_1 = 6, CPU_SSE4_2 = 7, CPU_POPCNT = 8, CPU_AVX = 10, CPU_AVX2 = 11, CPU_FMA3 = 12, CPU_AVX_512F = 13, CPU_AVX_512BW = 14, CPU_AVX_512CD = 15, CPU_AVX_512DQ = 16, CPU_AVX_512ER = 17, CPU_AVX_512IFMA512 = 18, CPU_AVX_512PF = 19, CPU_AVX_512VBMI = 20, CPU_AVX_512VL = 21, CPU_NEON = 100 }; // do not include SSE/AVX/NEON headers for NVCC compiler #ifndef __CUDACC__ #if defined __SSE2__ || defined _M_X64 || (defined _M_IX86_FP && _M_IX86_FP >= 2) # include # define CV_MMX 1 # define CV_SSE 1 # define CV_SSE2 1 # if defined __SSE3__ || (defined _MSC_VER && _MSC_VER >= 1500) # include # define CV_SSE3 1 # endif # if defined __SSSE3__ || (defined _MSC_VER && _MSC_VER >= 1500) # include # define CV_SSSE3 1 # endif # if defined __SSE4_1__ || (defined _MSC_VER && _MSC_VER >= 1500) # include # define CV_SSE4_1 1 # endif # if defined __SSE4_2__ || (defined _MSC_VER && _MSC_VER >= 1500) # include # define CV_SSE4_2 1 # endif # if defined __POPCNT__ || (defined _MSC_VER && _MSC_VER >= 1500) # ifdef _MSC_VER # include # else # include # endif # define CV_POPCNT 1 # endif # if defined __AVX__ || (defined _MSC_VER && _MSC_VER >= 1600 && 0) // MS Visual Studio 2010 (2012?) has no macro pre-defined to identify the use of /arch:AVX // See: http://connect.microsoft.com/VisualStudio/feedback/details/605858/arch-avx-should-define-a-predefined-macro-in-x64-and-set-a-unique-value-for-m-ix86-fp-in-win32 # include # define CV_AVX 1 # if defined(_XCR_XFEATURE_ENABLED_MASK) # define __xgetbv() _xgetbv(_XCR_XFEATURE_ENABLED_MASK) # else # define __xgetbv() 0 # endif # endif # if defined __AVX2__ || (defined _MSC_VER && _MSC_VER >= 1800 && 0) # include # define CV_AVX2 1 # if defined __FMA__ # define CV_FMA3 1 # endif # endif #endif #if (defined WIN32 || defined _WIN32) && defined(_M_ARM) # include # include "arm_neon.h" # define CV_NEON 1 # define CPU_HAS_NEON_FEATURE (true) #elif defined(__ARM_NEON__) || (defined (__ARM_NEON) && defined(__aarch64__)) # include # define CV_NEON 1 #endif #if defined __GNUC__ && defined __arm__ && (defined __ARM_PCS_VFP || defined __ARM_VFPV3__ || defined __ARM_NEON__) && !defined __SOFTFP__ # define CV_VFP 1 #endif #endif // __CUDACC__ #ifndef CV_POPCNT #define CV_POPCNT 0 #endif #ifndef CV_MMX # define CV_MMX 0 #endif #ifndef CV_SSE # define CV_SSE 0 #endif #ifndef CV_SSE2 # define CV_SSE2 0 #endif #ifndef CV_SSE3 # define CV_SSE3 0 #endif #ifndef CV_SSSE3 # define CV_SSSE3 0 #endif #ifndef CV_SSE4_1 # define CV_SSE4_1 0 #endif #ifndef CV_SSE4_2 # define CV_SSE4_2 0 #endif #ifndef CV_AVX # define CV_AVX 0 #endif #ifndef CV_AVX2 # define CV_AVX2 0 #endif #ifndef CV_FMA3 # define CV_FMA3 0 #endif #ifndef CV_AVX_512F # define CV_AVX_512F 0 #endif #ifndef CV_AVX_512BW # define CV_AVX_512BW 0 #endif #ifndef CV_AVX_512CD # define CV_AVX_512CD 0 #endif #ifndef CV_AVX_512DQ # define CV_AVX_512DQ 0 #endif #ifndef CV_AVX_512ER # define CV_AVX_512ER 0 #endif #ifndef CV_AVX_512IFMA512 # define CV_AVX_512IFMA512 0 #endif #ifndef CV_AVX_512PF # define CV_AVX_512PF 0 #endif #ifndef CV_AVX_512VBMI # define CV_AVX_512VBMI 0 #endif #ifndef CV_AVX_512VL # define CV_AVX_512VL 0 #endif #ifndef CV_NEON # define CV_NEON 0 #endif #ifndef CV_VFP # define CV_VFP 0 #endif /* fundamental constants */ #define CV_PI 3.1415926535897932384626433832795 #define CV_2PI 6.283185307179586476925286766559 #define CV_LOG2 0.69314718055994530941723212145818 typedef union Cv32suf { int i; unsigned u; float f; } Cv32suf; typedef union Cv64suf { int64 i; uint64 u; double f; } Cv64suf; #define OPENCV_ABI_COMPATIBILITY 300 #ifdef __OPENCV_BUILD # define DISABLE_OPENCV_24_COMPATIBILITY #endif #if (defined WIN32 || defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined CVAPI_EXPORTS # define CV_EXPORTS __declspec(dllexport) #elif defined __GNUC__ && __GNUC__ >= 4 # define CV_EXPORTS __attribute__ ((visibility ("default"))) #else # define CV_EXPORTS #endif #ifndef CV_EXTERN_C # ifdef __cplusplus # define CV_EXTERN_C extern "C" # else # define CV_EXTERN_C # endif #endif /* special informative macros for wrapper generators */ #define CV_EXPORTS_W CV_EXPORTS #define CV_EXPORTS_W_SIMPLE CV_EXPORTS #define CV_EXPORTS_AS(synonym) CV_EXPORTS #define CV_EXPORTS_W_MAP CV_EXPORTS #define CV_IN_OUT #define CV_OUT #define CV_PROP #define CV_PROP_RW #define CV_WRAP #define CV_WRAP_AS(synonym) /****************************************************************************************\ * Matrix type (Mat) * \****************************************************************************************/ #define CV_CN_MAX 512 #define CV_CN_SHIFT 3 #define CV_DEPTH_MAX (1 << CV_CN_SHIFT) #define CV_8U 0 #define CV_8S 1 #define CV_16U 2 #define CV_16S 3 #define CV_32S 4 #define CV_32F 5 #define CV_64F 6 #define CV_USRTYPE1 7 #define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) #define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) #define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) #define CV_MAKE_TYPE CV_MAKETYPE #define CV_8UC1 CV_MAKETYPE(CV_8U,1) #define CV_8UC2 CV_MAKETYPE(CV_8U,2) #define CV_8UC3 CV_MAKETYPE(CV_8U,3) #define CV_8UC4 CV_MAKETYPE(CV_8U,4) #define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) #define CV_8SC1 CV_MAKETYPE(CV_8S,1) #define CV_8SC2 CV_MAKETYPE(CV_8S,2) #define CV_8SC3 CV_MAKETYPE(CV_8S,3) #define CV_8SC4 CV_MAKETYPE(CV_8S,4) #define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) #define CV_16UC1 CV_MAKETYPE(CV_16U,1) #define CV_16UC2 CV_MAKETYPE(CV_16U,2) #define CV_16UC3 CV_MAKETYPE(CV_16U,3) #define CV_16UC4 CV_MAKETYPE(CV_16U,4) #define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) #define CV_16SC1 CV_MAKETYPE(CV_16S,1) #define CV_16SC2 CV_MAKETYPE(CV_16S,2) #define CV_16SC3 CV_MAKETYPE(CV_16S,3) #define CV_16SC4 CV_MAKETYPE(CV_16S,4) #define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) #define CV_32SC1 CV_MAKETYPE(CV_32S,1) #define CV_32SC2 CV_MAKETYPE(CV_32S,2) #define CV_32SC3 CV_MAKETYPE(CV_32S,3) #define CV_32SC4 CV_MAKETYPE(CV_32S,4) #define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) #define CV_32FC1 CV_MAKETYPE(CV_32F,1) #define CV_32FC2 CV_MAKETYPE(CV_32F,2) #define CV_32FC3 CV_MAKETYPE(CV_32F,3) #define CV_32FC4 CV_MAKETYPE(CV_32F,4) #define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) #define CV_64FC1 CV_MAKETYPE(CV_64F,1) #define CV_64FC2 CV_MAKETYPE(CV_64F,2) #define CV_64FC3 CV_MAKETYPE(CV_64F,3) #define CV_64FC4 CV_MAKETYPE(CV_64F,4) #define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) #define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) #define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) #define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) #define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) #define CV_MAT_CONT_FLAG_SHIFT 14 #define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) #define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) #define CV_IS_CONT_MAT CV_IS_MAT_CONT #define CV_SUBMAT_FLAG_SHIFT 15 #define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) #define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) /** Size of each channel item, 0x124489 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ #define CV_ELEM_SIZE1(type) \ ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15) /** 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */ #define CV_ELEM_SIZE(type) \ (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3)) #ifndef MIN # define MIN(a,b) ((a) > (b) ? (b) : (a)) #endif #ifndef MAX # define MAX(a,b) ((a) < (b) ? (b) : (a)) #endif /****************************************************************************************\ * exchange-add operation for atomic operations on reference counters * \****************************************************************************************/ #if defined __INTEL_COMPILER && !(defined WIN32 || defined _WIN32) // atomic increment on the linux version of the Intel(tm) compiler # define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd(const_cast(reinterpret_cast(addr)), delta) #elif defined __GNUC__ # if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__ && !defined __EMSCRIPTEN__ && !defined(__CUDACC__) # ifdef __ATOMIC_ACQ_REL # define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), delta, __ATOMIC_ACQ_REL) # else # define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), delta, 4) # endif # else # if defined __ATOMIC_ACQ_REL && !defined __clang__ // version for gcc >= 4.7 # define CV_XADD(addr, delta) (int)__atomic_fetch_add((unsigned*)(addr), (unsigned)(delta), __ATOMIC_ACQ_REL) # else # define CV_XADD(addr, delta) (int)__sync_fetch_and_add((unsigned*)(addr), (unsigned)(delta)) # endif # endif #elif defined _MSC_VER && !defined RC_INVOKED # include # define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd((long volatile*)addr, delta) #else CV_INLINE CV_XADD(int* addr, int delta) { int tmp = *addr; *addr += delta; return tmp; } #endif /****************************************************************************************\ * CV_NORETURN attribute * \****************************************************************************************/ #ifndef CV_NORETURN # if defined(__GNUC__) # define CV_NORETURN __attribute__((__noreturn__)) # elif defined(_MSC_VER) && (_MSC_VER >= 1300) # define CV_NORETURN __declspec(noreturn) # else # define CV_NORETURN /* nothing by default */ # endif #endif /****************************************************************************************\ * C++ Move semantics * \****************************************************************************************/ #ifndef CV_CXX_MOVE_SEMANTICS # if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || defined(_MSC_VER) && _MSC_VER >= 1600 # define CV_CXX_MOVE_SEMANTICS 1 # elif defined(__clang) # if __has_feature(cxx_rvalue_references) # define CV_CXX_MOVE_SEMANTICS 1 # endif # endif #else # if CV_CXX_MOVE_SEMANTICS == 0 # undef CV_CXX_MOVE_SEMANTICS # endif #endif //! @} #endif // __OPENCV_CORE_CVDEF_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cvstd.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_CVSTD_HPP__ #define __OPENCV_CORE_CVSTD_HPP__ #ifndef __cplusplus # error cvstd.hpp header must be compiled as C++ #endif #include "opencv2/core/cvdef.h" #include #include #include #ifndef OPENCV_NOSTL # include #endif // import useful primitives from stl #ifndef OPENCV_NOSTL_TRANSITIONAL # include # include # include //for abs(int) # include namespace cv { using std::min; using std::max; using std::abs; using std::swap; using std::sqrt; using std::exp; using std::pow; using std::log; } namespace std { static inline uchar abs(uchar a) { return a; } static inline ushort abs(ushort a) { return a; } static inline unsigned abs(unsigned a) { return a; } static inline uint64 abs(uint64 a) { return a; } } #else namespace cv { template static inline T min(T a, T b) { return a < b ? a : b; } template static inline T max(T a, T b) { return a > b ? a : b; } template static inline T abs(T a) { return a < 0 ? -a : a; } template static inline void swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template<> inline uchar abs(uchar a) { return a; } template<> inline ushort abs(ushort a) { return a; } template<> inline unsigned abs(unsigned a) { return a; } template<> inline uint64 abs(uint64 a) { return a; } } #endif namespace cv { //! @addtogroup core_utils //! @{ //////////////////////////// memory management functions //////////////////////////// /** @brief Allocates an aligned memory buffer. The function allocates the buffer of the specified size and returns it. When the buffer size is 16 bytes or more, the returned buffer is aligned to 16 bytes. @param bufSize Allocated buffer size. */ CV_EXPORTS void* fastMalloc(size_t bufSize); /** @brief Deallocates a memory buffer. The function deallocates the buffer allocated with fastMalloc . If NULL pointer is passed, the function does nothing. C version of the function clears the pointer *pptr* to avoid problems with double memory deallocation. @param ptr Pointer to the allocated buffer. */ CV_EXPORTS void fastFree(void* ptr); /*! The STL-compilant memory Allocator based on cv::fastMalloc() and cv::fastFree() */ template class Allocator { public: typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; template class rebind { typedef Allocator other; }; explicit Allocator() {} ~Allocator() {} explicit Allocator(Allocator const&) {} template explicit Allocator(Allocator const&) {} // address pointer address(reference r) { return &r; } const_pointer address(const_reference r) { return &r; } pointer allocate(size_type count, const void* =0) { return reinterpret_cast(fastMalloc(count * sizeof (_Tp))); } void deallocate(pointer p, size_type) { fastFree(p); } void construct(pointer p, const _Tp& v) { new(static_cast(p)) _Tp(v); } void destroy(pointer p) { p->~_Tp(); } size_type max_size() const { return cv::max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); } }; //! @} core_utils //! @cond IGNORED namespace detail { // Metafunction to avoid taking a reference to void. template struct RefOrVoid { typedef T& type; }; template<> struct RefOrVoid{ typedef void type; }; template<> struct RefOrVoid{ typedef const void type; }; template<> struct RefOrVoid{ typedef volatile void type; }; template<> struct RefOrVoid{ typedef const volatile void type; }; // This class would be private to Ptr, if it didn't have to be a non-template. struct PtrOwner; } template struct DefaultDeleter { void operator () (Y* p) const; }; //! @endcond //! @addtogroup core_basic //! @{ /** @brief Template class for smart pointers with shared ownership A Ptr\ pretends to be a pointer to an object of type T. Unlike an ordinary pointer, however, the object will be automatically cleaned up once all Ptr instances pointing to it are destroyed. Ptr is similar to boost::shared_ptr that is part of the Boost library () and std::shared_ptr from the [C++11](http://en.wikipedia.org/wiki/C++11) standard. This class provides the following advantages: - Default constructor, copy constructor, and assignment operator for an arbitrary C++ class or C structure. For some objects, like files, windows, mutexes, sockets, and others, a copy constructor or an assignment operator are difficult to define. For some other objects, like complex classifiers in OpenCV, copy constructors are absent and not easy to implement. Finally, some of complex OpenCV and your own data structures may be written in C. However, copy constructors and default constructors can simplify programming a lot. Besides, they are often required (for example, by STL containers). By using a Ptr to such an object instead of the object itself, you automatically get all of the necessary constructors and the assignment operator. - *O(1)* complexity of the above-mentioned operations. While some structures, like std::vector, provide a copy constructor and an assignment operator, the operations may take a considerable amount of time if the data structures are large. But if the structures are put into a Ptr, the overhead is small and independent of the data size. - Automatic and customizable cleanup, even for C structures. See the example below with FILE\*. - Heterogeneous collections of objects. The standard STL and most other C++ and OpenCV containers can store only objects of the same type and the same size. The classical solution to store objects of different types in the same container is to store pointers to the base class (Base\*) instead but then you lose the automatic memory management. Again, by using Ptr\ instead of raw pointers, you can solve the problem. A Ptr is said to *own* a pointer - that is, for each Ptr there is a pointer that will be deleted once all Ptr instances that own it are destroyed. The owned pointer may be null, in which case nothing is deleted. Each Ptr also *stores* a pointer. The stored pointer is the pointer the Ptr pretends to be; that is, the one you get when you use Ptr::get or the conversion to T\*. It's usually the same as the owned pointer, but if you use casts or the general shared-ownership constructor, the two may diverge: the Ptr will still own the original pointer, but will itself point to something else. The owned pointer is treated as a black box. The only thing Ptr needs to know about it is how to delete it. This knowledge is encapsulated in the *deleter* - an auxiliary object that is associated with the owned pointer and shared between all Ptr instances that own it. The default deleter is an instance of DefaultDeleter, which uses the standard C++ delete operator; as such it will work with any pointer allocated with the standard new operator. However, if the pointer must be deleted in a different way, you must specify a custom deleter upon Ptr construction. A deleter is simply a callable object that accepts the pointer as its sole argument. For example, if you want to wrap FILE, you may do so as follows: @code Ptr f(fopen("myfile.txt", "w"), fclose); if(!f) throw ...; fprintf(f, ....); ... // the file will be closed automatically by f's destructor. @endcode Alternatively, if you want all pointers of a particular type to be deleted the same way, you can specialize DefaultDeleter::operator() for that type, like this: @code namespace cv { template<> void DefaultDeleter::operator ()(FILE * obj) const { fclose(obj); } } @endcode For convenience, the following types from the OpenCV C API already have such a specialization that calls the appropriate release function: - CvCapture - CvFileStorage - CvHaarClassifierCascade - CvMat - CvMatND - CvMemStorage - CvSparseMat - CvVideoWriter - IplImage @note The shared ownership mechanism is implemented with reference counting. As such, cyclic ownership (e.g. when object a contains a Ptr to object b, which contains a Ptr to object a) will lead to all involved objects never being cleaned up. Avoid such situations. @note It is safe to concurrently read (but not write) a Ptr instance from multiple threads and therefore it is normally safe to use it in multi-threaded applications. The same is true for Mat and other C++ OpenCV classes that use internal reference counts. */ template struct Ptr { /** Generic programming support. */ typedef T element_type; /** The default constructor creates a null Ptr - one that owns and stores a null pointer. */ Ptr(); /** If p is null, these are equivalent to the default constructor. Otherwise, these constructors assume ownership of p - that is, the created Ptr owns and stores p and assumes it is the sole owner of it. Don't use them if p is already owned by another Ptr, or else p will get deleted twice. With the first constructor, DefaultDeleter\() becomes the associated deleter (so p will eventually be deleted with the standard delete operator). Y must be a complete type at the point of invocation. With the second constructor, d becomes the associated deleter. Y\* must be convertible to T\*. @param p Pointer to own. @note It is often easier to use makePtr instead. */ template #ifdef DISABLE_OPENCV_24_COMPATIBILITY explicit #endif Ptr(Y* p); /** @overload @param d Deleter to use for the owned pointer. @param p Pointer to own. */ template Ptr(Y* p, D d); /** These constructors create a Ptr that shares ownership with another Ptr - that is, own the same pointer as o. With the first two, the same pointer is stored, as well; for the second, Y\* must be convertible to T\*. With the third, p is stored, and Y may be any type. This constructor allows to have completely unrelated owned and stored pointers, and should be used with care to avoid confusion. A relatively benign use is to create a non-owning Ptr, like this: @code ptr = Ptr(Ptr(), dont_delete_me); // owns nothing; will not delete the pointer. @endcode @param o Ptr to share ownership with. */ Ptr(const Ptr& o); /** @overload @param o Ptr to share ownership with. */ template Ptr(const Ptr& o); /** @overload @param o Ptr to share ownership with. @param p Pointer to store. */ template Ptr(const Ptr& o, T* p); /** The destructor is equivalent to calling Ptr::release. */ ~Ptr(); /** Assignment replaces the current Ptr instance with one that owns and stores same pointers as o and then destroys the old instance. @param o Ptr to share ownership with. */ Ptr& operator = (const Ptr& o); /** @overload */ template Ptr& operator = (const Ptr& o); /** If no other Ptr instance owns the owned pointer, deletes it with the associated deleter. Then sets both the owned and the stored pointers to NULL. */ void release(); /** `ptr.reset(...)` is equivalent to `ptr = Ptr(...)`. @param p Pointer to own. */ template void reset(Y* p); /** @overload @param d Deleter to use for the owned pointer. @param p Pointer to own. */ template void reset(Y* p, D d); /** Swaps the owned and stored pointers (and deleters, if any) of this and o. @param o Ptr to swap with. */ void swap(Ptr& o); /** Returns the stored pointer. */ T* get() const; /** Ordinary pointer emulation. */ typename detail::RefOrVoid::type operator * () const; /** Ordinary pointer emulation. */ T* operator -> () const; /** Equivalent to get(). */ operator T* () const; /** ptr.empty() is equivalent to `!ptr.get()`. */ bool empty() const; /** Returns a Ptr that owns the same pointer as this, and stores the same pointer as this, except converted via static_cast to Y*. */ template Ptr staticCast() const; /** Ditto for const_cast. */ template Ptr constCast() const; /** Ditto for dynamic_cast. */ template Ptr dynamicCast() const; #ifdef CV_CXX_MOVE_SEMANTICS Ptr(Ptr&& o); Ptr& operator = (Ptr&& o); #endif private: detail::PtrOwner* owner; T* stored; template friend struct Ptr; // have to do this for the cross-type copy constructor }; /** Equivalent to ptr1.swap(ptr2). Provided to help write generic algorithms. */ template void swap(Ptr& ptr1, Ptr& ptr2); /** Return whether ptr1.get() and ptr2.get() are equal and not equal, respectively. */ template bool operator == (const Ptr& ptr1, const Ptr& ptr2); template bool operator != (const Ptr& ptr1, const Ptr& ptr2); /** `makePtr(...)` is equivalent to `Ptr(new T(...))`. It is shorter than the latter, and it's marginally safer than using a constructor or Ptr::reset, since it ensures that the owned pointer is new and thus not owned by any other Ptr instance. Unfortunately, perfect forwarding is impossible to implement in C++03, and so makePtr is limited to constructors of T that have up to 10 arguments, none of which are non-const references. */ template Ptr makePtr(); /** @overload */ template Ptr makePtr(const A1& a1); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9); /** @overload */ template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10); //////////////////////////////// string class //////////////////////////////// class CV_EXPORTS FileNode; //for string constructor from FileNode class CV_EXPORTS String { public: typedef char value_type; typedef char& reference; typedef const char& const_reference; typedef char* pointer; typedef const char* const_pointer; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef char* iterator; typedef const char* const_iterator; static const size_t npos = size_t(-1); explicit String(); String(const String& str); String(const String& str, size_t pos, size_t len = npos); String(const char* s); String(const char* s, size_t n); String(size_t n, char c); String(const char* first, const char* last); template String(Iterator first, Iterator last); explicit String(const FileNode& fn); ~String(); String& operator=(const String& str); String& operator=(const char* s); String& operator=(char c); String& operator+=(const String& str); String& operator+=(const char* s); String& operator+=(char c); size_t size() const; size_t length() const; char operator[](size_t idx) const; char operator[](int idx) const; const char* begin() const; const char* end() const; const char* c_str() const; bool empty() const; void clear(); int compare(const char* s) const; int compare(const String& str) const; void swap(String& str); String substr(size_t pos = 0, size_t len = npos) const; size_t find(const char* s, size_t pos, size_t n) const; size_t find(char c, size_t pos = 0) const; size_t find(const String& str, size_t pos = 0) const; size_t find(const char* s, size_t pos = 0) const; size_t rfind(const char* s, size_t pos, size_t n) const; size_t rfind(char c, size_t pos = npos) const; size_t rfind(const String& str, size_t pos = npos) const; size_t rfind(const char* s, size_t pos = npos) const; size_t find_first_of(const char* s, size_t pos, size_t n) const; size_t find_first_of(char c, size_t pos = 0) const; size_t find_first_of(const String& str, size_t pos = 0) const; size_t find_first_of(const char* s, size_t pos = 0) const; size_t find_last_of(const char* s, size_t pos, size_t n) const; size_t find_last_of(char c, size_t pos = npos) const; size_t find_last_of(const String& str, size_t pos = npos) const; size_t find_last_of(const char* s, size_t pos = npos) const; friend String operator+ (const String& lhs, const String& rhs); friend String operator+ (const String& lhs, const char* rhs); friend String operator+ (const char* lhs, const String& rhs); friend String operator+ (const String& lhs, char rhs); friend String operator+ (char lhs, const String& rhs); String toLowerCase() const; #ifndef OPENCV_NOSTL String(const std::string& str); String(const std::string& str, size_t pos, size_t len = npos); String& operator=(const std::string& str); String& operator+=(const std::string& str); operator std::string() const; friend String operator+ (const String& lhs, const std::string& rhs); friend String operator+ (const std::string& lhs, const String& rhs); #endif private: char* cstr_; size_t len_; char* allocate(size_t len); // len without trailing 0 void deallocate(); String(int); // disabled and invalid. Catch invalid usages like, commandLineParser.has(0) problem }; //! @} core_basic ////////////////////////// cv::String implementation ///////////////////////// //! @cond IGNORED inline String::String() : cstr_(0), len_(0) {} inline String::String(const String& str) : cstr_(str.cstr_), len_(str.len_) { if (cstr_) CV_XADD(((int*)cstr_)-1, 1); } inline String::String(const String& str, size_t pos, size_t len) : cstr_(0), len_(0) { pos = min(pos, str.len_); len = min(str.len_ - pos, len); if (!len) return; if (len == str.len_) { CV_XADD(((int*)str.cstr_)-1, 1); cstr_ = str.cstr_; len_ = str.len_; return; } memcpy(allocate(len), str.cstr_ + pos, len); } inline String::String(const char* s) : cstr_(0), len_(0) { if (!s) return; size_t len = strlen(s); memcpy(allocate(len), s, len); } inline String::String(const char* s, size_t n) : cstr_(0), len_(0) { if (!n) return; memcpy(allocate(n), s, n); } inline String::String(size_t n, char c) : cstr_(0), len_(0) { memset(allocate(n), c, n); } inline String::String(const char* first, const char* last) : cstr_(0), len_(0) { size_t len = (size_t)(last - first); memcpy(allocate(len), first, len); } template inline String::String(Iterator first, Iterator last) : cstr_(0), len_(0) { size_t len = (size_t)(last - first); char* str = allocate(len); while (first != last) { *str++ = *first; ++first; } } inline String::~String() { deallocate(); } inline String& String::operator=(const String& str) { if (&str == this) return *this; deallocate(); if (str.cstr_) CV_XADD(((int*)str.cstr_)-1, 1); cstr_ = str.cstr_; len_ = str.len_; return *this; } inline String& String::operator=(const char* s) { deallocate(); if (!s) return *this; size_t len = strlen(s); memcpy(allocate(len), s, len); return *this; } inline String& String::operator=(char c) { deallocate(); allocate(1)[0] = c; return *this; } inline String& String::operator+=(const String& str) { *this = *this + str; return *this; } inline String& String::operator+=(const char* s) { *this = *this + s; return *this; } inline String& String::operator+=(char c) { *this = *this + c; return *this; } inline size_t String::size() const { return len_; } inline size_t String::length() const { return len_; } inline char String::operator[](size_t idx) const { return cstr_[idx]; } inline char String::operator[](int idx) const { return cstr_[idx]; } inline const char* String::begin() const { return cstr_; } inline const char* String::end() const { return len_ ? cstr_ + 1 : 0; } inline bool String::empty() const { return len_ == 0; } inline const char* String::c_str() const { return cstr_ ? cstr_ : ""; } inline void String::swap(String& str) { cv::swap(cstr_, str.cstr_); cv::swap(len_, str.len_); } inline void String::clear() { deallocate(); } inline int String::compare(const char* s) const { if (cstr_ == s) return 0; return strcmp(c_str(), s); } inline int String::compare(const String& str) const { if (cstr_ == str.cstr_) return 0; return strcmp(c_str(), str.c_str()); } inline String String::substr(size_t pos, size_t len) const { return String(*this, pos, len); } inline size_t String::find(const char* s, size_t pos, size_t n) const { if (n == 0 || pos + n > len_) return npos; const char* lmax = cstr_ + len_ - n; for (const char* i = cstr_ + pos; i <= lmax; ++i) { size_t j = 0; while (j < n && s[j] == i[j]) ++j; if (j == n) return (size_t)(i - cstr_); } return npos; } inline size_t String::find(char c, size_t pos) const { return find(&c, pos, 1); } inline size_t String::find(const String& str, size_t pos) const { return find(str.c_str(), pos, str.len_); } inline size_t String::find(const char* s, size_t pos) const { if (pos >= len_ || !s[0]) return npos; const char* lmax = cstr_ + len_; for (const char* i = cstr_ + pos; i < lmax; ++i) { size_t j = 0; while (s[j] && s[j] == i[j]) { if(i + j >= lmax) return npos; ++j; } if (!s[j]) return (size_t)(i - cstr_); } return npos; } inline size_t String::rfind(const char* s, size_t pos, size_t n) const { if (n > len_) return npos; if (pos > len_ - n) pos = len_ - n; for (const char* i = cstr_ + pos; i >= cstr_; --i) { size_t j = 0; while (j < n && s[j] == i[j]) ++j; if (j == n) return (size_t)(i - cstr_); } return npos; } inline size_t String::rfind(char c, size_t pos) const { return rfind(&c, pos, 1); } inline size_t String::rfind(const String& str, size_t pos) const { return rfind(str.c_str(), pos, str.len_); } inline size_t String::rfind(const char* s, size_t pos) const { return rfind(s, pos, strlen(s)); } inline size_t String::find_first_of(const char* s, size_t pos, size_t n) const { if (n == 0 || pos + n > len_) return npos; const char* lmax = cstr_ + len_; for (const char* i = cstr_ + pos; i < lmax; ++i) { for (size_t j = 0; j < n; ++j) if (s[j] == *i) return (size_t)(i - cstr_); } return npos; } inline size_t String::find_first_of(char c, size_t pos) const { return find_first_of(&c, pos, 1); } inline size_t String::find_first_of(const String& str, size_t pos) const { return find_first_of(str.c_str(), pos, str.len_); } inline size_t String::find_first_of(const char* s, size_t pos) const { if (len_ == 0) return npos; if (pos >= len_ || !s[0]) return npos; const char* lmax = cstr_ + len_; for (const char* i = cstr_ + pos; i < lmax; ++i) { for (size_t j = 0; s[j]; ++j) if (s[j] == *i) return (size_t)(i - cstr_); } return npos; } inline size_t String::find_last_of(const char* s, size_t pos, size_t n) const { if (len_ == 0) return npos; if (pos >= len_) pos = len_ - 1; for (const char* i = cstr_ + pos; i >= cstr_; --i) { for (size_t j = 0; j < n; ++j) if (s[j] == *i) return (size_t)(i - cstr_); } return npos; } inline size_t String::find_last_of(char c, size_t pos) const { return find_last_of(&c, pos, 1); } inline size_t String::find_last_of(const String& str, size_t pos) const { return find_last_of(str.c_str(), pos, str.len_); } inline size_t String::find_last_of(const char* s, size_t pos) const { if (len_ == 0) return npos; if (pos >= len_) pos = len_ - 1; for (const char* i = cstr_ + pos; i >= cstr_; --i) { for (size_t j = 0; s[j]; ++j) if (s[j] == *i) return (size_t)(i - cstr_); } return npos; } inline String String::toLowerCase() const { String res(cstr_, len_); for (size_t i = 0; i < len_; ++i) res.cstr_[i] = (char) ::tolower(cstr_[i]); return res; } //! @endcond // ************************* cv::String non-member functions ************************* //! @relates cv::String //! @{ inline String operator + (const String& lhs, const String& rhs) { String s; s.allocate(lhs.len_ + rhs.len_); memcpy(s.cstr_, lhs.cstr_, lhs.len_); memcpy(s.cstr_ + lhs.len_, rhs.cstr_, rhs.len_); return s; } inline String operator + (const String& lhs, const char* rhs) { String s; size_t rhslen = strlen(rhs); s.allocate(lhs.len_ + rhslen); memcpy(s.cstr_, lhs.cstr_, lhs.len_); memcpy(s.cstr_ + lhs.len_, rhs, rhslen); return s; } inline String operator + (const char* lhs, const String& rhs) { String s; size_t lhslen = strlen(lhs); s.allocate(lhslen + rhs.len_); memcpy(s.cstr_, lhs, lhslen); memcpy(s.cstr_ + lhslen, rhs.cstr_, rhs.len_); return s; } inline String operator + (const String& lhs, char rhs) { String s; s.allocate(lhs.len_ + 1); memcpy(s.cstr_, lhs.cstr_, lhs.len_); s.cstr_[lhs.len_] = rhs; return s; } inline String operator + (char lhs, const String& rhs) { String s; s.allocate(rhs.len_ + 1); s.cstr_[0] = lhs; memcpy(s.cstr_ + 1, rhs.cstr_, rhs.len_); return s; } static inline bool operator== (const String& lhs, const String& rhs) { return 0 == lhs.compare(rhs); } static inline bool operator== (const char* lhs, const String& rhs) { return 0 == rhs.compare(lhs); } static inline bool operator== (const String& lhs, const char* rhs) { return 0 == lhs.compare(rhs); } static inline bool operator!= (const String& lhs, const String& rhs) { return 0 != lhs.compare(rhs); } static inline bool operator!= (const char* lhs, const String& rhs) { return 0 != rhs.compare(lhs); } static inline bool operator!= (const String& lhs, const char* rhs) { return 0 != lhs.compare(rhs); } static inline bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; } static inline bool operator< (const char* lhs, const String& rhs) { return rhs.compare(lhs) > 0; } static inline bool operator< (const String& lhs, const char* rhs) { return lhs.compare(rhs) < 0; } static inline bool operator<= (const String& lhs, const String& rhs) { return lhs.compare(rhs) <= 0; } static inline bool operator<= (const char* lhs, const String& rhs) { return rhs.compare(lhs) >= 0; } static inline bool operator<= (const String& lhs, const char* rhs) { return lhs.compare(rhs) <= 0; } static inline bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; } static inline bool operator> (const char* lhs, const String& rhs) { return rhs.compare(lhs) < 0; } static inline bool operator> (const String& lhs, const char* rhs) { return lhs.compare(rhs) > 0; } static inline bool operator>= (const String& lhs, const String& rhs) { return lhs.compare(rhs) >= 0; } static inline bool operator>= (const char* lhs, const String& rhs) { return rhs.compare(lhs) <= 0; } static inline bool operator>= (const String& lhs, const char* rhs) { return lhs.compare(rhs) >= 0; } //! @} relates cv::String } // cv #ifndef OPENCV_NOSTL_TRANSITIONAL namespace std { static inline void swap(cv::String& a, cv::String& b) { a.swap(b); } } #else namespace cv { template<> inline void swap(cv::String& a, cv::String& b) { a.swap(b); } } #endif #include "opencv2/core/ptr.inl.hpp" #endif //__OPENCV_CORE_CVSTD_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/cvstd.inl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_CVSTDINL_HPP__ #define __OPENCV_CORE_CVSTDINL_HPP__ #ifndef OPENCV_NOSTL # include # include #endif //! @cond IGNORED namespace cv { #ifndef OPENCV_NOSTL template class DataType< std::complex<_Tp> > { public: typedef std::complex<_Tp> value_type; typedef value_type work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 2, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; inline String::String(const std::string& str) : cstr_(0), len_(0) { if (!str.empty()) { size_t len = str.size(); memcpy(allocate(len), str.c_str(), len); } } inline String::String(const std::string& str, size_t pos, size_t len) : cstr_(0), len_(0) { size_t strlen = str.size(); pos = min(pos, strlen); len = min(strlen - pos, len); if (!len) return; memcpy(allocate(len), str.c_str() + pos, len); } inline String& String::operator = (const std::string& str) { deallocate(); if (!str.empty()) { size_t len = str.size(); memcpy(allocate(len), str.c_str(), len); } return *this; } inline String& String::operator += (const std::string& str) { *this = *this + str; return *this; } inline String::operator std::string() const { return std::string(cstr_, len_); } inline String operator + (const String& lhs, const std::string& rhs) { String s; size_t rhslen = rhs.size(); s.allocate(lhs.len_ + rhslen); memcpy(s.cstr_, lhs.cstr_, lhs.len_); memcpy(s.cstr_ + lhs.len_, rhs.c_str(), rhslen); return s; } inline String operator + (const std::string& lhs, const String& rhs) { String s; size_t lhslen = lhs.size(); s.allocate(lhslen + rhs.len_); memcpy(s.cstr_, lhs.c_str(), lhslen); memcpy(s.cstr_ + lhslen, rhs.cstr_, rhs.len_); return s; } inline FileNode::operator std::string() const { String value; read(*this, value, value); return value; } template<> inline void operator >> (const FileNode& n, std::string& value) { String val; read(n, val, val); value = val; } template<> inline FileStorage& operator << (FileStorage& fs, const std::string& value) { return fs << cv::String(value); } static inline std::ostream& operator << (std::ostream& os, const String& str) { return os << str.c_str(); } static inline std::ostream& operator << (std::ostream& out, Ptr fmtd) { fmtd->reset(); for(const char* str = fmtd->next(); str; str = fmtd->next()) out << str; return out; } static inline std::ostream& operator << (std::ostream& out, const Mat& mtx) { return out << Formatter::get()->format(mtx); } template static inline std::ostream& operator << (std::ostream& out, const std::vector >& vec) { return out << Formatter::get()->format(Mat(vec)); } template static inline std::ostream& operator << (std::ostream& out, const std::vector >& vec) { return out << Formatter::get()->format(Mat(vec)); } template static inline std::ostream& operator << (std::ostream& out, const Matx<_Tp, m, n>& matx) { return out << Formatter::get()->format(Mat(matx)); } template static inline std::ostream& operator << (std::ostream& out, const Point_<_Tp>& p) { out << "[" << p.x << ", " << p.y << "]"; return out; } template static inline std::ostream& operator << (std::ostream& out, const Point3_<_Tp>& p) { out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; return out; } template static inline std::ostream& operator << (std::ostream& out, const Vec<_Tp, n>& vec) { out << "["; #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable: 4127 ) #endif if(Vec<_Tp, n>::depth < CV_32F) #ifdef _MSC_VER #pragma warning( pop ) #endif { for (int i = 0; i < n - 1; ++i) { out << (int)vec[i] << ", "; } out << (int)vec[n-1] << "]"; } else { for (int i = 0; i < n - 1; ++i) { out << vec[i] << ", "; } out << vec[n-1] << "]"; } return out; } template static inline std::ostream& operator << (std::ostream& out, const Size_<_Tp>& size) { return out << "[" << size.width << " x " << size.height << "]"; } template static inline std::ostream& operator << (std::ostream& out, const Rect_<_Tp>& rect) { return out << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; } #endif // OPENCV_NOSTL } // cv //! @endcond #endif // __OPENCV_CORE_CVSTDINL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/directx.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors as is and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the copyright holders or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_DIRECTX_HPP__ #define __OPENCV_CORE_DIRECTX_HPP__ #include "mat.hpp" #include "ocl.hpp" #if !defined(__d3d11_h__) struct ID3D11Device; struct ID3D11Texture2D; #endif #if !defined(__d3d10_h__) struct ID3D10Device; struct ID3D10Texture2D; #endif #if !defined(_D3D9_H_) struct IDirect3DDevice9; struct IDirect3DDevice9Ex; struct IDirect3DSurface9; #endif namespace cv { namespace directx { namespace ocl { using namespace cv::ocl; //! @addtogroup core_directx // This section describes OpenCL and DirectX interoperability. // // To enable DirectX support, configure OpenCV using CMake with WITH_DIRECTX=ON . Note, DirectX is // supported only on Windows. // // To use OpenCL functionality you should first initialize OpenCL context from DirectX resource. // //! @{ // TODO static functions in the Context class //! @brief Creates OpenCL context from D3D11 device // //! @param pD3D11Device - pointer to D3D11 device //! @return Returns reference to OpenCL Context CV_EXPORTS Context& initializeContextFromD3D11Device(ID3D11Device* pD3D11Device); //! @brief Creates OpenCL context from D3D10 device // //! @param pD3D10Device - pointer to D3D10 device //! @return Returns reference to OpenCL Context CV_EXPORTS Context& initializeContextFromD3D10Device(ID3D10Device* pD3D10Device); //! @brief Creates OpenCL context from Direct3DDevice9Ex device // //! @param pDirect3DDevice9Ex - pointer to Direct3DDevice9Ex device //! @return Returns reference to OpenCL Context CV_EXPORTS Context& initializeContextFromDirect3DDevice9Ex(IDirect3DDevice9Ex* pDirect3DDevice9Ex); //! @brief Creates OpenCL context from Direct3DDevice9 device // //! @param pDirect3DDevice9 - pointer to Direct3Device9 device //! @return Returns reference to OpenCL Context CV_EXPORTS Context& initializeContextFromDirect3DDevice9(IDirect3DDevice9* pDirect3DDevice9); //! @} } // namespace cv::directx::ocl //! @addtogroup core_directx //! @{ //! @brief Converts InputArray to ID3D11Texture2D. If destination texture format is DXGI_FORMAT_NV12 then //! input UMat expected to be in BGR format and data will be downsampled and color-converted to NV12. // //! @note Note: Destination texture must be allocated by application. Function does memory copy from src to //! pD3D11Texture2D // //! @param src - source InputArray //! @param pD3D11Texture2D - destination D3D11 texture CV_EXPORTS void convertToD3D11Texture2D(InputArray src, ID3D11Texture2D* pD3D11Texture2D); //! @brief Converts ID3D11Texture2D to OutputArray. If input texture format is DXGI_FORMAT_NV12 then //! data will be upsampled and color-converted to BGR format. // //! @note Note: Destination matrix will be re-allocated if it has not enough memory to match texture size. //! function does memory copy from pD3D11Texture2D to dst // //! @param pD3D11Texture2D - source D3D11 texture //! @param dst - destination OutputArray CV_EXPORTS void convertFromD3D11Texture2D(ID3D11Texture2D* pD3D11Texture2D, OutputArray dst); //! @brief Converts InputArray to ID3D10Texture2D // //! @note Note: function does memory copy from src to //! pD3D10Texture2D // //! @param src - source InputArray //! @param pD3D10Texture2D - destination D3D10 texture CV_EXPORTS void convertToD3D10Texture2D(InputArray src, ID3D10Texture2D* pD3D10Texture2D); //! @brief Converts ID3D10Texture2D to OutputArray // //! @note Note: function does memory copy from pD3D10Texture2D //! to dst // //! @param pD3D10Texture2D - source D3D10 texture //! @param dst - destination OutputArray CV_EXPORTS void convertFromD3D10Texture2D(ID3D10Texture2D* pD3D10Texture2D, OutputArray dst); //! @brief Converts InputArray to IDirect3DSurface9 // //! @note Note: function does memory copy from src to //! pDirect3DSurface9 // //! @param src - source InputArray //! @param pDirect3DSurface9 - destination D3D10 texture //! @param surfaceSharedHandle - shared handle CV_EXPORTS void convertToDirect3DSurface9(InputArray src, IDirect3DSurface9* pDirect3DSurface9, void* surfaceSharedHandle = NULL); //! @brief Converts IDirect3DSurface9 to OutputArray // //! @note Note: function does memory copy from pDirect3DSurface9 //! to dst // //! @param pDirect3DSurface9 - source D3D10 texture //! @param dst - destination OutputArray //! @param surfaceSharedHandle - shared handle CV_EXPORTS void convertFromDirect3DSurface9(IDirect3DSurface9* pDirect3DSurface9, OutputArray dst, void* surfaceSharedHandle = NULL); //! @brief Get OpenCV type from DirectX type //! @param iDXGI_FORMAT - enum DXGI_FORMAT for D3D10/D3D11 //! @return OpenCV type or -1 if there is no equivalent CV_EXPORTS int getTypeFromDXGI_FORMAT(const int iDXGI_FORMAT); // enum DXGI_FORMAT for D3D10/D3D11 //! @brief Get OpenCV type from DirectX type //! @param iD3DFORMAT - enum D3DTYPE for D3D9 //! @return OpenCV type or -1 if there is no equivalent CV_EXPORTS int getTypeFromD3DFORMAT(const int iD3DFORMAT); // enum D3DTYPE for D3D9 //! @} } } // namespace cv::directx #endif // __OPENCV_CORE_DIRECTX_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/eigen.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_EIGEN_HPP__ #define __OPENCV_CORE_EIGEN_HPP__ #include "opencv2/core.hpp" #if defined _MSC_VER && _MSC_VER >= 1200 #pragma warning( disable: 4714 ) //__forceinline is not inlined #pragma warning( disable: 4127 ) //conditional expression is constant #pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data #endif namespace cv { //! @addtogroup core_eigen //! @{ template static inline void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Mat& dst ) { if( !(src.Flags & Eigen::RowMajorBit) ) { Mat _src(src.cols(), src.rows(), DataType<_Tp>::type, (void*)src.data(), src.stride()*sizeof(_Tp)); transpose(_src, dst); } else { Mat _src(src.rows(), src.cols(), DataType<_Tp>::type, (void*)src.data(), src.stride()*sizeof(_Tp)); _src.copyTo(dst); } } // Matx case template static inline void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Matx<_Tp, _rows, _cols>& dst ) { if( !(src.Flags & Eigen::RowMajorBit) ) { dst = Matx<_Tp, _cols, _rows>(static_cast(src.data())).t(); } else { dst = Matx<_Tp, _rows, _cols>(static_cast(src.data())); } } template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { CV_DbgAssert(src.rows == _rows && src.cols == _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) { src.convertTo(_dst, _dst.type()); transpose(_dst, _dst); } else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } // Matx case template static inline void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(_cols, _rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(_rows, _cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); Mat(src).copyTo(_dst); } } template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(src.rows, src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) { src.convertTo(_dst, _dst.type()); transpose(_dst, _dst); } else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } // Matx case template static inline void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(_rows, _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(_cols, _rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(_rows, _cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); Mat(src).copyTo(_dst); } } template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { CV_Assert(src.cols == 1); dst.resize(src.rows); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } // Matx case template static inline void cv2eigen( const Matx<_Tp, _rows, 1>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { dst.resize(_rows); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(1, _rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(_rows, 1, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.copyTo(_dst); } } template static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { CV_Assert(src.rows == 1); dst.resize(src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } //Matx template static inline void cv2eigen( const Matx<_Tp, 1, _cols>& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { dst.resize(_cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(_cols, 1, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(1, _cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); Mat(src).copyTo(_dst); } } //! @} } // cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/fast_math.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_FAST_MATH_HPP__ #define __OPENCV_CORE_FAST_MATH_HPP__ #include "opencv2/core/cvdef.h" //! @addtogroup core_utils //! @{ /****************************************************************************************\ * fast math * \****************************************************************************************/ #if defined __BORLANDC__ # include #elif defined __cplusplus # include #else # include #endif #ifdef HAVE_TEGRA_OPTIMIZATION # include "tegra_round.hpp" #endif #if CV_VFP // 1. general scheme #define ARM_ROUND(_value, _asm_string) \ int res; \ float temp; \ asm(_asm_string : [res] "=r" (res), [temp] "=w" (temp) : [value] "w" (_value)); \ return res // 2. version for double #ifdef __clang__ #define ARM_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %[value] \n vmov %[res], %[temp]") #else #define ARM_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %P[value] \n vmov %[res], %[temp]") #endif // 3. version for float #define ARM_ROUND_FLT(value) ARM_ROUND(value, "vcvtr.s32.f32 %[temp], %[value]\n vmov %[res], %[temp]") #endif // CV_VFP /** @brief Rounds floating-point number to the nearest integer @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the result is not defined. */ CV_INLINE int cvRound( double value ) { #if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \ && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__) __m128d t = _mm_set_sd( value ); return _mm_cvtsd_si32(t); #elif defined _MSC_VER && defined _M_IX86 int t; __asm { fld value; fistp t; } return t; #elif ((defined _MSC_VER && defined _M_ARM) || defined CV_ICC || \ defined __GNUC__) && defined HAVE_TEGRA_OPTIMIZATION TEGRA_ROUND_DBL(value); #elif defined CV_ICC || defined __GNUC__ # if CV_VFP ARM_ROUND_DBL(value); # else return (int)lrint(value); # endif #else /* it's ok if round does not comply with IEEE754 standard; the tests should allow +/-1 difference when the tested functions use round */ return (int)(value + (value >= 0 ? 0.5 : -0.5)); #endif } /** @brief Rounds floating-point number to the nearest integer not larger than the original. The function computes an integer i such that: \f[i \le \texttt{value} < i+1\f] @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the result is not defined. */ CV_INLINE int cvFloor( double value ) { #if (defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__) __m128d t = _mm_set_sd( value ); int i = _mm_cvtsd_si32(t); return i - _mm_movemask_pd(_mm_cmplt_sd(t, _mm_cvtsi32_sd(t,i))); #elif defined __GNUC__ int i = (int)value; return i - (i > value); #else int i = cvRound(value); float diff = (float)(value - i); return i - (diff < 0); #endif } /** @brief Rounds floating-point number to the nearest integer not smaller than the original. The function computes an integer i such that: \f[i \le \texttt{value} < i+1\f] @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the result is not defined. */ CV_INLINE int cvCeil( double value ) { #if (defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__&& !defined __APPLE__)) && !defined(__CUDACC__) __m128d t = _mm_set_sd( value ); int i = _mm_cvtsd_si32(t); return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t,i), t)); #elif defined __GNUC__ int i = (int)value; return i + (i < value); #else int i = cvRound(value); float diff = (float)(i - value); return i + (diff < 0); #endif } /** @brief Determines if the argument is Not A Number. @param value The input floating-point value The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise. */ CV_INLINE int cvIsNaN( double value ) { Cv64suf ieee754; ieee754.f = value; return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) + ((unsigned)ieee754.u != 0) > 0x7ff00000; } /** @brief Determines if the argument is Infinity. @param value The input floating-point value The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) and 0 otherwise. */ CV_INLINE int cvIsInf( double value ) { Cv64suf ieee754; ieee754.f = value; return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 && (unsigned)ieee754.u == 0; } #ifdef __cplusplus /** @overload */ CV_INLINE int cvRound(float value) { #if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ && \ defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__) __m128 t = _mm_set_ss( value ); return _mm_cvtss_si32(t); #elif defined _MSC_VER && defined _M_IX86 int t; __asm { fld value; fistp t; } return t; #elif ((defined _MSC_VER && defined _M_ARM) || defined CV_ICC || \ defined __GNUC__) && defined HAVE_TEGRA_OPTIMIZATION TEGRA_ROUND_FLT(value); #elif defined CV_ICC || defined __GNUC__ # if CV_VFP ARM_ROUND_FLT(value); # else return (int)lrintf(value); # endif #else /* it's ok if round does not comply with IEEE754 standard; the tests should allow +/-1 difference when the tested functions use round */ return (int)(value + (value >= 0 ? 0.5f : -0.5f)); #endif } /** @overload */ CV_INLINE int cvRound( int value ) { return value; } /** @overload */ CV_INLINE int cvFloor( float value ) { #if (defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__) __m128 t = _mm_set_ss( value ); int i = _mm_cvtss_si32(t); return i - _mm_movemask_ps(_mm_cmplt_ss(t, _mm_cvtsi32_ss(t,i))); #elif defined __GNUC__ int i = (int)value; return i - (i > value); #else int i = cvRound(value); float diff = (float)(value - i); return i - (diff < 0); #endif } /** @overload */ CV_INLINE int cvFloor( int value ) { return value; } /** @overload */ CV_INLINE int cvCeil( float value ) { #if (defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__&& !defined __APPLE__)) && !defined(__CUDACC__) __m128 t = _mm_set_ss( value ); int i = _mm_cvtss_si32(t); return i + _mm_movemask_ps(_mm_cmplt_ss(_mm_cvtsi32_ss(t,i), t)); #elif defined __GNUC__ int i = (int)value; return i + (i < value); #else int i = cvRound(value); float diff = (float)(i - value); return i + (diff < 0); #endif } /** @overload */ CV_INLINE int cvCeil( int value ) { return value; } /** @overload */ CV_INLINE int cvIsNaN( float value ) { Cv32suf ieee754; ieee754.f = value; return (ieee754.u & 0x7fffffff) > 0x7f800000; } /** @overload */ CV_INLINE int cvIsInf( float value ) { Cv32suf ieee754; ieee754.f = value; return (ieee754.u & 0x7fffffff) == 0x7f800000; } #endif // __cplusplus //! @} core_utils #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/hal/hal.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HAL_HPP__ #define __OPENCV_HAL_HPP__ #include "opencv2/core/cvdef.h" #include "opencv2/core/hal/interface.h" //! @cond IGNORED #define CALL_HAL(name, fun, ...) \ int res = fun(__VA_ARGS__); \ if (res == CV_HAL_ERROR_OK) \ return; \ else if (res != CV_HAL_ERROR_NOT_IMPLEMENTED) \ CV_Error_(cv::Error::StsInternal, \ ("HAL implementation " CVAUX_STR(name) " ==> " CVAUX_STR(fun) " returned %d (0x%08x)", res, res)); //! @endcond namespace cv { namespace hal { //! @addtogroup core_hal_functions //! @{ CV_EXPORTS int normHamming(const uchar* a, int n); CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n); CV_EXPORTS int normHamming(const uchar* a, int n, int cellSize); CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n, int cellSize); CV_EXPORTS int LU32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); CV_EXPORTS int LU64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); CV_EXPORTS bool Cholesky32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); CV_EXPORTS bool Cholesky64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); CV_EXPORTS int normL1_(const uchar* a, const uchar* b, int n); CV_EXPORTS float normL1_(const float* a, const float* b, int n); CV_EXPORTS float normL2Sqr_(const float* a, const float* b, int n); CV_EXPORTS void exp32f(const float* src, float* dst, int n); CV_EXPORTS void exp64f(const double* src, double* dst, int n); CV_EXPORTS void log32f(const float* src, float* dst, int n); CV_EXPORTS void log64f(const double* src, double* dst, int n); CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); CV_EXPORTS void magnitude32f(const float* x, const float* y, float* dst, int n); CV_EXPORTS void magnitude64f(const double* x, const double* y, double* dst, int n); CV_EXPORTS void sqrt32f(const float* src, float* dst, int len); CV_EXPORTS void sqrt64f(const double* src, double* dst, int len); CV_EXPORTS void invSqrt32f(const float* src, float* dst, int len); CV_EXPORTS void invSqrt64f(const double* src, double* dst, int len); CV_EXPORTS void split8u(const uchar* src, uchar** dst, int len, int cn ); CV_EXPORTS void split16u(const ushort* src, ushort** dst, int len, int cn ); CV_EXPORTS void split32s(const int* src, int** dst, int len, int cn ); CV_EXPORTS void split64s(const int64* src, int64** dst, int len, int cn ); CV_EXPORTS void merge8u(const uchar** src, uchar* dst, int len, int cn ); CV_EXPORTS void merge16u(const ushort** src, ushort* dst, int len, int cn ); CV_EXPORTS void merge32s(const int** src, int* dst, int len, int cn ); CV_EXPORTS void merge64s(const int64** src, int64* dst, int len, int cn ); CV_EXPORTS void add8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void add8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void add16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); CV_EXPORTS void add16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); CV_EXPORTS void add32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); CV_EXPORTS void add32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); CV_EXPORTS void add64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); CV_EXPORTS void sub8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void sub8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void sub16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); CV_EXPORTS void sub16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); CV_EXPORTS void sub32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); CV_EXPORTS void sub32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); CV_EXPORTS void sub64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); CV_EXPORTS void max8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void max8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void max16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); CV_EXPORTS void max16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); CV_EXPORTS void max32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); CV_EXPORTS void max32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); CV_EXPORTS void max64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); CV_EXPORTS void min8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void min8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void min16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); CV_EXPORTS void min16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); CV_EXPORTS void min32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); CV_EXPORTS void min32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); CV_EXPORTS void min64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); CV_EXPORTS void absdiff8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void absdiff8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void absdiff16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); CV_EXPORTS void absdiff16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); CV_EXPORTS void absdiff32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); CV_EXPORTS void absdiff32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); CV_EXPORTS void absdiff64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); CV_EXPORTS void and8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void or8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void xor8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void not8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); CV_EXPORTS void cmp8u(const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); CV_EXPORTS void cmp8s(const schar* src1, size_t step1, const schar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); CV_EXPORTS void cmp16u(const ushort* src1, size_t step1, const ushort* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); CV_EXPORTS void cmp16s(const short* src1, size_t step1, const short* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); CV_EXPORTS void cmp32s(const int* src1, size_t step1, const int* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); CV_EXPORTS void cmp32f(const float* src1, size_t step1, const float* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); CV_EXPORTS void cmp64f(const double* src1, size_t step1, const double* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); CV_EXPORTS void mul8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void mul8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void mul16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void mul16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void mul32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void mul32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void mul64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void div8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void div8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void div16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void div16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void div32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void div32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void div64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void recip8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void recip8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void recip16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void recip16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void recip32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void recip32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void recip64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); CV_EXPORTS void addWeighted8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _scalars ); CV_EXPORTS void addWeighted8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scalars ); CV_EXPORTS void addWeighted16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scalars ); CV_EXPORTS void addWeighted16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scalars ); CV_EXPORTS void addWeighted32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scalars ); CV_EXPORTS void addWeighted32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scalars ); CV_EXPORTS void addWeighted64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scalars ); //! @} core_hal //============================================================================= // for binary compatibility with 3.0 //! @cond IGNORED CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); CV_EXPORTS void exp(const float* src, float* dst, int n); CV_EXPORTS void exp(const double* src, double* dst, int n); CV_EXPORTS void log(const float* src, float* dst, int n); CV_EXPORTS void log(const double* src, double* dst, int n); CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); CV_EXPORTS void magnitude(const double* x, const double* y, double* dst, int n); CV_EXPORTS void sqrt(const float* src, float* dst, int len); CV_EXPORTS void sqrt(const double* src, double* dst, int len); CV_EXPORTS void invSqrt(const float* src, float* dst, int len); CV_EXPORTS void invSqrt(const double* src, double* dst, int len); //! @endcond }} //cv::hal #endif //__OPENCV_HAL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/hal/interface.h ================================================ #ifndef _HAL_INTERFACE_HPP_INCLUDED_ #define _HAL_INTERFACE_HPP_INCLUDED_ //! @addtogroup core_hal_interface //! @{ #define CV_HAL_ERROR_OK 0 #define CV_HAL_ERROR_NOT_IMPLEMENTED 1 #define CV_HAL_ERROR_UNKNOWN -1 #define CV_HAL_CMP_EQ 0 #define CV_HAL_CMP_GT 1 #define CV_HAL_CMP_GE 2 #define CV_HAL_CMP_LT 3 #define CV_HAL_CMP_LE 4 #define CV_HAL_CMP_NE 5 #ifdef __cplusplus #include #else #include #endif /* primitive types */ /* schar - signed 1 byte integer uchar - unsigned 1 byte integer short - signed 2 byte integer ushort - unsigned 2 byte integer int - signed 4 byte integer uint - unsigned 4 byte integer int64 - signed 8 byte integer uint64 - unsigned 8 byte integer */ #if !defined _MSC_VER && !defined __BORLANDC__ # if defined __cplusplus && __cplusplus >= 201103L && !defined __APPLE__ # include typedef std::uint32_t uint; # else # include typedef uint32_t uint; # endif #else typedef unsigned uint; #endif typedef signed char schar; #ifndef __IPL_H__ typedef unsigned char uchar; typedef unsigned short ushort; #endif #if defined _MSC_VER || defined __BORLANDC__ typedef __int64 int64; typedef unsigned __int64 uint64; # define CV_BIG_INT(n) n##I64 # define CV_BIG_UINT(n) n##UI64 #else typedef int64_t int64; typedef uint64_t uint64; # define CV_BIG_INT(n) n##LL # define CV_BIG_UINT(n) n##ULL #endif //! @} #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/hal/intrin.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HAL_INTRIN_HPP__ #define __OPENCV_HAL_INTRIN_HPP__ #include #include #include #include "opencv2/core/cvdef.h" #define OPENCV_HAL_ADD(a, b) ((a) + (b)) #define OPENCV_HAL_AND(a, b) ((a) & (b)) #define OPENCV_HAL_NOP(a) (a) #define OPENCV_HAL_1ST(a, b) (a) // unlike HAL API, which is in cv::hal, // we put intrinsics into cv namespace to make its // access from within opencv code more accessible namespace cv { //! @addtogroup core_hal_intrin //! @{ //! @cond IGNORED template struct V_TypeTraits { typedef _Tp int_type; typedef _Tp uint_type; typedef _Tp abs_type; typedef _Tp sum_type; enum { delta = 0, shift = 0 }; static int_type reinterpret_int(_Tp x) { return x; } static uint_type reinterpet_uint(_Tp x) { return x; } static _Tp reinterpret_from_int(int_type x) { return (_Tp)x; } }; template<> struct V_TypeTraits { typedef uchar value_type; typedef schar int_type; typedef uchar uint_type; typedef uchar abs_type; typedef int sum_type; typedef ushort w_type; typedef unsigned q_type; enum { delta = 128, shift = 8 }; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef schar value_type; typedef schar int_type; typedef uchar uint_type; typedef uchar abs_type; typedef int sum_type; typedef short w_type; typedef int q_type; enum { delta = 128, shift = 8 }; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef ushort value_type; typedef short int_type; typedef ushort uint_type; typedef ushort abs_type; typedef int sum_type; typedef unsigned w_type; typedef uchar nu_type; enum { delta = 32768, shift = 16 }; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef short value_type; typedef short int_type; typedef ushort uint_type; typedef ushort abs_type; typedef int sum_type; typedef int w_type; typedef uchar nu_type; typedef schar n_type; enum { delta = 128, shift = 8 }; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef unsigned value_type; typedef int int_type; typedef unsigned uint_type; typedef unsigned abs_type; typedef unsigned sum_type; typedef uint64 w_type; typedef ushort nu_type; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef int value_type; typedef int int_type; typedef unsigned uint_type; typedef unsigned abs_type; typedef int sum_type; typedef int64 w_type; typedef short n_type; typedef ushort nu_type; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef uint64 value_type; typedef int64 int_type; typedef uint64 uint_type; typedef uint64 abs_type; typedef uint64 sum_type; typedef unsigned nu_type; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef int64 value_type; typedef int64 int_type; typedef uint64 uint_type; typedef uint64 abs_type; typedef int64 sum_type; typedef int nu_type; static int_type reinterpret_int(value_type x) { return (int_type)x; } static uint_type reinterpret_uint(value_type x) { return (uint_type)x; } static value_type reinterpret_from_int(int_type x) { return (value_type)x; } }; template<> struct V_TypeTraits { typedef float value_type; typedef int int_type; typedef unsigned uint_type; typedef float abs_type; typedef float sum_type; typedef double w_type; static int_type reinterpret_int(value_type x) { Cv32suf u; u.f = x; return u.i; } static uint_type reinterpet_uint(value_type x) { Cv32suf u; u.f = x; return u.u; } static value_type reinterpret_from_int(int_type x) { Cv32suf u; u.i = x; return u.f; } }; template<> struct V_TypeTraits { typedef double value_type; typedef int64 int_type; typedef uint64 uint_type; typedef double abs_type; typedef double sum_type; static int_type reinterpret_int(value_type x) { Cv64suf u; u.f = x; return u.i; } static uint_type reinterpet_uint(value_type x) { Cv64suf u; u.f = x; return u.u; } static value_type reinterpret_from_int(int_type x) { Cv64suf u; u.i = x; return u.f; } }; template struct V_SIMD128Traits { enum { nlanes = 16 / sizeof(T) }; }; //! @endcond //! @} } #ifdef CV_DOXYGEN # undef CV_SSE2 # undef CV_NEON #endif #if CV_SSE2 #include "opencv2/core/hal/intrin_sse.hpp" #elif CV_NEON #include "opencv2/core/hal/intrin_neon.hpp" #else #include "opencv2/core/hal/intrin_cpp.hpp" #endif //! @addtogroup core_hal_intrin //! @{ #ifndef CV_SIMD128 //! Set to 1 if current compiler supports vector extensions (NEON or SSE is enabled) #define CV_SIMD128 0 #endif #ifndef CV_SIMD128_64F //! Set to 1 if current intrinsics implementation supports 64-bit float vectors #define CV_SIMD128_64F 0 #endif //! @} #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/hal/intrin_cpp.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HAL_INTRIN_CPP_HPP__ #define __OPENCV_HAL_INTRIN_CPP_HPP__ #include #include #include #include "opencv2/core/saturate.hpp" namespace cv { /** @addtogroup core_hal_intrin "Universal intrinsics" is a types and functions set intended to simplify vectorization of code on different platforms. Currently there are two supported SIMD extensions: __SSE/SSE2__ on x86 architectures and __NEON__ on ARM architectures, both allow working with 128 bit registers containing packed values of different types. In case when there is no SIMD extension available during compilation, fallback C++ implementation of intrinsics will be chosen and code will work as expected although it could be slower. ### Types There are several types representing 128-bit register as a vector of packed values, each type is implemented as a structure based on a one SIMD register. - cv::v_uint8x16 and cv::v_int8x16: sixteen 8-bit integer values (unsigned/signed) - char - cv::v_uint16x8 and cv::v_int16x8: eight 16-bit integer values (unsigned/signed) - short - cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsgined/signed) - int - cv::v_uint64x2 and cv::v_int64x2: two 64-bit integer values (unsigned/signed) - int64 - cv::v_float32x4: four 32-bit floating point values (signed) - float - cv::v_float64x2: two 64-bit floating point valies (signed) - double @note cv::v_float64x2 is not implemented in NEON variant, if you want to use this type, don't forget to check the CV_SIMD128_64F preprocessor definition: @code #if CV_SIMD128_64F //... #endif @endcode ### Load and store operations These operations allow to set contents of the register explicitly or by loading it from some memory block and to save contents of the register to memory block. - Constructors: @ref v_reg::v_reg(const _Tp *ptr) "from memory", @ref v_reg::v_reg(_Tp s0, _Tp s1) "from two values", ... - Other create methods: @ref v_setall_s8, @ref v_setall_u8, ..., @ref v_setzero_u8, @ref v_setzero_s8, ... - Memory operations: @ref v_load, @ref v_load_aligned, @ref v_load_halves, @ref v_store, @ref v_store_aligned, @ref v_store_high, @ref v_store_low ### Value reordering These operations allow to reorder or recombine elements in one or multiple vectors. - Interleave, deinterleave (3 and 4 channels): @ref v_load_deinterleave, @ref v_store_interleave - Expand: @ref v_load_expand, @ref v_load_expand_q, @ref v_expand - Pack: @ref v_pack, @ref v_pack_u, @ref v_rshr_pack, @ref v_rshr_pack_u, @ref v_pack_store, @ref v_pack_u_store, @ref v_rshr_pack_store, @ref v_rshr_pack_u_store - Recombine: @ref v_zip, @ref v_recombine, @ref v_combine_low, @ref v_combine_high - Extract: @ref v_extract ### Arithmetic, bitwise and comparison operations Element-wise binary and unary operations. - Arithmetics: @ref operator+(const v_reg &a, const v_reg &b) "+", @ref operator-(const v_reg &a, const v_reg &b) "-", @ref operator*(const v_reg &a, const v_reg &b) "*", @ref operator/(const v_reg &a, const v_reg &b) "/", @ref v_mul_expand - Non-saturating arithmetics: @ref v_add_wrap, @ref v_sub_wrap - Bitwise shifts: @ref operator<<(const v_reg &a, int s) "<<", @ref operator>>(const v_reg &a, int s) ">>", @ref v_shl, @ref v_shr - Bitwise logic: @ref operator&(const v_reg &a, const v_reg &b) "&", @ref operator|(const v_reg &a, const v_reg &b) "|", @ref operator^(const v_reg &a, const v_reg &b) "^", @ref operator~(const v_reg &a) "~" - Comparison: @ref operator>(const v_reg &a, const v_reg &b) ">", @ref operator>=(const v_reg &a, const v_reg &b) ">=", @ref operator<(const v_reg &a, const v_reg &b) "<", @ref operator<=(const v_reg &a, const v_reg &b) "<=", @ref operator==(const v_reg &a, const v_reg &b) "==", @ref operator!=(const v_reg &a, const v_reg &b) "!=" - min/max: @ref v_min, @ref v_max ### Reduce and mask Most of these operations return only one value. - Reduce: @ref v_reduce_min, @ref v_reduce_max, @ref v_reduce_sum - Mask: @ref v_signmask, @ref v_check_all, @ref v_check_any, @ref v_select ### Other math - Some frequent operations: @ref v_sqrt, @ref v_invsqrt, @ref v_magnitude, @ref v_sqr_magnitude - Absolute values: @ref v_abs, @ref v_absdiff ### Conversions Different type conversions and casts: - Rounding: @ref v_round, @ref v_floor, @ref v_ceil, @ref v_trunc, - To float: @ref v_cvt_f32, @ref v_cvt_f64 - Reinterpret: @ref v_reinterpret_as_u8, @ref v_reinterpret_as_s8, ... ### Matrix operations In these operations vectors represent matrix rows/columns: @ref v_dotprod, @ref v_matmul, @ref v_transpose4x4 ### Usability Most operations are implemented only for some subset of the available types, following matrices shows the applicability of different operations to the types. Regular integers: | Operations\\Types | uint 8x16 | int 8x16 | uint 16x8 | int 16x8 | uint 32x4 | int 32x4 | |-------------------|:-:|:-:|:-:|:-:|:-:|:-:| |load, store | x | x | x | x | x | x | |interleave | x | x | x | x | x | x | |expand | x | x | x | x | x | x | |expand_q | x | x | | | | | |add, sub | x | x | x | x | x | x | |add_wrap, sub_wrap | x | x | x | x | | | |mul | | | x | x | x | x | |mul_expand | | | x | x | x | | |compare | x | x | x | x | x | x | |shift | | | x | x | x | x | |dotprod | | | | x | | | |logical | x | x | x | x | x | x | |min, max | x | x | x | x | x | x | |absdiff | x | x | x | x | x | x | |reduce | | | | | x | x | |mask | x | x | x | x | x | x | |pack | x | x | x | x | x | x | |pack_u | x | | x | | | | |unpack | x | x | x | x | x | x | |extract | x | x | x | x | x | x | |cvt_flt32 | | | | | | x | |cvt_flt64 | | | | | | x | |transpose4x4 | | | | | x | x | Big integers: | Operations\\Types | uint 64x2 | int 64x2 | |-------------------|:-:|:-:| |load, store | x | x | |add, sub | x | x | |shift | x | x | |logical | x | x | |extract | x | x | Floating point: | Operations\\Types | float 32x4 | float 64x2 | |-------------------|:-:|:-:| |load, store | x | x | |interleave | x | | |add, sub | x | x | |mul | x | x | |div | x | x | |compare | x | x | |min, max | x | x | |absdiff | x | x | |reduce | x | | |mask | x | x | |unpack | x | x | |cvt_flt32 | | x | |cvt_flt64 | x | | |sqrt, abs | x | x | |float math | x | x | |transpose4x4 | x | | @{ */ template struct v_reg { //! @cond IGNORED typedef _Tp lane_type; typedef v_reg::int_type, n> int_vec; typedef v_reg::abs_type, n> abs_vec; enum { nlanes = n }; // !@endcond /** @brief Constructor Initializes register with data from memory @param ptr pointer to memory block with data for register */ explicit v_reg(const _Tp* ptr) { for( int i = 0; i < n; i++ ) s[i] = ptr[i]; } /** @brief Constructor Initializes register with two 64-bit values */ v_reg(_Tp s0, _Tp s1) { s[0] = s0; s[1] = s1; } /** @brief Constructor Initializes register with four 32-bit values */ v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; } /** @brief Constructor Initializes register with eight 16-bit values */ v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; } /** @brief Constructor Initializes register with sixteen 8-bit values */ v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7, _Tp s8, _Tp s9, _Tp s10, _Tp s11, _Tp s12, _Tp s13, _Tp s14, _Tp s15) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; s[8] = s8; s[9] = s9; s[10] = s10; s[11] = s11; s[12] = s12; s[13] = s13; s[14] = s14; s[15] = s15; } /** @brief Default constructor Does not initialize anything*/ v_reg() {} /** @brief Copy constructor */ v_reg(const v_reg<_Tp, n> & r) { for( int i = 0; i < n; i++ ) s[i] = r.s[i]; } /** @brief Access first value Returns value of the first lane according to register type, for example: @code{.cpp} v_int32x4 r(1, 2, 3, 4); int v = r.get0(); // returns 1 v_uint64x2 r(1, 2); uint64_t v = r.get0(); // returns 1 @endcode */ _Tp get0() const { return s[0]; } //! @cond IGNORED _Tp get(const int i) const { return s[i]; } v_reg<_Tp, n> high() const { v_reg<_Tp, n> c; int i; for( i = 0; i < n/2; i++ ) { c.s[i] = s[i+(n/2)]; c.s[i+(n/2)] = 0; } return c; } static v_reg<_Tp, n> zero() { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = (_Tp)0; return c; } static v_reg<_Tp, n> all(_Tp s) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = s; return c; } template v_reg<_Tp2, n2> reinterpret_as() const { size_t bytes = std::min(sizeof(_Tp2)*n2, sizeof(_Tp)*n); v_reg<_Tp2, n2> c; std::memcpy(&c.s[0], &s[0], bytes); return c; } _Tp s[n]; //! @endcond }; /** @brief Sixteen 8-bit unsigned integer values */ typedef v_reg v_uint8x16; /** @brief Sixteen 8-bit signed integer values */ typedef v_reg v_int8x16; /** @brief Eight 16-bit unsigned integer values */ typedef v_reg v_uint16x8; /** @brief Eight 16-bit signed integer values */ typedef v_reg v_int16x8; /** @brief Four 32-bit unsigned integer values */ typedef v_reg v_uint32x4; /** @brief Four 32-bit signed integer values */ typedef v_reg v_int32x4; /** @brief Four 32-bit floating point values (single precision) */ typedef v_reg v_float32x4; /** @brief Two 64-bit floating point values (double precision) */ typedef v_reg v_float64x2; /** @brief Two 64-bit unsigned integer values */ typedef v_reg v_uint64x2; /** @brief Two 64-bit signed integer values */ typedef v_reg v_int64x2; //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_BIN_OP(bin_op) \ template inline v_reg<_Tp, n> \ operator bin_op (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ return c; \ } \ template inline v_reg<_Tp, n>& \ operator bin_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ for( int i = 0; i < n; i++ ) \ a.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ return a; \ } /** @brief Add values For all types. */ OPENCV_HAL_IMPL_BIN_OP(+) /** @brief Subtract values For all types. */ OPENCV_HAL_IMPL_BIN_OP(-) /** @brief Multiply values For 16- and 32-bit integer types and floating types. */ OPENCV_HAL_IMPL_BIN_OP(*) /** @brief Divide values For floating types only. */ OPENCV_HAL_IMPL_BIN_OP(/) //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_BIT_OP(bit_op) \ template inline v_reg<_Tp, n> operator bit_op \ (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ v_reg<_Tp, n> c; \ typedef typename V_TypeTraits<_Tp>::int_type itype; \ for( int i = 0; i < n; i++ ) \ c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ return c; \ } \ template inline v_reg<_Tp, n>& operator \ bit_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ typedef typename V_TypeTraits<_Tp>::int_type itype; \ for( int i = 0; i < n; i++ ) \ a.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ return a; \ } /** @brief Bitwise AND Only for integer types. */ OPENCV_HAL_IMPL_BIT_OP(&) /** @brief Bitwise OR Only for integer types. */ OPENCV_HAL_IMPL_BIT_OP(|) /** @brief Bitwise XOR Only for integer types.*/ OPENCV_HAL_IMPL_BIT_OP(^) /** @brief Bitwise NOT Only for integer types.*/ template inline v_reg<_Tp, n> operator ~ (const v_reg<_Tp, n>& a) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i])); return c; } //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_MATH_FUNC(func, cfunc, _Tp2) \ template inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a) \ { \ v_reg<_Tp2, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = cfunc(a.s[i]); \ return c; \ } /** @brief Square root of elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_sqrt, std::sqrt, _Tp) //! @cond IGNORED OPENCV_HAL_IMPL_MATH_FUNC(v_sin, std::sin, _Tp) OPENCV_HAL_IMPL_MATH_FUNC(v_cos, std::cos, _Tp) OPENCV_HAL_IMPL_MATH_FUNC(v_exp, std::exp, _Tp) OPENCV_HAL_IMPL_MATH_FUNC(v_log, std::log, _Tp) //! @endcond /** @brief Absolute value of elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_abs, (typename V_TypeTraits<_Tp>::abs_type)std::abs, typename V_TypeTraits<_Tp>::abs_type) /** @brief Round elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_round, cvRound, int) /** @brief Floor elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_floor, cvFloor, int) /** @brief Ceil elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_ceil, cvCeil, int) /** @brief Truncate elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_trunc, int, int) //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_MINMAX_FUNC(func, cfunc) \ template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = cfunc(a.s[i], b.s[i]); \ return c; \ } //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(func, cfunc) \ template inline _Tp func(const v_reg<_Tp, n>& a) \ { \ _Tp c = a.s[0]; \ for( int i = 1; i < n; i++ ) \ c = cfunc(c, a.s[i]); \ return c; \ } /** @brief Choose min values for each pair Scheme: @code {A1 A2 ...} {B1 B2 ...} -------------- {min(A1,B1) min(A2,B2) ...} @endcode For all types except 64-bit integer. */ OPENCV_HAL_IMPL_MINMAX_FUNC(v_min, std::min) /** @brief Choose max values for each pair Scheme: @code {A1 A2 ...} {B1 B2 ...} -------------- {max(A1,B1) max(A2,B2) ...} @endcode For all types except 64-bit integer. */ OPENCV_HAL_IMPL_MINMAX_FUNC(v_max, std::max) /** @brief Find one min value Scheme: @code {A1 A2 A3 ...} => min(A1,A2,A3,...) @endcode For 32-bit integer and 32-bit floating point types. */ OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_min, std::min) /** @brief Find one max value Scheme: @code {A1 A2 A3 ...} => max(A1,A2,A3,...) @endcode For 32-bit integer and 32-bit floating point types. */ OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_max, std::max) //! @cond IGNORED template inline void v_minmax( const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, v_reg<_Tp, n>& minval, v_reg<_Tp, n>& maxval ) { for( int i = 0; i < n; i++ ) { minval.s[i] = std::min(a.s[i], b.s[i]); maxval.s[i] = std::max(a.s[i], b.s[i]); } } //! @endcond //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_CMP_OP(cmp_op) \ template \ inline v_reg<_Tp, n> operator cmp_op(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ typedef typename V_TypeTraits<_Tp>::int_type itype; \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)-(int)(a.s[i] cmp_op b.s[i])); \ return c; \ } /** @brief Less-than comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(<) /** @brief Greater-than comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(>) /** @brief Less-than or equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(<=) /** @brief Greater-than or equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(>=) /** @brief Equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(==) /** @brief Not equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(!=) //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_ADD_SUB_OP(func, bin_op, cast_op, _Tp2) \ template \ inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ typedef _Tp2 rtype; \ v_reg c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = cast_op(a.s[i] bin_op b.s[i]); \ return c; \ } /** @brief Add values without saturation For 8- and 16-bit integer values. */ OPENCV_HAL_IMPL_ADD_SUB_OP(v_add_wrap, +, (_Tp), _Tp) /** @brief Subtract values without saturation For 8- and 16-bit integer values. */ OPENCV_HAL_IMPL_ADD_SUB_OP(v_sub_wrap, -, (_Tp), _Tp) //! @cond IGNORED template inline T _absdiff(T a, T b) { return a > b ? a - b : b - a; } //! @endcond /** @brief Absolute difference Returns \f$ |a - b| \f$ converted to corresponding unsigned type. Example: @code{.cpp} v_int32x4 a, b; // {1, 2, 3, 4} and {4, 3, 2, 1} v_uint32x4 c = v_absdiff(a, b); // result is {3, 1, 1, 3} @endcode For 8-, 16-, 32-bit integer source types. */ template inline v_reg::abs_type, n> v_absdiff(const v_reg<_Tp, n>& a, const v_reg<_Tp, n> & b) { typedef typename V_TypeTraits<_Tp>::abs_type rtype; v_reg c; const rtype mask = std::numeric_limits<_Tp>::is_signed ? (1 << (sizeof(rtype)*8 - 1)) : 0; for( int i = 0; i < n; i++ ) { rtype ua = a.s[i] ^ mask; rtype ub = b.s[i] ^ mask; c.s[i] = _absdiff(ua, ub); } return c; } /** @overload For 32-bit floating point values */ inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) { v_float32x4 c; for( int i = 0; i < c.nlanes; i++ ) c.s[i] = _absdiff(a.s[i], b.s[i]); return c; } /** @overload For 64-bit floating point values */ inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) { v_float64x2 c; for( int i = 0; i < c.nlanes; i++ ) c.s[i] = _absdiff(a.s[i], b.s[i]); return c; } /** @brief Inversed square root Returns \f$ 1/sqrt(a) \f$ For floating point types only. */ template inline v_reg<_Tp, n> v_invsqrt(const v_reg<_Tp, n>& a) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = 1.f/std::sqrt(a.s[i]); return c; } /** @brief Magnitude Returns \f$ sqrt(a^2 + b^2) \f$ For floating point types only. */ template inline v_reg<_Tp, n> v_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = std::sqrt(a.s[i]*a.s[i] + b.s[i]*b.s[i]); return c; } /** @brief Square of the magnitude Returns \f$ a^2 + b^2 \f$ For floating point types only. */ template inline v_reg<_Tp, n> v_sqr_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = a.s[i]*a.s[i] + b.s[i]*b.s[i]; return c; } /** @brief Multiply and add Returns \f$ a*b + c \f$ For floating point types only. */ template inline v_reg<_Tp, n> v_muladd(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c) { v_reg<_Tp, n> d; for( int i = 0; i < n; i++ ) d.s[i] = a.s[i]*b.s[i] + c.s[i]; return d; } /** @brief Dot product of elements Multiply values in two registers and sum adjacent result pairs. Scheme: @code {A1 A2 ...} // 16-bit x {B1 B2 ...} // 16-bit ------------- {A1B1+A2B2 ...} // 32-bit @endcode Implemented only for 16-bit signed source type (v_int16x8). */ template inline v_reg::w_type, n/2> v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { typedef typename V_TypeTraits<_Tp>::w_type w_type; v_reg c; for( int i = 0; i < (n/2); i++ ) c.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1]; return c; } /** @brief Multiply and expand Multiply values two registers and store results in two registers with wider pack type. Scheme: @code {A B C D} // 32-bit x {E F G H} // 32-bit --------------- {AE BF} // 64-bit {CG DH} // 64-bit @endcode Example: @code{.cpp} v_uint32x4 a, b; // {1,2,3,4} and {2,2,2,2} v_uint64x2 c, d; // results v_mul_expand(a, b, c, d); // c, d = {2,4}, {6, 8} @endcode Implemented only for 16- and unsigned 32-bit source types (v_int16x8, v_uint16x8, v_uint32x4). */ template inline void v_mul_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, v_reg::w_type, n/2>& c, v_reg::w_type, n/2>& d) { typedef typename V_TypeTraits<_Tp>::w_type w_type; for( int i = 0; i < (n/2); i++ ) { c.s[i] = (w_type)a.s[i]*b.s[i]; d.s[i] = (w_type)a.s[i+(n/2)]*b.s[i+(n/2)]; } } //! @cond IGNORED template inline void v_hsum(const v_reg<_Tp, n>& a, v_reg::w_type, n/2>& c) { typedef typename V_TypeTraits<_Tp>::w_type w_type; for( int i = 0; i < (n/2); i++ ) { c.s[i] = (w_type)a.s[i*2] + a.s[i*2+1]; } } //! @endcond //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_SHIFT_OP(shift_op) \ template inline v_reg<_Tp, n> operator shift_op(const v_reg<_Tp, n>& a, int imm) \ { \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = (_Tp)(a.s[i] shift_op imm); \ return c; \ } /** @brief Bitwise shift left For 16-, 32- and 64-bit integer values. */ OPENCV_HAL_IMPL_SHIFT_OP(<<) /** @brief Bitwise shift right For 16-, 32- and 64-bit integer values. */ OPENCV_HAL_IMPL_SHIFT_OP(>>) /** @brief Sum packed values Scheme: @code {A1 A2 A3 ...} => sum{A1,A2,A3,...} @endcode For 32-bit integer and 32-bit floating point types.*/ template inline typename V_TypeTraits<_Tp>::sum_type v_reduce_sum(const v_reg<_Tp, n>& a) { typename V_TypeTraits<_Tp>::sum_type c = a.s[0]; for( int i = 1; i < n; i++ ) c += a.s[i]; return c; } /** @brief Get negative values mask Returned value is a bit mask with bits set to 1 on places corresponding to negative packed values indexes. Example: @code{.cpp} v_int32x4 r; // set to {-1, -1, 1, 1} int mask = v_signmask(r); // mask = 3 <== 00000000 00000000 00000000 00000011 @endcode For all types except 64-bit. */ template inline int v_signmask(const v_reg<_Tp, n>& a) { int mask = 0; for( int i = 0; i < n; i++ ) mask |= (V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) << i; return mask; } /** @brief Check if all packed values are less than zero Unsigned values will be casted to signed: `uchar 254 => char -2`. For all types except 64-bit. */ template inline bool v_check_all(const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) >= 0 ) return false; return true; } /** @brief Check if any of packed values is less than zero Unsigned values will be casted to signed: `uchar 254 => char -2`. For all types except 64-bit. */ template inline bool v_check_any(const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0 ) return true; return false; } /** @brief Bitwise select Return value will be built by combining values a and b using the following scheme: If the i-th bit in _mask_ is 1 select i-th bit from _a_ else select i-th bit from _b_ */ template inline v_reg<_Tp, n> v_select(const v_reg<_Tp, n>& mask, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { typedef V_TypeTraits<_Tp> Traits; typedef typename Traits::int_type int_type; v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) { int_type m = Traits::reinterpret_int(mask.s[i]); c.s[i] = Traits::reinterpret_from_int((Traits::reinterpret_int(a.s[i]) & m) | (Traits::reinterpret_int(b.s[i]) & ~m)); } return c; } /** @brief Expand values to the wider pack type Copy contents of register to two registers with 2x wider pack type. Scheme: @code int32x4 int64x2 int64x2 {A B C D} ==> {A B} , {C D} @endcode */ template inline void v_expand(const v_reg<_Tp, n>& a, v_reg::w_type, n/2>& b0, v_reg::w_type, n/2>& b1) { for( int i = 0; i < (n/2); i++ ) { b0.s[i] = a.s[i]; b1.s[i] = a.s[i+(n/2)]; } } //! @cond IGNORED template inline v_reg::int_type, n> v_reinterpret_as_int(const v_reg<_Tp, n>& a) { v_reg::int_type, n> c; for( int i = 0; i < n; i++ ) c.s[i] = V_TypeTraits<_Tp>::reinterpret_int(a.s[i]); return c; } template inline v_reg::uint_type, n> v_reinterpret_as_uint(const v_reg<_Tp, n>& a) { v_reg::uint_type, n> c; for( int i = 0; i < n; i++ ) c.s[i] = V_TypeTraits<_Tp>::reinterpret_uint(a.s[i]); return c; } //! @endcond /** @brief Interleave two vectors Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} --------------- {A1 B1 A2 B2} and {A3 B3 A4 B4} @endcode For all types except 64-bit. */ template inline void v_zip( const v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1 ) { int i; for( i = 0; i < n/2; i++ ) { b0.s[i*2] = a0.s[i]; b0.s[i*2+1] = a1.s[i]; } for( ; i < n; i++ ) { b1.s[i*2-n] = a0.s[i]; b1.s[i*2-n+1] = a1.s[i]; } } /** @brief Load register contents from memory @param ptr pointer to memory block with data @return register object @note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x16, int ==> cv::v_int32x4, etc. */ template inline v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> v_load(const _Tp* ptr) { return v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes>(ptr); } /** @brief Load register contents from memory (aligned) similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary) */ template inline v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> v_load_aligned(const _Tp* ptr) { return v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes>(ptr); } /** @brief Load register contents from two memory blocks @param loptr memory block containing data for first half (0..n/2) @param hiptr memory block containing data for second half (n/2..n) @code{.cpp} int lo[2] = { 1, 2 }, hi[2] = { 3, 4 }; v_int32x4 r = v_load_halves(lo, hi); @endcode */ template inline v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> v_load_halves(const _Tp* loptr, const _Tp* hiptr) { v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> c; for( int i = 0; i < c.nlanes/2; i++ ) { c.s[i] = loptr[i]; c.s[i+c.nlanes/2] = hiptr[i]; } return c; } /** @brief Load register contents from memory with double expand Same as cv::v_load, but result pack type will be 2x wider than memory type. @code{.cpp} short buf[4] = {1, 2, 3, 4}; // type is int16 v_int32x4 r = v_load_expand(buf); // r = {1, 2, 3, 4} - type is int32 @endcode For 8-, 16-, 32-bit integer source types. */ template inline v_reg::w_type, V_SIMD128Traits<_Tp>::nlanes / 2> v_load_expand(const _Tp* ptr) { typedef typename V_TypeTraits<_Tp>::w_type w_type; v_reg::nlanes> c; for( int i = 0; i < c.nlanes; i++ ) { c.s[i] = ptr[i]; } return c; } /** @brief Load register contents from memory with quad expand Same as cv::v_load_expand, but result type is 4 times wider than source. @code{.cpp} char buf[4] = {1, 2, 3, 4}; // type is int8 v_int32x4 r = v_load_q(buf); // r = {1, 2, 3, 4} - type is int32 @endcode For 8-bit integer source types. */ template inline v_reg::q_type, V_SIMD128Traits<_Tp>::nlanes / 4> v_load_expand_q(const _Tp* ptr) { typedef typename V_TypeTraits<_Tp>::q_type q_type; v_reg::nlanes> c; for( int i = 0; i < c.nlanes; i++ ) { c.s[i] = ptr[i]; } return c; } /** @brief Load and deinterleave (4 channels) Load data from memory deinterleave and store to 4 registers. Scheme: @code {A1 B1 C1 D1 A2 B2 C2 D2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} @endcode For all types except 64-bit. */ template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, v_reg<_Tp, n>& b, v_reg<_Tp, n>& c) { int i, i3; for( i = i3 = 0; i < n; i++, i3 += 3 ) { a.s[i] = ptr[i3]; b.s[i] = ptr[i3+1]; c.s[i] = ptr[i3+2]; } } /** @brief Load and deinterleave (3 channels) Load data from memory deinterleave and store to 3 registers. Scheme: @code {A1 B1 C1 A2 B2 C2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} @endcode For all types except 64-bit. */ template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, v_reg<_Tp, n>& b, v_reg<_Tp, n>& c, v_reg<_Tp, n>& d) { int i, i4; for( i = i4 = 0; i < n; i++, i4 += 4 ) { a.s[i] = ptr[i4]; b.s[i] = ptr[i4+1]; c.s[i] = ptr[i4+2]; d.s[i] = ptr[i4+3]; } } /** @brief Interleave and store (3 channels) Interleave and store data from 3 registers to memory. Scheme: @code {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} ==> {A1 B1 C1 D1 A2 B2 C2 D2 ...} @endcode For all types except 64-bit. */ template inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c) { int i, i3; for( i = i3 = 0; i < n; i++, i3 += 3 ) { ptr[i3] = a.s[i]; ptr[i3+1] = b.s[i]; ptr[i3+2] = c.s[i]; } } /** @brief Interleave and store (4 channels) Interleave and store data from 4 registers to memory. Scheme: @code {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} ==> {A1 B1 C1 D1 A2 B2 C2 D2 ...} @endcode For all types except 64-bit. */ template inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, const v_reg<_Tp, n>& d) { int i, i4; for( i = i4 = 0; i < n; i++, i4 += 4 ) { ptr[i4] = a.s[i]; ptr[i4+1] = b.s[i]; ptr[i4+2] = c.s[i]; ptr[i4+3] = d.s[i]; } } /** @brief Store data to memory Store register contents to memory. Scheme: @code REG {A B C D} ==> MEM {A B C D} @endcode Pointer can be unaligned. */ template inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) ptr[i] = a.s[i]; } /** @brief Store data to memory (lower half) Store lower half of register contents to memory. Scheme: @code REG {A B C D} ==> MEM {A B} @endcode */ template inline void v_store_low(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < (n/2); i++ ) ptr[i] = a.s[i]; } /** @brief Store data to memory (higher half) Store higher half of register contents to memory. Scheme: @code REG {A B C D} ==> MEM {C D} @endcode */ template inline void v_store_high(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < (n/2); i++ ) ptr[i] = a.s[i+(n/2)]; } /** @brief Store data to memory (aligned) Store register contents to memory. Scheme: @code REG {A B C D} ==> MEM {A B C D} @endcode Pointer __should__ be aligned by 16-byte boundary. */ template inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) ptr[i] = a.s[i]; } /** @brief Combine vector from first elements of two vectors Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} --------------- {A1 A2 B1 B2} @endcode For all types except 64-bit. */ template inline v_reg<_Tp, n> v_combine_low(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < (n/2); i++ ) { c.s[i] = a.s[i]; c.s[i+(n/2)] = b.s[i]; } return c; } /** @brief Combine vector from last elements of two vectors Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} --------------- {A3 A4 B3 B4} @endcode For all types except 64-bit. */ template inline v_reg<_Tp, n> v_combine_high(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < (n/2); i++ ) { c.s[i] = a.s[i+(n/2)]; c.s[i+(n/2)] = b.s[i+(n/2)]; } return c; } /** @brief Combine two vectors from lower and higher parts of two other vectors @code{.cpp} low = cv::v_combine_low(a, b); high = cv::v_combine_high(a, b); @endcode */ template inline void v_recombine(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, v_reg<_Tp, n>& low, v_reg<_Tp, n>& high) { for( int i = 0; i < (n/2); i++ ) { low.s[i] = a.s[i]; low.s[i+(n/2)] = b.s[i]; high.s[i] = a.s[i+(n/2)]; high.s[i+(n/2)] = b.s[i+(n/2)]; } } /** @brief Vector extract Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} ======================== shift = 1 {A2 A3 A4 B1} shift = 2 {A3 A4 B1 B2} shift = 3 {A4 B1 B2 B3} @endcode Restriction: 0 <= shift < nlanes Usage: @code v_int32x4 a, b, c; c = v_extract<2>(a, b); @endcode For integer types only. */ template inline v_reg<_Tp, n> v_extract(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> r; const int shift = n - s; int i = 0; for (; i < shift; ++i) r.s[i] = a.s[i+s]; for (; i < n; ++i) r.s[i] = b.s[i-shift]; return r; } /** @brief Round Rounds each value. Input type is float vector ==> output type is int vector.*/ template inline v_reg v_round(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) c.s[i] = cvRound(a.s[i]); return c; } /** @brief Floor Floor each value. Input type is float vector ==> output type is int vector.*/ template inline v_reg v_floor(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) c.s[i] = cvFloor(a.s[i]); return c; } /** @brief Ceil Ceil each value. Input type is float vector ==> output type is int vector.*/ template inline v_reg v_ceil(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) c.s[i] = cvCeil(a.s[i]); return c; } /** @brief Trunc Truncate each value. Input type is float vector ==> output type is int vector.*/ template inline v_reg v_trunc(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) c.s[i] = (int)(a.s[i]); return c; } /** @overload */ template inline v_reg v_round(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) { c.s[i] = cvRound(a.s[i]); c.s[i+n] = 0; } return c; } /** @overload */ template inline v_reg v_floor(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) { c.s[i] = cvFloor(a.s[i]); c.s[i+n] = 0; } return c; } /** @overload */ template inline v_reg v_ceil(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) { c.s[i] = cvCeil(a.s[i]); c.s[i+n] = 0; } return c; } /** @overload */ template inline v_reg v_trunc(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) { c.s[i] = cvCeil(a.s[i]); c.s[i+n] = 0; } return c; } /** @brief Convert to float Supported input type is cv::v_int32x4. */ template inline v_reg v_cvt_f32(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) c.s[i] = (float)a.s[i]; return c; } /** @brief Convert to double Supported input type is cv::v_int32x4. */ template inline v_reg v_cvt_f64(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) c.s[i] = (double)a.s[i]; return c; } /** @brief Convert to double Supported input type is cv::v_float32x4. */ template inline v_reg v_cvt_f64(const v_reg& a) { v_reg c; for( int i = 0; i < n; i++ ) c.s[i] = (double)a.s[i]; return c; } /** @brief Transpose 4x4 matrix Scheme: @code a0 {A1 A2 A3 A4} a1 {B1 B2 B3 B4} a2 {C1 C2 C3 C4} a3 {D1 D2 D3 D4} =============== b0 {A1 B1 C1 D1} b1 {A2 B2 C2 D2} b2 {A3 B3 C3 D3} b3 {A4 B4 C4 D4} @endcode */ template inline void v_transpose4x4( v_reg<_Tp, 4>& a0, const v_reg<_Tp, 4>& a1, const v_reg<_Tp, 4>& a2, const v_reg<_Tp, 4>& a3, v_reg<_Tp, 4>& b0, v_reg<_Tp, 4>& b1, v_reg<_Tp, 4>& b2, v_reg<_Tp, 4>& b3 ) { b0 = v_reg<_Tp, 4>(a0.s[0], a1.s[0], a2.s[0], a3.s[0]); b1 = v_reg<_Tp, 4>(a0.s[1], a1.s[1], a2.s[1], a3.s[1]); b2 = v_reg<_Tp, 4>(a0.s[2], a1.s[2], a2.s[2], a3.s[2]); b3 = v_reg<_Tp, 4>(a0.s[3], a1.s[3], a2.s[3], a3.s[3]); } //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_INIT_ZERO(_Tpvec, _Tp, suffix) \ inline _Tpvec v_setzero_##suffix() { return _Tpvec::zero(); } //! @name Init with zero //! @{ //! @brief Create new vector with zero elements OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x16, schar, s8) OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x8, short, s16) OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x4, int, s32) OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x4, float, f32) OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x2, double, f64) OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x2, uint64, u64) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x2, int64, s64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_INIT_VAL(_Tpvec, _Tp, suffix) \ inline _Tpvec v_setall_##suffix(_Tp val) { return _Tpvec::all(val); } //! @name Init with value //! @{ //! @brief Create new vector with elements set to a specific value OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x16, schar, s8) OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x8, short, s16) OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x4, int, s32) OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x4, float, f32) OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x2, double, f64) OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x2, uint64, u64) OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x2, int64, s64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_REINTERPRET(_Tpvec, _Tp, suffix) \ template inline _Tpvec \ v_reinterpret_as_##suffix(const v_reg<_Tp0, n0>& a) \ { return a.template reinterpret_as<_Tp, _Tpvec::nlanes>(); } //! @name Reinterpret //! @{ //! @brief Convert vector to different type without modifying underlying data. OPENCV_HAL_IMPL_C_REINTERPRET(v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_C_REINTERPRET(v_int8x16, schar, s8) OPENCV_HAL_IMPL_C_REINTERPRET(v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_C_REINTERPRET(v_int16x8, short, s16) OPENCV_HAL_IMPL_C_REINTERPRET(v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_C_REINTERPRET(v_int32x4, int, s32) OPENCV_HAL_IMPL_C_REINTERPRET(v_float32x4, float, f32) OPENCV_HAL_IMPL_C_REINTERPRET(v_float64x2, double, f64) OPENCV_HAL_IMPL_C_REINTERPRET(v_uint64x2, uint64, u64) OPENCV_HAL_IMPL_C_REINTERPRET(v_int64x2, int64, s64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_SHIFTL(_Tpvec, _Tp) \ template inline _Tpvec v_shl(const _Tpvec& a) \ { return a << n; } //! @name Left shift //! @{ //! @brief Shift left OPENCV_HAL_IMPL_C_SHIFTL(v_uint16x8, ushort) OPENCV_HAL_IMPL_C_SHIFTL(v_int16x8, short) OPENCV_HAL_IMPL_C_SHIFTL(v_uint32x4, unsigned) OPENCV_HAL_IMPL_C_SHIFTL(v_int32x4, int) OPENCV_HAL_IMPL_C_SHIFTL(v_uint64x2, uint64) OPENCV_HAL_IMPL_C_SHIFTL(v_int64x2, int64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_SHIFTR(_Tpvec, _Tp) \ template inline _Tpvec v_shr(const _Tpvec& a) \ { return a >> n; } //! @name Right shift //! @{ //! @brief Shift right OPENCV_HAL_IMPL_C_SHIFTR(v_uint16x8, ushort) OPENCV_HAL_IMPL_C_SHIFTR(v_int16x8, short) OPENCV_HAL_IMPL_C_SHIFTR(v_uint32x4, unsigned) OPENCV_HAL_IMPL_C_SHIFTR(v_int32x4, int) OPENCV_HAL_IMPL_C_SHIFTR(v_uint64x2, uint64) OPENCV_HAL_IMPL_C_SHIFTR(v_int64x2, int64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_RSHIFTR(_Tpvec, _Tp) \ template inline _Tpvec v_rshr(const _Tpvec& a) \ { \ _Tpvec c; \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ c.s[i] = (_Tp)((a.s[i] + ((_Tp)1 << (n - 1))) >> n); \ return c; \ } //! @name Rounding shift //! @{ //! @brief Rounding shift right OPENCV_HAL_IMPL_C_RSHIFTR(v_uint16x8, ushort) OPENCV_HAL_IMPL_C_RSHIFTR(v_int16x8, short) OPENCV_HAL_IMPL_C_RSHIFTR(v_uint32x4, unsigned) OPENCV_HAL_IMPL_C_RSHIFTR(v_int32x4, int) OPENCV_HAL_IMPL_C_RSHIFTR(v_uint64x2, uint64) OPENCV_HAL_IMPL_C_RSHIFTR(v_int64x2, int64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_PACK(_Tpvec, _Tpnvec, _Tpn, pack_suffix) \ inline _Tpnvec v_##pack_suffix(const _Tpvec& a, const _Tpvec& b) \ { \ _Tpnvec c; \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ { \ c.s[i] = saturate_cast<_Tpn>(a.s[i]); \ c.s[i+_Tpvec::nlanes] = saturate_cast<_Tpn>(b.s[i]); \ } \ return c; \ } //! @name Pack //! @{ //! @brief Pack values from two vectors to one //! //! Return vector type have twice more elements than input vector types. Variant with _u_ suffix also //! converts to corresponding unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_PACK(v_uint16x8, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_PACK(v_int16x8, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_PACK(v_uint32x4, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_PACK(v_int32x4, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_PACK(v_uint64x2, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_PACK(v_int64x2, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_PACK(v_int16x8, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_PACK(v_int32x4, v_uint16x8, ushort, pack_u) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_RSHR_PACK(_Tpvec, _Tp, _Tpnvec, _Tpn, pack_suffix) \ template inline _Tpnvec v_rshr_##pack_suffix(const _Tpvec& a, const _Tpvec& b) \ { \ _Tpnvec c; \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ { \ c.s[i] = saturate_cast<_Tpn>((a.s[i] + ((_Tp)1 << (n - 1))) >> n); \ c.s[i+_Tpvec::nlanes] = saturate_cast<_Tpn>((b.s[i] + ((_Tp)1 << (n - 1))) >> n); \ } \ return c; \ } //! @name Pack with rounding shift //! @{ //! @brief Pack values from two vectors to one with rounding shift //! //! Values from the input vectors will be shifted right by _n_ bits with rounding, converted to narrower //! type and returned in the result vector. Variant with _u_ suffix converts to unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_RSHR_PACK(v_uint16x8, ushort, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int16x8, short, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_uint32x4, unsigned, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int32x4, int, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_uint64x2, uint64, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int64x2, int64, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int16x8, short, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int32x4, int, v_uint16x8, ushort, pack_u) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_PACK_STORE(_Tpvec, _Tp, _Tpnvec, _Tpn, pack_suffix) \ inline void v_##pack_suffix##_store(_Tpn* ptr, const _Tpvec& a) \ { \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ ptr[i] = saturate_cast<_Tpn>(a.s[i]); \ } //! @name Pack and store //! @{ //! @brief Store values from the input vector into memory with pack //! //! Values will be stored into memory with saturating conversion to narrower type. //! Variant with _u_ suffix converts to corresponding unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_PACK_STORE(v_uint16x8, ushort, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int16x8, short, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_uint32x4, unsigned, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int32x4, int, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_uint64x2, uint64, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int64x2, int64, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int16x8, short, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_PACK_STORE(v_int32x4, int, v_uint16x8, ushort, pack_u) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(_Tpvec, _Tp, _Tpnvec, _Tpn, pack_suffix) \ template inline void v_rshr_##pack_suffix##_store(_Tpn* ptr, const _Tpvec& a) \ { \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ ptr[i] = saturate_cast<_Tpn>((a.s[i] + ((_Tp)1 << (n - 1))) >> n); \ } //! @name Pack and store with rounding shift //! @{ //! @brief Store values from the input vector into memory with pack //! //! Values will be shifted _n_ bits right with rounding, converted to narrower type and stored into //! memory. Variant with _u_ suffix converts to unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_uint16x8, ushort, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int16x8, short, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_uint32x4, unsigned, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int32x4, int, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_uint64x2, uint64, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int64x2, int64, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int16x8, short, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int32x4, int, v_uint16x8, ushort, pack_u) //! @} /** @brief Matrix multiplication Scheme: @code {A0 A1 A2 A3} |V0| {B0 B1 B2 B3} |V1| {C0 C1 C2 C3} |V2| {D0 D1 D2 D3} x |V3| ==================== {R0 R1 R2 R3}, where: R0 = A0V0 + A1V1 + A2V2 + A3V3, R1 = B0V0 + B1V1 + B2V2 + B3V3 ... @endcode */ inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) { return v_float32x4(v.s[0]*m0.s[0] + v.s[1]*m1.s[0] + v.s[2]*m2.s[0] + v.s[3]*m3.s[0], v.s[0]*m0.s[1] + v.s[1]*m1.s[1] + v.s[2]*m2.s[1] + v.s[3]*m3.s[1], v.s[0]*m0.s[2] + v.s[1]*m1.s[2] + v.s[2]*m2.s[2] + v.s[3]*m3.s[2], v.s[0]*m0.s[3] + v.s[1]*m1.s[3] + v.s[2]*m2.s[3] + v.s[3]*m3.s[3]); } //! @} } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/hal/intrin_neon.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HAL_INTRIN_NEON_HPP__ #define __OPENCV_HAL_INTRIN_NEON_HPP__ #include namespace cv { //! @cond IGNORED #define CV_SIMD128 1 struct v_uint8x16 { typedef uchar lane_type; enum { nlanes = 16 }; v_uint8x16() {} explicit v_uint8x16(uint8x16_t v) : val(v) {} v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) { uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; val = vld1q_u8(v); } uchar get0() const { return vgetq_lane_u8(val, 0); } uint8x16_t val; }; struct v_int8x16 { typedef schar lane_type; enum { nlanes = 16 }; v_int8x16() {} explicit v_int8x16(int8x16_t v) : val(v) {} v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) { schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; val = vld1q_s8(v); } schar get0() const { return vgetq_lane_s8(val, 0); } int8x16_t val; }; struct v_uint16x8 { typedef ushort lane_type; enum { nlanes = 8 }; v_uint16x8() {} explicit v_uint16x8(uint16x8_t v) : val(v) {} v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) { ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; val = vld1q_u16(v); } ushort get0() const { return vgetq_lane_u16(val, 0); } uint16x8_t val; }; struct v_int16x8 { typedef short lane_type; enum { nlanes = 8 }; v_int16x8() {} explicit v_int16x8(int16x8_t v) : val(v) {} v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) { short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; val = vld1q_s16(v); } short get0() const { return vgetq_lane_s16(val, 0); } int16x8_t val; }; struct v_uint32x4 { typedef unsigned lane_type; enum { nlanes = 4 }; v_uint32x4() {} explicit v_uint32x4(uint32x4_t v) : val(v) {} v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) { unsigned v[] = {v0, v1, v2, v3}; val = vld1q_u32(v); } unsigned get0() const { return vgetq_lane_u32(val, 0); } uint32x4_t val; }; struct v_int32x4 { typedef int lane_type; enum { nlanes = 4 }; v_int32x4() {} explicit v_int32x4(int32x4_t v) : val(v) {} v_int32x4(int v0, int v1, int v2, int v3) { int v[] = {v0, v1, v2, v3}; val = vld1q_s32(v); } int get0() const { return vgetq_lane_s32(val, 0); } int32x4_t val; }; struct v_float32x4 { typedef float lane_type; enum { nlanes = 4 }; v_float32x4() {} explicit v_float32x4(float32x4_t v) : val(v) {} v_float32x4(float v0, float v1, float v2, float v3) { float v[] = {v0, v1, v2, v3}; val = vld1q_f32(v); } float get0() const { return vgetq_lane_f32(val, 0); } float32x4_t val; }; struct v_uint64x2 { typedef uint64 lane_type; enum { nlanes = 2 }; v_uint64x2() {} explicit v_uint64x2(uint64x2_t v) : val(v) {} v_uint64x2(unsigned v0, unsigned v1) { uint64 v[] = {v0, v1}; val = vld1q_u64(v); } uint64 get0() const { return vgetq_lane_u64(val, 0); } uint64x2_t val; }; struct v_int64x2 { typedef int64 lane_type; enum { nlanes = 2 }; v_int64x2() {} explicit v_int64x2(int64x2_t v) : val(v) {} v_int64x2(int v0, int v1) { int64 v[] = {v0, v1}; val = vld1q_s64(v); } int64 get0() const { return vgetq_lane_s64(val, 0); } int64x2_t val; }; #define OPENCV_HAL_IMPL_NEON_INIT(_Tpv, _Tp, suffix) \ inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(vdupq_n_##suffix((_Tp)0)); } \ inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(vdupq_n_##suffix(v)); } \ inline _Tpv##_t vreinterpretq_##suffix##_##suffix(_Tpv##_t v) { return v; } \ inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(vreinterpretq_u8_##suffix(v.val)); } \ inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(vreinterpretq_s8_##suffix(v.val)); } \ inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(vreinterpretq_u16_##suffix(v.val)); } \ inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpretq_s16_##suffix(v.val)); } \ inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(vreinterpretq_u32_##suffix(v.val)); } \ inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(vreinterpretq_s32_##suffix(v.val)); } \ inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(vreinterpretq_u64_##suffix(v.val)); } \ inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(vreinterpretq_s64_##suffix(v.val)); } \ inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(vreinterpretq_f32_##suffix(v.val)); } OPENCV_HAL_IMPL_NEON_INIT(uint8x16, uchar, u8) OPENCV_HAL_IMPL_NEON_INIT(int8x16, schar, s8) OPENCV_HAL_IMPL_NEON_INIT(uint16x8, ushort, u16) OPENCV_HAL_IMPL_NEON_INIT(int16x8, short, s16) OPENCV_HAL_IMPL_NEON_INIT(uint32x4, unsigned, u32) OPENCV_HAL_IMPL_NEON_INIT(int32x4, int, s32) OPENCV_HAL_IMPL_NEON_INIT(uint64x2, uint64, u64) OPENCV_HAL_IMPL_NEON_INIT(int64x2, int64, s64) OPENCV_HAL_IMPL_NEON_INIT(float32x4, float, f32) #define OPENCV_HAL_IMPL_NEON_PACK(_Tpvec, _Tp, hreg, suffix, _Tpwvec, wsuffix, pack, op) \ inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ { \ hreg a1 = vqmov##op##_##wsuffix(a.val), b1 = vqmov##op##_##wsuffix(b.val); \ return _Tpvec(vcombine_##suffix(a1, b1)); \ } \ inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ { \ hreg a1 = vqmov##op##_##wsuffix(a.val); \ vst1_##suffix(ptr, a1); \ } \ template inline \ _Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ { \ hreg a1 = vqrshr##op##_n_##wsuffix(a.val, n); \ hreg b1 = vqrshr##op##_n_##wsuffix(b.val, n); \ return _Tpvec(vcombine_##suffix(a1, b1)); \ } \ template inline \ void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ { \ hreg a1 = vqrshr##op##_n_##wsuffix(a.val, n); \ vst1_##suffix(ptr, a1); \ } OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_uint16x8, u16, pack, n) OPENCV_HAL_IMPL_NEON_PACK(v_int8x16, schar, int8x8_t, s8, v_int16x8, s16, pack, n) OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_uint32x4, u32, pack, n) OPENCV_HAL_IMPL_NEON_PACK(v_int16x8, short, int16x4_t, s16, v_int32x4, s32, pack, n) OPENCV_HAL_IMPL_NEON_PACK(v_uint32x4, unsigned, uint32x2_t, u32, v_uint64x2, u64, pack, n) OPENCV_HAL_IMPL_NEON_PACK(v_int32x4, int, int32x2_t, s32, v_int64x2, s64, pack, n) OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_int16x8, s16, pack_u, un) OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_int32x4, s32, pack_u, un) inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) { float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); res = vmlaq_lane_f32(res, m1.val, vl, 1); res = vmlaq_lane_f32(res, m2.val, vh, 0); res = vmlaq_lane_f32(res, m3.val, vh, 1); return v_float32x4(res); } #define OPENCV_HAL_IMPL_NEON_BIN_OP(bin_op, _Tpvec, intrin) \ inline _Tpvec operator bin_op (const _Tpvec& a, const _Tpvec& b) \ { \ return _Tpvec(intrin(a.val, b.val)); \ } \ inline _Tpvec& operator bin_op##= (_Tpvec& a, const _Tpvec& b) \ { \ a.val = intrin(a.val, b.val); \ return a; \ } OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint8x16, vqaddq_u8) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint8x16, vqsubq_u8) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int8x16, vqaddq_s8) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int8x16, vqsubq_s8) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint16x8, vqaddq_u16) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint16x8, vqsubq_u16) OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_uint16x8, vmulq_u16) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int16x8, vqaddq_s16) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int16x8, vqsubq_s16) OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_int16x8, vmulq_s16) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int32x4, vaddq_s32) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int32x4, vsubq_s32) OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_int32x4, vmulq_s32) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint32x4, vaddq_u32) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint32x4, vsubq_u32) OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_uint32x4, vmulq_u32) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_float32x4, vaddq_f32) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_float32x4, vsubq_f32) OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_float32x4, vmulq_f32) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int64x2, vaddq_s64) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int64x2, vsubq_s64) OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint64x2, vaddq_u64) OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint64x2, vsubq_u64) inline v_float32x4 operator / (const v_float32x4& a, const v_float32x4& b) { float32x4_t reciprocal = vrecpeq_f32(b.val); reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); return v_float32x4(vmulq_f32(a.val, reciprocal)); } inline v_float32x4& operator /= (v_float32x4& a, const v_float32x4& b) { float32x4_t reciprocal = vrecpeq_f32(b.val); reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); a.val = vmulq_f32(a.val, reciprocal); return a; } inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, v_int32x4& c, v_int32x4& d) { c.val = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); d.val = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); } inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, v_uint32x4& c, v_uint32x4& d) { c.val = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); d.val = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); } inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, v_uint64x2& c, v_uint64x2& d) { c.val = vmull_u32(vget_low_u32(a.val), vget_low_u32(b.val)); d.val = vmull_u32(vget_high_u32(a.val), vget_high_u32(b.val)); } inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) { int32x4_t c = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); int32x4_t d = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); int32x4x2_t cd = vuzpq_s32(c, d); return v_int32x4(vaddq_s32(cd.val[0], cd.val[1])); } #define OPENCV_HAL_IMPL_NEON_LOGIC_OP(_Tpvec, suffix) \ OPENCV_HAL_IMPL_NEON_BIN_OP(&, _Tpvec, vandq_##suffix) \ OPENCV_HAL_IMPL_NEON_BIN_OP(|, _Tpvec, vorrq_##suffix) \ OPENCV_HAL_IMPL_NEON_BIN_OP(^, _Tpvec, veorq_##suffix) \ inline _Tpvec operator ~ (const _Tpvec& a) \ { \ return _Tpvec(vreinterpretq_##suffix##_u8(vmvnq_u8(vreinterpretq_u8_##suffix(a.val)))); \ } OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint8x16, u8) OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int8x16, s8) OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint16x8, u16) OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int16x8, s16) OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint32x4, u32) OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int32x4, s32) OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint64x2, u64) OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int64x2, s64) #define OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(bin_op, intrin) \ inline v_float32x4 operator bin_op (const v_float32x4& a, const v_float32x4& b) \ { \ return v_float32x4(vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val)))); \ } \ inline v_float32x4& operator bin_op##= (v_float32x4& a, const v_float32x4& b) \ { \ a.val = vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val))); \ return a; \ } OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(&, vandq_s32) OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(|, vorrq_s32) OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(^, veorq_s32) inline v_float32x4 operator ~ (const v_float32x4& a) { return v_float32x4(vreinterpretq_f32_s32(vmvnq_s32(vreinterpretq_s32_f32(a.val)))); } inline v_float32x4 v_sqrt(const v_float32x4& x) { float32x4_t x1 = vmaxq_f32(x.val, vdupq_n_f32(FLT_MIN)); float32x4_t e = vrsqrteq_f32(x1); e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); return v_float32x4(vmulq_f32(x.val, e)); } inline v_float32x4 v_invsqrt(const v_float32x4& x) { float32x4_t e = vrsqrteq_f32(x.val); e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); return v_float32x4(e); } inline v_float32x4 v_abs(v_float32x4 x) { return v_float32x4(vabsq_f32(x.val)); } // TODO: exp, log, sin, cos #define OPENCV_HAL_IMPL_NEON_BIN_FUNC(_Tpvec, func, intrin) \ inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ { \ return _Tpvec(intrin(a.val, b.val)); \ } OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_min, vminq_u8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_max, vmaxq_u8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_min, vminq_s8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_max, vmaxq_s8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_min, vminq_u16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_max, vmaxq_u16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_min, vminq_s16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_max, vmaxq_s16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_min, vminq_u32) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_max, vmaxq_u32) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_min, vminq_s32) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_max, vmaxq_s32) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_min, vminq_f32) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_max, vmaxq_f32) #define OPENCV_HAL_IMPL_NEON_INT_CMP_OP(_Tpvec, cast, suffix, not_suffix) \ inline _Tpvec operator == (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(cast(vceqq_##suffix(a.val, b.val))); } \ inline _Tpvec operator != (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(cast(vmvnq_##not_suffix(vceqq_##suffix(a.val, b.val)))); } \ inline _Tpvec operator < (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(cast(vcltq_##suffix(a.val, b.val))); } \ inline _Tpvec operator > (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(cast(vcgtq_##suffix(a.val, b.val))); } \ inline _Tpvec operator <= (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(cast(vcleq_##suffix(a.val, b.val))); } \ inline _Tpvec operator >= (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(cast(vcgeq_##suffix(a.val, b.val))); } OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint8x16, OPENCV_HAL_NOP, u8, u8) OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int8x16, vreinterpretq_s8_u8, s8, u8) OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint16x8, OPENCV_HAL_NOP, u16, u16) OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int16x8, vreinterpretq_s16_u16, s16, u16) OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint32x4, OPENCV_HAL_NOP, u32, u32) OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int32x4, vreinterpretq_s32_u32, s32, u32) OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float32x4, vreinterpretq_f32_u32, f32, u32) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_add_wrap, vaddq_u8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_add_wrap, vaddq_s8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_add_wrap, vaddq_u16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_add_wrap, vaddq_s16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_sub_wrap, vsubq_u8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_sub_wrap, vsubq_s8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_sub_wrap, vsubq_u16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_sub_wrap, vsubq_s16) // TODO: absdiff for signed integers OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_absdiff, vabdq_u8) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_absdiff, vabdq_u16) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_absdiff, vabdq_u32) OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_absdiff, vabdq_f32) #define OPENCV_HAL_IMPL_NEON_BIN_FUNC2(_Tpvec, _Tpvec2, cast, func, intrin) \ inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ { \ return _Tpvec2(cast(intrin(a.val, b.val))); \ } OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int8x16, v_uint8x16, vreinterpretq_u8_s8, v_absdiff, vabdq_s8) OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int16x8, v_uint16x8, vreinterpretq_u16_s16, v_absdiff, vabdq_s16) OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int32x4, v_uint32x4, vreinterpretq_u32_s32, v_absdiff, vabdq_s32) inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) { v_float32x4 x(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); return v_sqrt(x); } inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) { return v_float32x4(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); } inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) { return v_float32x4(vmlaq_f32(c.val, a.val, b.val)); } // trade efficiency for convenience #define OPENCV_HAL_IMPL_NEON_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ inline _Tpvec operator << (const _Tpvec& a, int n) \ { return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)n))); } \ inline _Tpvec operator >> (const _Tpvec& a, int n) \ { return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)-n))); } \ template inline _Tpvec v_shl(const _Tpvec& a) \ { return _Tpvec(vshlq_n_##suffix(a.val, n)); } \ template inline _Tpvec v_shr(const _Tpvec& a) \ { return _Tpvec(vshrq_n_##suffix(a.val, n)); } \ template inline _Tpvec v_rshr(const _Tpvec& a) \ { return _Tpvec(vrshrq_n_##suffix(a.val, n)); } OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint8x16, u8, schar, s8) OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int8x16, s8, schar, s8) OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint16x8, u16, short, s16) OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int16x8, s16, short, s16) OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint32x4, u32, int, s32) OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int32x4, s32, int, s32) OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint64x2, u64, int64, s64) OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int64x2, s64, int64, s64) #define OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ inline _Tpvec v_load(const _Tp* ptr) \ { return _Tpvec(vld1q_##suffix(ptr)); } \ inline _Tpvec v_load_aligned(const _Tp* ptr) \ { return _Tpvec(vld1q_##suffix(ptr)); } \ inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ { return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr0), vld1_##suffix(ptr1))); } \ inline void v_store(_Tp* ptr, const _Tpvec& a) \ { vst1q_##suffix(ptr, a.val); } \ inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ { vst1q_##suffix(ptr, a.val); } \ inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ { vst1_##suffix(ptr, vget_low_##suffix(a.val)); } \ inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ { vst1_##suffix(ptr, vget_high_##suffix(a.val)); } OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int8x16, schar, s8) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int16x8, short, s16) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int32x4, int, s32) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint64x2, uint64, u64) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int64x2, int64, s64) OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float32x4, float, f32) #define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, scalartype, func, scalar_func) \ inline scalartype v_reduce_##func(const _Tpvec& a) \ { \ scalartype CV_DECL_ALIGNED(16) buf[4]; \ v_store_aligned(buf, a); \ scalartype s0 = scalar_func(buf[0], buf[1]); \ scalartype s1 = scalar_func(buf[2], buf[3]); \ return scalar_func(s0, s1); \ } OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, unsigned, sum, OPENCV_HAL_ADD) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int, sum, OPENCV_HAL_ADD) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int, max, std::max) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int, min, std::min) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float, sum, OPENCV_HAL_ADD) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float, max, std::max) OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float, min, std::min) inline int v_signmask(const v_uint8x16& a) { int8x8_t m0 = vcreate_s8(CV_BIG_UINT(0x0706050403020100)); uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), vcombine_s8(m0, m0)); uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(v0))); return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 8); } inline int v_signmask(const v_int8x16& a) { return v_signmask(v_reinterpret_as_u8(a)); } inline int v_signmask(const v_uint16x8& a) { int16x4_t m0 = vcreate_s16(CV_BIG_UINT(0x0003000200010000)); uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), vcombine_s16(m0, m0)); uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(v0)); return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 4); } inline int v_signmask(const v_int16x8& a) { return v_signmask(v_reinterpret_as_u16(a)); } inline int v_signmask(const v_uint32x4& a) { int32x2_t m0 = vcreate_s32(CV_BIG_UINT(0x0000000100000000)); uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), vcombine_s32(m0, m0)); uint64x2_t v1 = vpaddlq_u32(v0); return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 2); } inline int v_signmask(const v_int32x4& a) { return v_signmask(v_reinterpret_as_u32(a)); } inline int v_signmask(const v_float32x4& a) { return v_signmask(v_reinterpret_as_u32(a)); } #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ inline bool v_check_all(const v_##_Tpvec& a) \ { \ _Tpvec##_t v0 = vshrq_n_##suffix(vmvnq_##suffix(a.val), shift); \ uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) == 0; \ } \ inline bool v_check_any(const v_##_Tpvec& a) \ { \ _Tpvec##_t v0 = vshrq_n_##suffix(a.val, shift); \ uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) != 0; \ } OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint8x16, u8, 7) OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint16x8, u16, 15) OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint32x4, u32, 31) inline bool v_check_all(const v_int8x16& a) { return v_check_all(v_reinterpret_as_u8(a)); } inline bool v_check_all(const v_int16x8& a) { return v_check_all(v_reinterpret_as_u16(a)); } inline bool v_check_all(const v_int32x4& a) { return v_check_all(v_reinterpret_as_u32(a)); } inline bool v_check_all(const v_float32x4& a) { return v_check_all(v_reinterpret_as_u32(a)); } inline bool v_check_any(const v_int8x16& a) { return v_check_any(v_reinterpret_as_u8(a)); } inline bool v_check_any(const v_int16x8& a) { return v_check_any(v_reinterpret_as_u16(a)); } inline bool v_check_any(const v_int32x4& a) { return v_check_any(v_reinterpret_as_u32(a)); } inline bool v_check_any(const v_float32x4& a) { return v_check_any(v_reinterpret_as_u32(a)); } #define OPENCV_HAL_IMPL_NEON_SELECT(_Tpvec, suffix, usuffix) \ inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ { \ return _Tpvec(vbslq_##suffix(vreinterpretq_##usuffix##_##suffix(mask.val), a.val, b.val)); \ } OPENCV_HAL_IMPL_NEON_SELECT(v_uint8x16, u8, u8) OPENCV_HAL_IMPL_NEON_SELECT(v_int8x16, s8, u8) OPENCV_HAL_IMPL_NEON_SELECT(v_uint16x8, u16, u16) OPENCV_HAL_IMPL_NEON_SELECT(v_int16x8, s16, u16) OPENCV_HAL_IMPL_NEON_SELECT(v_uint32x4, u32, u32) OPENCV_HAL_IMPL_NEON_SELECT(v_int32x4, s32, u32) OPENCV_HAL_IMPL_NEON_SELECT(v_float32x4, f32, u32) #define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ { \ b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ b1.val = vmovl_##suffix(vget_high_##suffix(a.val)); \ } \ inline _Tpwvec v_load_expand(const _Tp* ptr) \ { \ return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ } OPENCV_HAL_IMPL_NEON_EXPAND(v_uint8x16, v_uint16x8, uchar, u8) OPENCV_HAL_IMPL_NEON_EXPAND(v_int8x16, v_int16x8, schar, s8) OPENCV_HAL_IMPL_NEON_EXPAND(v_uint16x8, v_uint32x4, ushort, u16) OPENCV_HAL_IMPL_NEON_EXPAND(v_int16x8, v_int32x4, short, s16) OPENCV_HAL_IMPL_NEON_EXPAND(v_uint32x4, v_uint64x2, uint, u32) OPENCV_HAL_IMPL_NEON_EXPAND(v_int32x4, v_int64x2, int, s32) inline v_uint32x4 v_load_expand_q(const uchar* ptr) { uint8x8_t v0 = vcreate_u8(*(unsigned*)ptr); uint16x4_t v1 = vget_low_u16(vmovl_u8(v0)); return v_uint32x4(vmovl_u16(v1)); } inline v_int32x4 v_load_expand_q(const schar* ptr) { int8x8_t v0 = vcreate_s8(*(unsigned*)ptr); int16x4_t v1 = vget_low_s16(vmovl_s8(v0)); return v_int32x4(vmovl_s16(v1)); } #define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ { \ _Tpvec##x2_t p = vzipq_##suffix(a0.val, a1.val); \ b0.val = p.val[0]; \ b1.val = p.val[1]; \ } \ inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ { \ return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ } \ inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ { \ return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ } \ inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ { \ c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ } OPENCV_HAL_IMPL_NEON_UNPACKS(uint8x16, u8) OPENCV_HAL_IMPL_NEON_UNPACKS(int8x16, s8) OPENCV_HAL_IMPL_NEON_UNPACKS(uint16x8, u16) OPENCV_HAL_IMPL_NEON_UNPACKS(int16x8, s16) OPENCV_HAL_IMPL_NEON_UNPACKS(uint32x4, u32) OPENCV_HAL_IMPL_NEON_UNPACKS(int32x4, s32) OPENCV_HAL_IMPL_NEON_UNPACKS(float32x4, f32) #define OPENCV_HAL_IMPL_NEON_EXTRACT(_Tpvec, suffix) \ template \ inline v_##_Tpvec v_extract(const v_##_Tpvec& a, const v_##_Tpvec& b) \ { \ return v_##_Tpvec(vextq_##suffix(a.val, b.val, s)); \ } OPENCV_HAL_IMPL_NEON_EXTRACT(uint8x16, u8) OPENCV_HAL_IMPL_NEON_EXTRACT(int8x16, s8) OPENCV_HAL_IMPL_NEON_EXTRACT(uint16x8, u16) OPENCV_HAL_IMPL_NEON_EXTRACT(int16x8, s16) OPENCV_HAL_IMPL_NEON_EXTRACT(uint32x4, u32) OPENCV_HAL_IMPL_NEON_EXTRACT(int32x4, s32) OPENCV_HAL_IMPL_NEON_EXTRACT(uint64x2, u64) OPENCV_HAL_IMPL_NEON_EXTRACT(int64x2, s64) OPENCV_HAL_IMPL_NEON_EXTRACT(float32x4, f32) inline v_int32x4 v_round(const v_float32x4& a) { static const int32x4_t v_sign = vdupq_n_s32(1 << 31), v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f)); int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(a.val))); return v_int32x4(vcvtq_s32_f32(vaddq_f32(a.val, vreinterpretq_f32_s32(v_addition)))); } inline v_int32x4 v_floor(const v_float32x4& a) { int32x4_t a1 = vcvtq_s32_f32(a.val); uint32x4_t mask = vcgtq_f32(vcvtq_f32_s32(a1), a.val); return v_int32x4(vaddq_s32(a1, vreinterpretq_s32_u32(mask))); } inline v_int32x4 v_ceil(const v_float32x4& a) { int32x4_t a1 = vcvtq_s32_f32(a.val); uint32x4_t mask = vcgtq_f32(a.val, vcvtq_f32_s32(a1)); return v_int32x4(vsubq_s32(a1, vreinterpretq_s32_u32(mask))); } inline v_int32x4 v_trunc(const v_float32x4& a) { return v_int32x4(vcvtq_s32_f32(a.val)); } #define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ v_##_Tpvec& b0, v_##_Tpvec& b1, \ v_##_Tpvec& b2, v_##_Tpvec& b3) \ { \ /* m00 m01 m02 m03 */ \ /* m10 m11 m12 m13 */ \ /* m20 m21 m22 m23 */ \ /* m30 m31 m32 m33 */ \ _Tpvec##x2_t t0 = vtrnq_##suffix(a0.val, a1.val); \ _Tpvec##x2_t t1 = vtrnq_##suffix(a2.val, a3.val); \ /* m00 m10 m02 m12 */ \ /* m01 m11 m03 m13 */ \ /* m20 m30 m22 m32 */ \ /* m21 m31 m23 m33 */ \ b0.val = vcombine_##suffix(vget_low_##suffix(t0.val[0]), vget_low_##suffix(t1.val[0])); \ b1.val = vcombine_##suffix(vget_low_##suffix(t0.val[1]), vget_low_##suffix(t1.val[1])); \ b2.val = vcombine_##suffix(vget_high_##suffix(t0.val[0]), vget_high_##suffix(t1.val[0])); \ b3.val = vcombine_##suffix(vget_high_##suffix(t0.val[1]), vget_high_##suffix(t1.val[1])); \ } OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u32) OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s32) OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f32) #define OPENCV_HAL_IMPL_NEON_INTERLEAVED(_Tpvec, _Tp, suffix) \ inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ { \ _Tpvec##x3_t v = vld3q_##suffix(ptr); \ a.val = v.val[0]; \ b.val = v.val[1]; \ c.val = v.val[2]; \ } \ inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ v_##_Tpvec& c, v_##_Tpvec& d) \ { \ _Tpvec##x4_t v = vld4q_##suffix(ptr); \ a.val = v.val[0]; \ b.val = v.val[1]; \ c.val = v.val[2]; \ d.val = v.val[3]; \ } \ inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, const v_##_Tpvec& c) \ { \ _Tpvec##x3_t v; \ v.val[0] = a.val; \ v.val[1] = b.val; \ v.val[2] = c.val; \ vst3q_##suffix(ptr, v); \ } \ inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ const v_##_Tpvec& c, const v_##_Tpvec& d) \ { \ _Tpvec##x4_t v; \ v.val[0] = a.val; \ v.val[1] = b.val; \ v.val[2] = c.val; \ v.val[3] = d.val; \ vst4q_##suffix(ptr, v); \ } OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint8x16, uchar, u8) OPENCV_HAL_IMPL_NEON_INTERLEAVED(int8x16, schar, s8) OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint16x8, ushort, u16) OPENCV_HAL_IMPL_NEON_INTERLEAVED(int16x8, short, s16) OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint32x4, unsigned, u32) OPENCV_HAL_IMPL_NEON_INTERLEAVED(int32x4, int, s32) OPENCV_HAL_IMPL_NEON_INTERLEAVED(float32x4, float, f32) inline v_float32x4 v_cvt_f32(const v_int32x4& a) { return v_float32x4(vcvtq_f32_s32(a.val)); } //! @endcond } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/hal/intrin_sse.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HAL_SSE_HPP__ #define __OPENCV_HAL_SSE_HPP__ #include #define CV_SIMD128 1 #define CV_SIMD128_64F 1 namespace cv { //! @cond IGNORED struct v_uint8x16 { typedef uchar lane_type; enum { nlanes = 16 }; v_uint8x16() {} explicit v_uint8x16(__m128i v) : val(v) {} v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) { val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, (char)v4, (char)v5, (char)v6, (char)v7, (char)v8, (char)v9, (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15); } uchar get0() const { return (uchar)_mm_cvtsi128_si32(val); } __m128i val; }; struct v_int8x16 { typedef schar lane_type; enum { nlanes = 16 }; v_int8x16() {} explicit v_int8x16(__m128i v) : val(v) {} v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) { val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, (char)v4, (char)v5, (char)v6, (char)v7, (char)v8, (char)v9, (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15); } schar get0() const { return (schar)_mm_cvtsi128_si32(val); } __m128i val; }; struct v_uint16x8 { typedef ushort lane_type; enum { nlanes = 8 }; v_uint16x8() {} explicit v_uint16x8(__m128i v) : val(v) {} v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) { val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, (short)v4, (short)v5, (short)v6, (short)v7); } ushort get0() const { return (ushort)_mm_cvtsi128_si32(val); } __m128i val; }; struct v_int16x8 { typedef short lane_type; enum { nlanes = 8 }; v_int16x8() {} explicit v_int16x8(__m128i v) : val(v) {} v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) { val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, (short)v4, (short)v5, (short)v6, (short)v7); } short get0() const { return (short)_mm_cvtsi128_si32(val); } __m128i val; }; struct v_uint32x4 { typedef unsigned lane_type; enum { nlanes = 4 }; v_uint32x4() {} explicit v_uint32x4(__m128i v) : val(v) {} v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) { val = _mm_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3); } unsigned get0() const { return (unsigned)_mm_cvtsi128_si32(val); } __m128i val; }; struct v_int32x4 { typedef int lane_type; enum { nlanes = 4 }; v_int32x4() {} explicit v_int32x4(__m128i v) : val(v) {} v_int32x4(int v0, int v1, int v2, int v3) { val = _mm_setr_epi32(v0, v1, v2, v3); } int get0() const { return _mm_cvtsi128_si32(val); } __m128i val; }; struct v_float32x4 { typedef float lane_type; enum { nlanes = 4 }; v_float32x4() {} explicit v_float32x4(__m128 v) : val(v) {} v_float32x4(float v0, float v1, float v2, float v3) { val = _mm_setr_ps(v0, v1, v2, v3); } float get0() const { return _mm_cvtss_f32(val); } __m128 val; }; struct v_uint64x2 { typedef uint64 lane_type; enum { nlanes = 2 }; v_uint64x2() {} explicit v_uint64x2(__m128i v) : val(v) {} v_uint64x2(uint64 v0, uint64 v1) { val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); } uint64 get0() const { int a = _mm_cvtsi128_si32(val); int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); return (unsigned)a | ((uint64)(unsigned)b << 32); } __m128i val; }; struct v_int64x2 { typedef int64 lane_type; enum { nlanes = 2 }; v_int64x2() {} explicit v_int64x2(__m128i v) : val(v) {} v_int64x2(int64 v0, int64 v1) { val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); } int64 get0() const { int a = _mm_cvtsi128_si32(val); int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); } __m128i val; }; struct v_float64x2 { typedef double lane_type; enum { nlanes = 2 }; v_float64x2() {} explicit v_float64x2(__m128d v) : val(v) {} v_float64x2(double v0, double v1) { val = _mm_setr_pd(v0, v1); } double get0() const { return _mm_cvtsd_f64(val); } __m128d val; }; #define OPENCV_HAL_IMPL_SSE_INITVEC(_Tpvec, _Tp, suffix, zsuffix, ssuffix, _Tps, cast) \ inline _Tpvec v_setzero_##suffix() { return _Tpvec(_mm_setzero_##zsuffix()); } \ inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(_mm_set1_##ssuffix((_Tps)v)); } \ template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ { return _Tpvec(cast(a.val)); } OPENCV_HAL_IMPL_SSE_INITVEC(v_uint8x16, uchar, u8, si128, epi8, char, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_INITVEC(v_int8x16, schar, s8, si128, epi8, char, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_INITVEC(v_uint16x8, ushort, u16, si128, epi16, short, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_INITVEC(v_int16x8, short, s16, si128, epi16, short, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_INITVEC(v_uint32x4, unsigned, u32, si128, epi32, int, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_INITVEC(v_int32x4, int, s32, si128, epi32, int, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_INITVEC(v_float32x4, float, f32, ps, ps, float, _mm_castsi128_ps) OPENCV_HAL_IMPL_SSE_INITVEC(v_float64x2, double, f64, pd, pd, double, _mm_castsi128_pd) inline v_uint64x2 v_setzero_u64() { return v_uint64x2(_mm_setzero_si128()); } inline v_int64x2 v_setzero_s64() { return v_int64x2(_mm_setzero_si128()); } inline v_uint64x2 v_setall_u64(uint64 val) { return v_uint64x2(val, val); } inline v_int64x2 v_setall_s64(int64 val) { return v_int64x2(val, val); } template inline v_uint64x2 v_reinterpret_as_u64(const _Tpvec& a) { return v_uint64x2(a.val); } template inline v_int64x2 v_reinterpret_as_s64(const _Tpvec& a) { return v_int64x2(a.val); } inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& a) { return v_float32x4(_mm_castsi128_ps(a.val)); } inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& a) { return v_float32x4(_mm_castsi128_ps(a.val)); } inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& a) { return v_float64x2(_mm_castsi128_pd(a.val)); } inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& a) { return v_float64x2(_mm_castsi128_pd(a.val)); } #define OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(_Tpvec, suffix) \ inline _Tpvec v_reinterpret_as_##suffix(const v_float32x4& a) \ { return _Tpvec(_mm_castps_si128(a.val)); } \ inline _Tpvec v_reinterpret_as_##suffix(const v_float64x2& a) \ { return _Tpvec(_mm_castpd_si128(a.val)); } OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint8x16, u8) OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int8x16, s8) OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint16x8, u16) OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int16x8, s16) OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint32x4, u32) OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int32x4, s32) OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint64x2, u64) OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int64x2, s64) inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) {return a; } inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) {return a; } inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) {return v_float32x4(_mm_castpd_ps(a.val)); } inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) {return v_float64x2(_mm_castps_pd(a.val)); } //////////////// PACK /////////////// inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) { __m128i delta = _mm_set1_epi16(255); return v_uint8x16(_mm_packus_epi16(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)), _mm_subs_epu16(b.val, _mm_subs_epu16(b.val, delta)))); } inline void v_pack_store(uchar* ptr, const v_uint16x8& a) { __m128i delta = _mm_set1_epi16(255); __m128i a1 = _mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)); _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); } inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) { return v_uint8x16(_mm_packus_epi16(a.val, b.val)); } inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) { _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a.val, a.val)); } template inline v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) { // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); return v_uint8x16(_mm_packus_epi16(_mm_srli_epi16(_mm_adds_epu16(a.val, delta), n), _mm_srli_epi16(_mm_adds_epu16(b.val, delta), n))); } template inline void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) { __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); __m128i a1 = _mm_srli_epi16(_mm_adds_epu16(a.val, delta), n); _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); } template inline v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) { __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); return v_uint8x16(_mm_packus_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); } template inline void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) { __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); } inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) { return v_int8x16(_mm_packs_epi16(a.val, b.val)); } inline void v_pack_store(schar* ptr, v_int16x8& a) { _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a.val, a.val)); } template inline v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) { // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); return v_int8x16(_mm_packs_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); } template inline void v_rshr_pack_store(schar* ptr, const v_int16x8& a) { // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a1, a1)); } // bit-wise "mask ? a : b" inline __m128i v_select_si128(__m128i mask, __m128i a, __m128i b) { return _mm_xor_si128(b, _mm_and_si128(_mm_xor_si128(a, b), mask)); } inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) { __m128i z = _mm_setzero_si128(), maxval32 = _mm_set1_epi32(65535), delta32 = _mm_set1_epi32(32768); __m128i a1 = _mm_sub_epi32(v_select_si128(_mm_cmpgt_epi32(z, a.val), maxval32, a.val), delta32); __m128i b1 = _mm_sub_epi32(v_select_si128(_mm_cmpgt_epi32(z, b.val), maxval32, b.val), delta32); __m128i r = _mm_packs_epi32(a1, b1); return v_uint16x8(_mm_sub_epi16(r, _mm_set1_epi16(-32768))); } inline void v_pack_store(ushort* ptr, const v_uint32x4& a) { __m128i z = _mm_setzero_si128(), maxval32 = _mm_set1_epi32(65535), delta32 = _mm_set1_epi32(32768); __m128i a1 = _mm_sub_epi32(v_select_si128(_mm_cmpgt_epi32(z, a.val), maxval32, a.val), delta32); __m128i r = _mm_packs_epi32(a1, a1); _mm_storel_epi64((__m128i*)ptr, _mm_sub_epi16(r, _mm_set1_epi16(-32768))); } template inline v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) { __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); __m128i b1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(b.val, delta), n), delta32); return v_uint16x8(_mm_sub_epi16(_mm_packs_epi32(a1, b1), _mm_set1_epi16(-32768))); } template inline void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) { __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); _mm_storel_epi64((__m128i*)ptr, a2); } inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) { __m128i delta32 = _mm_set1_epi32(32768); __m128i r = _mm_packs_epi32(_mm_sub_epi32(a.val, delta32), _mm_sub_epi32(b.val, delta32)); return v_uint16x8(_mm_sub_epi16(r, _mm_set1_epi16(-32768))); } inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) { __m128i delta32 = _mm_set1_epi32(32768); __m128i a1 = _mm_sub_epi32(a.val, delta32); __m128i r = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); _mm_storel_epi64((__m128i*)ptr, r); } template inline v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) { __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); __m128i b1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(b.val, delta), n), delta32); __m128i b2 = _mm_sub_epi16(_mm_packs_epi32(b1, b1), _mm_set1_epi16(-32768)); return v_uint16x8(_mm_unpacklo_epi64(a2, b2)); } template inline void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) { __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); _mm_storel_epi64((__m128i*)ptr, a2); } inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) { return v_int16x8(_mm_packs_epi32(a.val, b.val)); } inline void v_pack_store(short* ptr, const v_int32x4& a) { _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a.val, a.val)); } template inline v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) { __m128i delta = _mm_set1_epi32(1 << (n-1)); return v_int16x8(_mm_packs_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); } template inline void v_rshr_pack_store(short* ptr, const v_int32x4& a) { __m128i delta = _mm_set1_epi32(1 << (n-1)); __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a1, a1)); } // [a0 0 | b0 0] [a1 0 | b1 0] inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) { __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); } inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) { __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); _mm_storel_epi64((__m128i*)ptr, a1); } // [a0 0 | b0 0] [a1 0 | b1 0] inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) { __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 return v_int32x4(_mm_unpacklo_epi32(v0, v1)); } inline void v_pack_store(int* ptr, const v_int64x2& a) { __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); _mm_storel_epi64((__m128i*)ptr, a1); } template inline v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) { uint64 delta = (uint64)1 << (n-1); v_uint64x2 delta2(delta, delta); __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); __m128i b1 = _mm_srli_epi64(_mm_add_epi64(b.val, delta2.val), n); __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); } template inline void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) { uint64 delta = (uint64)1 << (n-1); v_uint64x2 delta2(delta, delta); __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); _mm_storel_epi64((__m128i*)ptr, a2); } inline __m128i v_sign_epi64(__m128i a) { return _mm_shuffle_epi32(_mm_srai_epi32(a, 31), _MM_SHUFFLE(3, 3, 1, 1)); // x m0 | x m1 } inline __m128i v_srai_epi64(__m128i a, int imm) { __m128i smask = v_sign_epi64(a); return _mm_xor_si128(_mm_srli_epi64(_mm_xor_si128(a, smask), imm), smask); } template inline v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) { int64 delta = (int64)1 << (n-1); v_int64x2 delta2(delta, delta); __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); __m128i b1 = v_srai_epi64(_mm_add_epi64(b.val, delta2.val), n); __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 return v_int32x4(_mm_unpacklo_epi32(v0, v1)); } template inline void v_rshr_pack_store(int* ptr, const v_int64x2& a) { int64 delta = (int64)1 << (n-1); v_int64x2 delta2(delta, delta); __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); _mm_storel_epi64((__m128i*)ptr, a2); } inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) { __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); __m128 v3 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(3, 3, 3, 3)), m3.val); return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, v3))); } #define OPENCV_HAL_IMPL_SSE_BIN_OP(bin_op, _Tpvec, intrin) \ inline _Tpvec operator bin_op (const _Tpvec& a, const _Tpvec& b) \ { \ return _Tpvec(intrin(a.val, b.val)); \ } \ inline _Tpvec& operator bin_op##= (_Tpvec& a, const _Tpvec& b) \ { \ a.val = intrin(a.val, b.val); \ return a; \ } OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_uint8x16, _mm_adds_epu8) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_uint8x16, _mm_subs_epu8) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_int8x16, _mm_adds_epi8) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_int8x16, _mm_subs_epi8) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_uint16x8, _mm_adds_epu16) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_uint16x8, _mm_subs_epu16) OPENCV_HAL_IMPL_SSE_BIN_OP(*, v_uint16x8, _mm_mullo_epi16) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_int16x8, _mm_adds_epi16) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_int16x8, _mm_subs_epi16) OPENCV_HAL_IMPL_SSE_BIN_OP(*, v_int16x8, _mm_mullo_epi16) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_uint32x4, _mm_add_epi32) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_uint32x4, _mm_sub_epi32) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_int32x4, _mm_add_epi32) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_int32x4, _mm_sub_epi32) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_float32x4, _mm_add_ps) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_float32x4, _mm_sub_ps) OPENCV_HAL_IMPL_SSE_BIN_OP(*, v_float32x4, _mm_mul_ps) OPENCV_HAL_IMPL_SSE_BIN_OP(/, v_float32x4, _mm_div_ps) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_float64x2, _mm_add_pd) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_float64x2, _mm_sub_pd) OPENCV_HAL_IMPL_SSE_BIN_OP(*, v_float64x2, _mm_mul_pd) OPENCV_HAL_IMPL_SSE_BIN_OP(/, v_float64x2, _mm_div_pd) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_uint64x2, _mm_add_epi64) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_uint64x2, _mm_sub_epi64) OPENCV_HAL_IMPL_SSE_BIN_OP(+, v_int64x2, _mm_add_epi64) OPENCV_HAL_IMPL_SSE_BIN_OP(-, v_int64x2, _mm_sub_epi64) inline v_uint32x4 operator * (const v_uint32x4& a, const v_uint32x4& b) { __m128i c0 = _mm_mul_epu32(a.val, b.val); __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); __m128i d0 = _mm_unpacklo_epi32(c0, c1); __m128i d1 = _mm_unpackhi_epi32(c0, c1); return v_uint32x4(_mm_unpacklo_epi64(d0, d1)); } inline v_int32x4 operator * (const v_int32x4& a, const v_int32x4& b) { __m128i c0 = _mm_mul_epu32(a.val, b.val); __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); __m128i d0 = _mm_unpacklo_epi32(c0, c1); __m128i d1 = _mm_unpackhi_epi32(c0, c1); return v_int32x4(_mm_unpacklo_epi64(d0, d1)); } inline v_uint32x4& operator *= (v_uint32x4& a, const v_uint32x4& b) { a = a * b; return a; } inline v_int32x4& operator *= (v_int32x4& a, const v_int32x4& b) { a = a * b; return a; } inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, v_int32x4& c, v_int32x4& d) { __m128i v0 = _mm_mullo_epi16(a.val, b.val); __m128i v1 = _mm_mulhi_epi16(a.val, b.val); c.val = _mm_unpacklo_epi16(v0, v1); d.val = _mm_unpackhi_epi16(v0, v1); } inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, v_uint32x4& c, v_uint32x4& d) { __m128i v0 = _mm_mullo_epi16(a.val, b.val); __m128i v1 = _mm_mulhi_epu16(a.val, b.val); c.val = _mm_unpacklo_epi16(v0, v1); d.val = _mm_unpackhi_epi16(v0, v1); } inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, v_uint64x2& c, v_uint64x2& d) { __m128i c0 = _mm_mul_epu32(a.val, b.val); __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); c.val = _mm_unpacklo_epi64(c0, c1); d.val = _mm_unpackhi_epi64(c0, c1); } inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) { return v_int32x4(_mm_madd_epi16(a.val, b.val)); } #define OPENCV_HAL_IMPL_SSE_LOGIC_OP(_Tpvec, suffix, not_const) \ OPENCV_HAL_IMPL_SSE_BIN_OP(&, _Tpvec, _mm_and_##suffix) \ OPENCV_HAL_IMPL_SSE_BIN_OP(|, _Tpvec, _mm_or_##suffix) \ OPENCV_HAL_IMPL_SSE_BIN_OP(^, _Tpvec, _mm_xor_##suffix) \ inline _Tpvec operator ~ (const _Tpvec& a) \ { \ return _Tpvec(_mm_xor_##suffix(a.val, not_const)); \ } OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint8x16, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int8x16, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint16x8, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int16x8, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint32x4, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int32x4, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint64x2, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int64x2, si128, _mm_set1_epi32(-1)) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float32x4, ps, _mm_castsi128_ps(_mm_set1_epi32(-1))) OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float64x2, pd, _mm_castsi128_pd(_mm_set1_epi32(-1))) inline v_float32x4 v_sqrt(const v_float32x4& x) { return v_float32x4(_mm_sqrt_ps(x.val)); } inline v_float32x4 v_invsqrt(const v_float32x4& x) { static const __m128 _0_5 = _mm_set1_ps(0.5f), _1_5 = _mm_set1_ps(1.5f); __m128 t = x.val; __m128 h = _mm_mul_ps(t, _0_5); t = _mm_rsqrt_ps(t); t = _mm_mul_ps(t, _mm_sub_ps(_1_5, _mm_mul_ps(_mm_mul_ps(t, t), h))); return v_float32x4(t); } inline v_float64x2 v_sqrt(const v_float64x2& x) { return v_float64x2(_mm_sqrt_pd(x.val)); } inline v_float64x2 v_invsqrt(const v_float64x2& x) { static const __m128d v_1 = _mm_set1_pd(1.); return v_float64x2(_mm_div_pd(v_1, _mm_sqrt_pd(x.val))); } inline v_float32x4 v_abs(const v_float32x4& x) { return v_float32x4(_mm_and_ps(x.val, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)))); } inline v_float64x2 v_abs(const v_float64x2& x) { return v_float64x2(_mm_and_pd(x.val, _mm_castsi128_pd(_mm_srli_epi64(_mm_set1_epi32(-1), 1)))); } // TODO: exp, log, sin, cos #define OPENCV_HAL_IMPL_SSE_BIN_FUNC(_Tpvec, func, intrin) \ inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ { \ return _Tpvec(intrin(a.val, b.val)); \ } OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_min, _mm_min_epu8) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_max, _mm_max_epu8) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_min, _mm_min_epi16) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_max, _mm_max_epi16) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_min, _mm_min_ps) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_max, _mm_max_ps) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_min, _mm_min_pd) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_max, _mm_max_pd) inline v_int8x16 v_min(const v_int8x16& a, const v_int8x16& b) { __m128i delta = _mm_set1_epi8((char)-128); return v_int8x16(_mm_xor_si128(delta, _mm_min_epu8(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)))); } inline v_int8x16 v_max(const v_int8x16& a, const v_int8x16& b) { __m128i delta = _mm_set1_epi8((char)-128); return v_int8x16(_mm_xor_si128(delta, _mm_max_epu8(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)))); } inline v_uint16x8 v_min(const v_uint16x8& a, const v_uint16x8& b) { return v_uint16x8(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, b.val))); } inline v_uint16x8 v_max(const v_uint16x8& a, const v_uint16x8& b) { return v_uint16x8(_mm_adds_epu16(_mm_subs_epu16(a.val, b.val), b.val)); } inline v_uint32x4 v_min(const v_uint32x4& a, const v_uint32x4& b) { __m128i delta = _mm_set1_epi32((int)0x80000000); __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); return v_uint32x4(v_select_si128(mask, b.val, a.val)); } inline v_uint32x4 v_max(const v_uint32x4& a, const v_uint32x4& b) { __m128i delta = _mm_set1_epi32((int)0x80000000); __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); return v_uint32x4(v_select_si128(mask, a.val, b.val)); } inline v_int32x4 v_min(const v_int32x4& a, const v_int32x4& b) { return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), b.val, a.val)); } inline v_int32x4 v_max(const v_int32x4& a, const v_int32x4& b) { return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), a.val, b.val)); } #define OPENCV_HAL_IMPL_SSE_INT_CMP_OP(_Tpuvec, _Tpsvec, suffix, sbit) \ inline _Tpuvec operator == (const _Tpuvec& a, const _Tpuvec& b) \ { return _Tpuvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ inline _Tpuvec operator != (const _Tpuvec& a, const _Tpuvec& b) \ { \ __m128i not_mask = _mm_set1_epi32(-1); \ return _Tpuvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ } \ inline _Tpsvec operator == (const _Tpsvec& a, const _Tpsvec& b) \ { return _Tpsvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ inline _Tpsvec operator != (const _Tpsvec& a, const _Tpsvec& b) \ { \ __m128i not_mask = _mm_set1_epi32(-1); \ return _Tpsvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ } \ inline _Tpuvec operator < (const _Tpuvec& a, const _Tpuvec& b) \ { \ __m128i smask = _mm_set1_##suffix(sbit); \ return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask))); \ } \ inline _Tpuvec operator > (const _Tpuvec& a, const _Tpuvec& b) \ { \ __m128i smask = _mm_set1_##suffix(sbit); \ return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask))); \ } \ inline _Tpuvec operator <= (const _Tpuvec& a, const _Tpuvec& b) \ { \ __m128i smask = _mm_set1_##suffix(sbit); \ __m128i not_mask = _mm_set1_epi32(-1); \ __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask)); \ return _Tpuvec(_mm_xor_si128(res, not_mask)); \ } \ inline _Tpuvec operator >= (const _Tpuvec& a, const _Tpuvec& b) \ { \ __m128i smask = _mm_set1_##suffix(sbit); \ __m128i not_mask = _mm_set1_epi32(-1); \ __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask)); \ return _Tpuvec(_mm_xor_si128(res, not_mask)); \ } \ inline _Tpsvec operator < (const _Tpsvec& a, const _Tpsvec& b) \ { \ return _Tpsvec(_mm_cmpgt_##suffix(b.val, a.val)); \ } \ inline _Tpsvec operator > (const _Tpsvec& a, const _Tpsvec& b) \ { \ return _Tpsvec(_mm_cmpgt_##suffix(a.val, b.val)); \ } \ inline _Tpsvec operator <= (const _Tpsvec& a, const _Tpsvec& b) \ { \ __m128i not_mask = _mm_set1_epi32(-1); \ return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(a.val, b.val), not_mask)); \ } \ inline _Tpsvec operator >= (const _Tpsvec& a, const _Tpsvec& b) \ { \ __m128i not_mask = _mm_set1_epi32(-1); \ return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(b.val, a.val), not_mask)); \ } OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint8x16, v_int8x16, epi8, (char)-128) OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint16x8, v_int16x8, epi16, (short)-32768) OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint32x4, v_int32x4, epi32, (int)0x80000000) #define OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(_Tpvec, suffix) \ inline _Tpvec operator == (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ inline _Tpvec operator != (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(_mm_cmpneq_##suffix(a.val, b.val)); } \ inline _Tpvec operator < (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(_mm_cmplt_##suffix(a.val, b.val)); } \ inline _Tpvec operator > (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(_mm_cmpgt_##suffix(a.val, b.val)); } \ inline _Tpvec operator <= (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(_mm_cmple_##suffix(a.val, b.val)); } \ inline _Tpvec operator >= (const _Tpvec& a, const _Tpvec& b) \ { return _Tpvec(_mm_cmpge_##suffix(a.val, b.val)); } OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float32x4, ps) OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float64x2, pd) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_add_wrap, _mm_add_epi8) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_add_wrap, _mm_add_epi8) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_add_wrap, _mm_add_epi16) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_add_wrap, _mm_add_epi16) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_sub_wrap, _mm_sub_epi8) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_sub_wrap, _mm_sub_epi8) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_sub_wrap, _mm_sub_epi16) OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_sub_wrap, _mm_sub_epi16) #define OPENCV_HAL_IMPL_SSE_ABSDIFF_8_16(_Tpuvec, _Tpsvec, bits, smask32) \ inline _Tpuvec v_absdiff(const _Tpuvec& a, const _Tpuvec& b) \ { \ return _Tpuvec(_mm_add_epi##bits(_mm_subs_epu##bits(a.val, b.val), _mm_subs_epu##bits(b.val, a.val))); \ } \ inline _Tpuvec v_absdiff(const _Tpsvec& a, const _Tpsvec& b) \ { \ __m128i smask = _mm_set1_epi32(smask32); \ __m128i a1 = _mm_xor_si128(a.val, smask); \ __m128i b1 = _mm_xor_si128(b.val, smask); \ return _Tpuvec(_mm_add_epi##bits(_mm_subs_epu##bits(a1, b1), _mm_subs_epu##bits(b1, a1))); \ } OPENCV_HAL_IMPL_SSE_ABSDIFF_8_16(v_uint8x16, v_int8x16, 8, (int)0x80808080) OPENCV_HAL_IMPL_SSE_ABSDIFF_8_16(v_uint16x8, v_int16x8, 16, (int)0x80008000) inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) { return v_max(a, b) - v_min(a, b); } inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) { __m128i d = _mm_sub_epi32(a.val, b.val); __m128i m = _mm_cmpgt_epi32(b.val, a.val); return v_uint32x4(_mm_sub_epi32(_mm_xor_si128(d, m), m)); } #define OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(_Tpvec, _Tp, _Tpreg, suffix, absmask_vec) \ inline _Tpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ { \ _Tpreg absmask = _mm_castsi128_##suffix(absmask_vec); \ return _Tpvec(_mm_and_##suffix(_mm_sub_##suffix(a.val, b.val), absmask)); \ } \ inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ { \ _Tpreg res = _mm_add_##suffix(_mm_mul_##suffix(a.val, a.val), _mm_mul_##suffix(b.val, b.val)); \ return _Tpvec(_mm_sqrt_##suffix(res)); \ } \ inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ { \ _Tpreg res = _mm_add_##suffix(_mm_mul_##suffix(a.val, a.val), _mm_mul_##suffix(b.val, b.val)); \ return _Tpvec(res); \ } \ inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ { \ return _Tpvec(_mm_add_##suffix(_mm_mul_##suffix(a.val, b.val), c.val)); \ } OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float32x4, float, __m128, ps, _mm_set1_epi32((int)0x7fffffff)) OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float64x2, double, __m128d, pd, _mm_srli_epi64(_mm_set1_epi32(-1), 1)) #define OPENCV_HAL_IMPL_SSE_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ inline _Tpuvec operator << (const _Tpuvec& a, int imm) \ { \ return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ } \ inline _Tpsvec operator << (const _Tpsvec& a, int imm) \ { \ return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ } \ inline _Tpuvec operator >> (const _Tpuvec& a, int imm) \ { \ return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ } \ inline _Tpsvec operator >> (const _Tpsvec& a, int imm) \ { \ return _Tpsvec(srai(a.val, imm)); \ } \ template \ inline _Tpuvec v_shl(const _Tpuvec& a) \ { \ return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ } \ template \ inline _Tpsvec v_shl(const _Tpsvec& a) \ { \ return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ } \ template \ inline _Tpuvec v_shr(const _Tpuvec& a) \ { \ return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ } \ template \ inline _Tpsvec v_shr(const _Tpsvec& a) \ { \ return _Tpsvec(srai(a.val, imm)); \ } OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint16x8, v_int16x8, epi16, _mm_srai_epi16) OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint32x4, v_int32x4, epi32, _mm_srai_epi32) OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint64x2, v_int64x2, epi64, v_srai_epi64) #define OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(_Tpvec, _Tp) \ inline _Tpvec v_load(const _Tp* ptr) \ { return _Tpvec(_mm_loadu_si128((const __m128i*)ptr)); } \ inline _Tpvec v_load_aligned(const _Tp* ptr) \ { return _Tpvec(_mm_load_si128((const __m128i*)ptr)); } \ inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ { \ return _Tpvec(_mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ _mm_loadl_epi64((const __m128i*)ptr1))); \ } \ inline void v_store(_Tp* ptr, const _Tpvec& a) \ { _mm_storeu_si128((__m128i*)ptr, a.val); } \ inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ { _mm_store_si128((__m128i*)ptr, a.val); } \ inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ { _mm_storel_epi64((__m128i*)ptr, a.val); } \ inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ { _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a.val, a.val)); } OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint8x16, uchar) OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int8x16, schar) OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint16x8, ushort) OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int16x8, short) OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint32x4, unsigned) OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int32x4, int) OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint64x2, uint64) OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int64x2, int64) #define OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(_Tpvec, _Tp, suffix) \ inline _Tpvec v_load(const _Tp* ptr) \ { return _Tpvec(_mm_loadu_##suffix(ptr)); } \ inline _Tpvec v_load_aligned(const _Tp* ptr) \ { return _Tpvec(_mm_load_##suffix(ptr)); } \ inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ { \ return _Tpvec(_mm_castsi128_##suffix( \ _mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ _mm_loadl_epi64((const __m128i*)ptr1)))); \ } \ inline void v_store(_Tp* ptr, const _Tpvec& a) \ { _mm_storeu_##suffix(ptr, a.val); } \ inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ { _mm_store_##suffix(ptr, a.val); } \ inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ { _mm_storel_epi64((__m128i*)ptr, _mm_cast##suffix##_si128(a.val)); } \ inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ { \ __m128i a1 = _mm_cast##suffix##_si128(a.val); \ _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a1, a1)); \ } OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float32x4, float, ps) OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float64x2, double, pd) #define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(_Tpvec, scalartype, func, scalar_func) \ inline scalartype v_reduce_##func(const _Tpvec& a) \ { \ scalartype CV_DECL_ALIGNED(16) buf[4]; \ v_store_aligned(buf, a); \ scalartype s0 = scalar_func(buf[0], buf[1]); \ scalartype s1 = scalar_func(buf[2], buf[3]); \ return scalar_func(s0, s1); \ } OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, sum, OPENCV_HAL_ADD) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, sum, OPENCV_HAL_ADD) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, max, std::max) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, min, std::min) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, sum, OPENCV_HAL_ADD) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, max, std::max) OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, min, std::min) #define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(_Tpvec, suffix, pack_op, and_op, signmask, allmask) \ inline int v_signmask(const _Tpvec& a) \ { \ return and_op(_mm_movemask_##suffix(pack_op(a.val)), signmask); \ } \ inline bool v_check_all(const _Tpvec& a) \ { return and_op(_mm_movemask_##suffix(a.val), allmask) == allmask; } \ inline bool v_check_any(const _Tpvec& a) \ { return and_op(_mm_movemask_##suffix(a.val), allmask) != 0; } #define OPENCV_HAL_PACKS(a) _mm_packs_epi16(a, a) inline __m128i v_packq_epi32(__m128i a) { __m128i b = _mm_packs_epi32(a, a); return _mm_packs_epi16(b, b); } OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_1ST, 65535, 65535) OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_1ST, 65535, 65535) OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint16x8, epi8, OPENCV_HAL_PACKS, OPENCV_HAL_AND, 255, (int)0xaaaa) OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int16x8, epi8, OPENCV_HAL_PACKS, OPENCV_HAL_AND, 255, (int)0xaaaa) OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint32x4, epi8, v_packq_epi32, OPENCV_HAL_AND, 15, (int)0x8888) OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int32x4, epi8, v_packq_epi32, OPENCV_HAL_AND, 15, (int)0x8888) OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float32x4, ps, OPENCV_HAL_NOP, OPENCV_HAL_1ST, 15, 15) OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float64x2, pd, OPENCV_HAL_NOP, OPENCV_HAL_1ST, 3, 3) #define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, suffix) \ inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ { \ return _Tpvec(_mm_xor_##suffix(b.val, _mm_and_##suffix(_mm_xor_##suffix(b.val, a.val), mask.val))); \ } OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, si128) OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, si128) OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, si128) OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, si128) OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, si128) OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, si128) // OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, si128) // OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, si128) OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, ps) OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, pd) #define OPENCV_HAL_IMPL_SSE_EXPAND(_Tpuvec, _Tpwuvec, _Tpu, _Tpsvec, _Tpwsvec, _Tps, suffix, wsuffix, shift) \ inline void v_expand(const _Tpuvec& a, _Tpwuvec& b0, _Tpwuvec& b1) \ { \ __m128i z = _mm_setzero_si128(); \ b0.val = _mm_unpacklo_##suffix(a.val, z); \ b1.val = _mm_unpackhi_##suffix(a.val, z); \ } \ inline _Tpwuvec v_load_expand(const _Tpu* ptr) \ { \ __m128i z = _mm_setzero_si128(); \ return _Tpwuvec(_mm_unpacklo_##suffix(_mm_loadl_epi64((const __m128i*)ptr), z)); \ } \ inline void v_expand(const _Tpsvec& a, _Tpwsvec& b0, _Tpwsvec& b1) \ { \ b0.val = _mm_srai_##wsuffix(_mm_unpacklo_##suffix(a.val, a.val), shift); \ b1.val = _mm_srai_##wsuffix(_mm_unpackhi_##suffix(a.val, a.val), shift); \ } \ inline _Tpwsvec v_load_expand(const _Tps* ptr) \ { \ __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ return _Tpwsvec(_mm_srai_##wsuffix(_mm_unpacklo_##suffix(a, a), shift)); \ } OPENCV_HAL_IMPL_SSE_EXPAND(v_uint8x16, v_uint16x8, uchar, v_int8x16, v_int16x8, schar, epi8, epi16, 8) OPENCV_HAL_IMPL_SSE_EXPAND(v_uint16x8, v_uint32x4, ushort, v_int16x8, v_int32x4, short, epi16, epi32, 16) inline void v_expand(const v_uint32x4& a, v_uint64x2& b0, v_uint64x2& b1) { __m128i z = _mm_setzero_si128(); b0.val = _mm_unpacklo_epi32(a.val, z); b1.val = _mm_unpackhi_epi32(a.val, z); } inline v_uint64x2 v_load_expand(const unsigned* ptr) { __m128i z = _mm_setzero_si128(); return v_uint64x2(_mm_unpacklo_epi32(_mm_loadl_epi64((const __m128i*)ptr), z)); } inline void v_expand(const v_int32x4& a, v_int64x2& b0, v_int64x2& b1) { __m128i s = _mm_srai_epi32(a.val, 31); b0.val = _mm_unpacklo_epi32(a.val, s); b1.val = _mm_unpackhi_epi32(a.val, s); } inline v_int64x2 v_load_expand(const int* ptr) { __m128i a = _mm_loadl_epi64((const __m128i*)ptr); __m128i s = _mm_srai_epi32(a, 31); return v_int64x2(_mm_unpacklo_epi32(a, s)); } inline v_uint32x4 v_load_expand_q(const uchar* ptr) { __m128i z = _mm_setzero_si128(); __m128i a = _mm_cvtsi32_si128(*(const int*)ptr); return v_uint32x4(_mm_unpacklo_epi16(_mm_unpacklo_epi8(a, z), z)); } inline v_int32x4 v_load_expand_q(const schar* ptr) { __m128i a = _mm_cvtsi32_si128(*(const int*)ptr); a = _mm_unpacklo_epi8(a, a); a = _mm_unpacklo_epi8(a, a); return v_int32x4(_mm_srai_epi32(a, 24)); } #define OPENCV_HAL_IMPL_SSE_UNPACKS(_Tpvec, suffix, cast_from, cast_to) \ inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ { \ b0.val = _mm_unpacklo_##suffix(a0.val, a1.val); \ b1.val = _mm_unpackhi_##suffix(a0.val, a1.val); \ } \ inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ { \ __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ return _Tpvec(cast_to(_mm_unpacklo_epi64(a1, b1))); \ } \ inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ { \ __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ return _Tpvec(cast_to(_mm_unpackhi_epi64(a1, b1))); \ } \ inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ { \ __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ c.val = cast_to(_mm_unpacklo_epi64(a1, b1)); \ d.val = cast_to(_mm_unpackhi_epi64(a1, b1)); \ } OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_UNPACKS(v_int8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_UNPACKS(v_int16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_UNPACKS(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_UNPACKS(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) OPENCV_HAL_IMPL_SSE_UNPACKS(v_float64x2, pd, _mm_castpd_si128, _mm_castsi128_pd) template inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) { const int w = sizeof(typename _Tpvec::lane_type); const int n = _Tpvec::nlanes; __m128i ra, rb; ra = _mm_srli_si128(a.val, s*w); rb = _mm_slli_si128(b.val, (n-s)*w); return _Tpvec(_mm_or_si128(ra, rb)); } inline v_int32x4 v_round(const v_float32x4& a) { return v_int32x4(_mm_cvtps_epi32(a.val)); } inline v_int32x4 v_floor(const v_float32x4& a) { __m128i a1 = _mm_cvtps_epi32(a.val); __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(_mm_cvtepi32_ps(a1), a.val)); return v_int32x4(_mm_add_epi32(a1, mask)); } inline v_int32x4 v_ceil(const v_float32x4& a) { __m128i a1 = _mm_cvtps_epi32(a.val); __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(a.val, _mm_cvtepi32_ps(a1))); return v_int32x4(_mm_sub_epi32(a1, mask)); } inline v_int32x4 v_trunc(const v_float32x4& a) { return v_int32x4(_mm_cvttps_epi32(a.val)); } inline v_int32x4 v_round(const v_float64x2& a) { return v_int32x4(_mm_cvtpd_epi32(a.val)); } inline v_int32x4 v_floor(const v_float64x2& a) { __m128i a1 = _mm_cvtpd_epi32(a.val); __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(_mm_cvtepi32_pd(a1), a.val)); mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 return v_int32x4(_mm_add_epi32(a1, mask)); } inline v_int32x4 v_ceil(const v_float64x2& a) { __m128i a1 = _mm_cvtpd_epi32(a.val); __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(a.val, _mm_cvtepi32_pd(a1))); mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 return v_int32x4(_mm_sub_epi32(a1, mask)); } inline v_int32x4 v_trunc(const v_float64x2& a) { return v_int32x4(_mm_cvttpd_epi32(a.val)); } #define OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ const _Tpvec& a2, const _Tpvec& a3, \ _Tpvec& b0, _Tpvec& b1, \ _Tpvec& b2, _Tpvec& b3) \ { \ __m128i t0 = cast_from(_mm_unpacklo_##suffix(a0.val, a1.val)); \ __m128i t1 = cast_from(_mm_unpacklo_##suffix(a2.val, a3.val)); \ __m128i t2 = cast_from(_mm_unpackhi_##suffix(a0.val, a1.val)); \ __m128i t3 = cast_from(_mm_unpackhi_##suffix(a2.val, a3.val)); \ \ b0.val = cast_to(_mm_unpacklo_epi64(t0, t1)); \ b1.val = cast_to(_mm_unpackhi_epi64(t0, t1)); \ b2.val = cast_to(_mm_unpacklo_epi64(t2, t3)); \ b3.val = cast_to(_mm_unpackhi_epi64(t2, t3)); \ } OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) // adopted from sse_utils.hpp inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) { __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 32)); __m128i t10 = _mm_unpacklo_epi8(t00, _mm_unpackhi_epi64(t01, t01)); __m128i t11 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t00, t00), t02); __m128i t12 = _mm_unpacklo_epi8(t01, _mm_unpackhi_epi64(t02, t02)); __m128i t20 = _mm_unpacklo_epi8(t10, _mm_unpackhi_epi64(t11, t11)); __m128i t21 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t10, t10), t12); __m128i t22 = _mm_unpacklo_epi8(t11, _mm_unpackhi_epi64(t12, t12)); __m128i t30 = _mm_unpacklo_epi8(t20, _mm_unpackhi_epi64(t21, t21)); __m128i t31 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t20, t20), t22); __m128i t32 = _mm_unpacklo_epi8(t21, _mm_unpackhi_epi64(t22, t22)); a.val = _mm_unpacklo_epi8(t30, _mm_unpackhi_epi64(t31, t31)); b.val = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t30, t30), t32); c.val = _mm_unpacklo_epi8(t31, _mm_unpackhi_epi64(t32, t32)); } inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) { __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); // a8 b8 c8 d8 ... __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 48)); // a12 b12 c12 d12 ... __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 a8 b0 b8 ... __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a2 a10 b2 b10 ... __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a4 a12 b4 b12 ... __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a6 a14 b6 b14 ... u0 = _mm_unpacklo_epi8(v0, v2); // a0 a4 a8 a12 ... u1 = _mm_unpacklo_epi8(v1, v3); // a2 a6 a10 a14 ... u2 = _mm_unpackhi_epi8(v0, v2); // a1 a5 a9 a13 ... u3 = _mm_unpackhi_epi8(v1, v3); // a3 a7 a11 a15 ... v0 = _mm_unpacklo_epi8(u0, u1); // a0 a2 a4 a6 ... v1 = _mm_unpacklo_epi8(u2, u3); // a1 a3 a5 a7 ... v2 = _mm_unpackhi_epi8(u0, u1); // c0 c2 c4 c6 ... v3 = _mm_unpackhi_epi8(u2, u3); // c1 c3 c5 c7 ... a.val = _mm_unpacklo_epi8(v0, v1); b.val = _mm_unpackhi_epi8(v0, v1); c.val = _mm_unpacklo_epi8(v2, v3); d.val = _mm_unpackhi_epi8(v2, v3); } inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) { __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 8)); __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 16)); __m128i t10 = _mm_unpacklo_epi16(t00, _mm_unpackhi_epi64(t01, t01)); __m128i t11 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t00, t00), t02); __m128i t12 = _mm_unpacklo_epi16(t01, _mm_unpackhi_epi64(t02, t02)); __m128i t20 = _mm_unpacklo_epi16(t10, _mm_unpackhi_epi64(t11, t11)); __m128i t21 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t10, t10), t12); __m128i t22 = _mm_unpacklo_epi16(t11, _mm_unpackhi_epi64(t12, t12)); a.val = _mm_unpacklo_epi16(t20, _mm_unpackhi_epi64(t21, t21)); b.val = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t20, t20), t22); c.val = _mm_unpacklo_epi16(t21, _mm_unpackhi_epi64(t22, t22)); } inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) { __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 8)); // a2 b2 c2 d2 ... __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 24)); // a6 b6 c6 d6 ... __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 a4 b0 b4 ... __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a1 a5 b1 b5 ... __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a2 a6 b2 b6 ... __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a3 a7 b3 b7 ... u0 = _mm_unpacklo_epi16(v0, v2); // a0 a2 a4 a6 ... u1 = _mm_unpacklo_epi16(v1, v3); // a1 a3 a5 a7 ... u2 = _mm_unpackhi_epi16(v0, v2); // c0 c2 c4 c6 ... u3 = _mm_unpackhi_epi16(v1, v3); // c1 c3 c5 c7 ... a.val = _mm_unpacklo_epi16(u0, u1); b.val = _mm_unpackhi_epi16(u0, u1); c.val = _mm_unpacklo_epi16(u2, u3); d.val = _mm_unpackhi_epi16(u2, u3); } inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) { __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 4)); __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 8)); __m128i t10 = _mm_unpacklo_epi32(t00, _mm_unpackhi_epi64(t01, t01)); __m128i t11 = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t00, t00), t02); __m128i t12 = _mm_unpacklo_epi32(t01, _mm_unpackhi_epi64(t02, t02)); a.val = _mm_unpacklo_epi32(t10, _mm_unpackhi_epi64(t11, t11)); b.val = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t10, t10), t12); c.val = _mm_unpacklo_epi32(t11, _mm_unpackhi_epi64(t12, t12)); } inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) { v_uint32x4 u0(_mm_loadu_si128((const __m128i*)ptr)); // a0 b0 c0 d0 v_uint32x4 u1(_mm_loadu_si128((const __m128i*)(ptr + 4))); // a1 b1 c1 d1 v_uint32x4 u2(_mm_loadu_si128((const __m128i*)(ptr + 8))); // a2 b2 c2 d2 v_uint32x4 u3(_mm_loadu_si128((const __m128i*)(ptr + 12))); // a3 b3 c3 d3 v_transpose4x4(u0, u1, u2, u3, a, b, c, d); } inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, const v_uint8x16& c ) { __m128i z = _mm_setzero_si128(); __m128i ab0 = _mm_unpacklo_epi8(a.val, b.val); __m128i ab1 = _mm_unpackhi_epi8(a.val, b.val); __m128i c0 = _mm_unpacklo_epi8(c.val, z); __m128i c1 = _mm_unpackhi_epi8(c.val, z); __m128i p00 = _mm_unpacklo_epi16(ab0, c0); __m128i p01 = _mm_unpackhi_epi16(ab0, c0); __m128i p02 = _mm_unpacklo_epi16(ab1, c1); __m128i p03 = _mm_unpackhi_epi16(ab1, c1); __m128i p10 = _mm_unpacklo_epi32(p00, p01); __m128i p11 = _mm_unpackhi_epi32(p00, p01); __m128i p12 = _mm_unpacklo_epi32(p02, p03); __m128i p13 = _mm_unpackhi_epi32(p02, p03); __m128i p20 = _mm_unpacklo_epi64(p10, p11); __m128i p21 = _mm_unpackhi_epi64(p10, p11); __m128i p22 = _mm_unpacklo_epi64(p12, p13); __m128i p23 = _mm_unpackhi_epi64(p12, p13); p20 = _mm_slli_si128(p20, 1); p22 = _mm_slli_si128(p22, 1); __m128i p30 = _mm_slli_epi64(_mm_unpacklo_epi32(p20, p21), 8); __m128i p31 = _mm_srli_epi64(_mm_unpackhi_epi32(p20, p21), 8); __m128i p32 = _mm_slli_epi64(_mm_unpacklo_epi32(p22, p23), 8); __m128i p33 = _mm_srli_epi64(_mm_unpackhi_epi32(p22, p23), 8); __m128i p40 = _mm_unpacklo_epi64(p30, p31); __m128i p41 = _mm_unpackhi_epi64(p30, p31); __m128i p42 = _mm_unpacklo_epi64(p32, p33); __m128i p43 = _mm_unpackhi_epi64(p32, p33); __m128i v0 = _mm_or_si128(_mm_srli_si128(p40, 2), _mm_slli_si128(p41, 10)); __m128i v1 = _mm_or_si128(_mm_srli_si128(p41, 6), _mm_slli_si128(p42, 6)); __m128i v2 = _mm_or_si128(_mm_srli_si128(p42, 10), _mm_slli_si128(p43, 2)); _mm_storeu_si128((__m128i*)(ptr), v0); _mm_storeu_si128((__m128i*)(ptr + 16), v1); _mm_storeu_si128((__m128i*)(ptr + 32), v2); } inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, const v_uint8x16& c, const v_uint8x16& d) { // a0 a1 a2 a3 .... // b0 b1 b2 b3 .... // c0 c1 c2 c3 .... // d0 d1 d2 d3 .... __m128i u0 = _mm_unpacklo_epi8(a.val, c.val); // a0 c0 a1 c1 ... __m128i u1 = _mm_unpackhi_epi8(a.val, c.val); // a8 c8 a9 c9 ... __m128i u2 = _mm_unpacklo_epi8(b.val, d.val); // b0 d0 b1 d1 ... __m128i u3 = _mm_unpackhi_epi8(b.val, d.val); // b8 d8 b9 d9 ... __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 b0 c0 d0 ... __m128i v1 = _mm_unpacklo_epi8(u1, u3); // a8 b8 c8 d8 ... __m128i v2 = _mm_unpackhi_epi8(u0, u2); // a4 b4 c4 d4 ... __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a12 b12 c12 d12 ... _mm_storeu_si128((__m128i*)ptr, v0); _mm_storeu_si128((__m128i*)(ptr + 16), v2); _mm_storeu_si128((__m128i*)(ptr + 32), v1); _mm_storeu_si128((__m128i*)(ptr + 48), v3); } inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, const v_uint16x8& c ) { __m128i z = _mm_setzero_si128(); __m128i ab0 = _mm_unpacklo_epi16(a.val, b.val); __m128i ab1 = _mm_unpackhi_epi16(a.val, b.val); __m128i c0 = _mm_unpacklo_epi16(c.val, z); __m128i c1 = _mm_unpackhi_epi16(c.val, z); __m128i p10 = _mm_unpacklo_epi32(ab0, c0); __m128i p11 = _mm_unpackhi_epi32(ab0, c0); __m128i p12 = _mm_unpacklo_epi32(ab1, c1); __m128i p13 = _mm_unpackhi_epi32(ab1, c1); __m128i p20 = _mm_unpacklo_epi64(p10, p11); __m128i p21 = _mm_unpackhi_epi64(p10, p11); __m128i p22 = _mm_unpacklo_epi64(p12, p13); __m128i p23 = _mm_unpackhi_epi64(p12, p13); p20 = _mm_slli_si128(p20, 2); p22 = _mm_slli_si128(p22, 2); __m128i p30 = _mm_unpacklo_epi64(p20, p21); __m128i p31 = _mm_unpackhi_epi64(p20, p21); __m128i p32 = _mm_unpacklo_epi64(p22, p23); __m128i p33 = _mm_unpackhi_epi64(p22, p23); __m128i v0 = _mm_or_si128(_mm_srli_si128(p30, 2), _mm_slli_si128(p31, 10)); __m128i v1 = _mm_or_si128(_mm_srli_si128(p31, 6), _mm_slli_si128(p32, 6)); __m128i v2 = _mm_or_si128(_mm_srli_si128(p32, 10), _mm_slli_si128(p33, 2)); _mm_storeu_si128((__m128i*)(ptr), v0); _mm_storeu_si128((__m128i*)(ptr + 8), v1); _mm_storeu_si128((__m128i*)(ptr + 16), v2); } inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, const v_uint16x8& c, const v_uint16x8& d) { // a0 a1 a2 a3 .... // b0 b1 b2 b3 .... // c0 c1 c2 c3 .... // d0 d1 d2 d3 .... __m128i u0 = _mm_unpacklo_epi16(a.val, c.val); // a0 c0 a1 c1 ... __m128i u1 = _mm_unpackhi_epi16(a.val, c.val); // a4 c4 a5 c5 ... __m128i u2 = _mm_unpacklo_epi16(b.val, d.val); // b0 d0 b1 d1 ... __m128i u3 = _mm_unpackhi_epi16(b.val, d.val); // b4 d4 b5 d5 ... __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 b0 c0 d0 ... __m128i v1 = _mm_unpacklo_epi16(u1, u3); // a4 b4 c4 d4 ... __m128i v2 = _mm_unpackhi_epi16(u0, u2); // a2 b2 c2 d2 ... __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a6 b6 c6 d6 ... _mm_storeu_si128((__m128i*)ptr, v0); _mm_storeu_si128((__m128i*)(ptr + 8), v2); _mm_storeu_si128((__m128i*)(ptr + 16), v1); _mm_storeu_si128((__m128i*)(ptr + 24), v3); } inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, const v_uint32x4& c ) { v_uint32x4 z = v_setzero_u32(), u0, u1, u2, u3; v_transpose4x4(a, b, c, z, u0, u1, u2, u3); __m128i v0 = _mm_or_si128(u0.val, _mm_slli_si128(u1.val, 12)); __m128i v1 = _mm_or_si128(_mm_srli_si128(u1.val, 4), _mm_slli_si128(u2.val, 8)); __m128i v2 = _mm_or_si128(_mm_srli_si128(u2.val, 8), _mm_slli_si128(u3.val, 4)); _mm_storeu_si128((__m128i*)ptr, v0); _mm_storeu_si128((__m128i*)(ptr + 4), v1); _mm_storeu_si128((__m128i*)(ptr + 8), v2); } inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, const v_uint32x4& c, const v_uint32x4& d) { v_uint32x4 t0, t1, t2, t3; v_transpose4x4(a, b, c, d, t0, t1, t2, t3); v_store(ptr, t0); v_store(ptr + 4, t1); v_store(ptr + 8, t2); v_store(ptr + 12, t3); } #define OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(_Tpvec, _Tp, suffix, _Tpuvec, _Tpu, usuffix) \ inline void v_load_deinterleave( const _Tp* ptr, _Tpvec& a0, \ _Tpvec& b0, _Tpvec& c0 ) \ { \ _Tpuvec a1, b1, c1; \ v_load_deinterleave((const _Tpu*)ptr, a1, b1, c1); \ a0 = v_reinterpret_as_##suffix(a1); \ b0 = v_reinterpret_as_##suffix(b1); \ c0 = v_reinterpret_as_##suffix(c1); \ } \ inline void v_load_deinterleave( const _Tp* ptr, _Tpvec& a0, \ _Tpvec& b0, _Tpvec& c0, _Tpvec& d0 ) \ { \ _Tpuvec a1, b1, c1, d1; \ v_load_deinterleave((const _Tpu*)ptr, a1, b1, c1, d1); \ a0 = v_reinterpret_as_##suffix(a1); \ b0 = v_reinterpret_as_##suffix(b1); \ c0 = v_reinterpret_as_##suffix(c1); \ d0 = v_reinterpret_as_##suffix(d1); \ } \ inline void v_store_interleave( _Tp* ptr, const _Tpvec& a0, \ const _Tpvec& b0, const _Tpvec& c0 ) \ { \ _Tpuvec a1 = v_reinterpret_as_##usuffix(a0); \ _Tpuvec b1 = v_reinterpret_as_##usuffix(b0); \ _Tpuvec c1 = v_reinterpret_as_##usuffix(c0); \ v_store_interleave((_Tpu*)ptr, a1, b1, c1); \ } \ inline void v_store_interleave( _Tp* ptr, const _Tpvec& a0, const _Tpvec& b0, \ const _Tpvec& c0, const _Tpvec& d0 ) \ { \ _Tpuvec a1 = v_reinterpret_as_##usuffix(a0); \ _Tpuvec b1 = v_reinterpret_as_##usuffix(b0); \ _Tpuvec c1 = v_reinterpret_as_##usuffix(c0); \ _Tpuvec d1 = v_reinterpret_as_##usuffix(d0); \ v_store_interleave((_Tpu*)ptr, a1, b1, c1, d1); \ } OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_float32x4, float, f32, v_uint32x4, unsigned, u32) inline v_float32x4 v_cvt_f32(const v_int32x4& a) { return v_float32x4(_mm_cvtepi32_ps(a.val)); } inline v_float32x4 v_cvt_f32(const v_float64x2& a) { return v_float32x4(_mm_cvtpd_ps(a.val)); } inline v_float64x2 v_cvt_f64(const v_int32x4& a) { return v_float64x2(_mm_cvtepi32_pd(a.val)); } inline v_float64x2 v_cvt_f64(const v_float32x4& a) { return v_float64x2(_mm_cvtps_pd(a.val)); } //! @endcond } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/ippasync.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2015, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_IPPASYNC_HPP__ #define __OPENCV_CORE_IPPASYNC_HPP__ #ifdef HAVE_IPP_A #include "opencv2/core.hpp" #include #include namespace cv { namespace hpp { /** @addtogroup core_ipp This section describes conversion between OpenCV and [Intel® IPP Asynchronous C/C++](http://software.intel.com/en-us/intel-ipp-preview) library. [Getting Started Guide](http://registrationcenter.intel.com/irc_nas/3727/ipp_async_get_started.htm) help you to install the library, configure header and library build paths. */ //! @{ //! convert OpenCV data type to hppDataType inline int toHppType(const int cvType) { int depth = CV_MAT_DEPTH(cvType); int hppType = depth == CV_8U ? HPP_DATA_TYPE_8U : depth == CV_16U ? HPP_DATA_TYPE_16U : depth == CV_16S ? HPP_DATA_TYPE_16S : depth == CV_32S ? HPP_DATA_TYPE_32S : depth == CV_32F ? HPP_DATA_TYPE_32F : depth == CV_64F ? HPP_DATA_TYPE_64F : -1; CV_Assert( hppType >= 0 ); return hppType; } //! convert hppDataType to OpenCV data type inline int toCvType(const int hppType) { int cvType = hppType == HPP_DATA_TYPE_8U ? CV_8U : hppType == HPP_DATA_TYPE_16U ? CV_16U : hppType == HPP_DATA_TYPE_16S ? CV_16S : hppType == HPP_DATA_TYPE_32S ? CV_32S : hppType == HPP_DATA_TYPE_32F ? CV_32F : hppType == HPP_DATA_TYPE_64F ? CV_64F : -1; CV_Assert( cvType >= 0 ); return cvType; } /** @brief Convert hppiMatrix to Mat. This function allocates and initializes new matrix (if needed) that has the same size and type as input matrix. Supports CV_8U, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F. @param src input hppiMatrix. @param dst output matrix. @param accel accelerator instance (see hpp::getHpp for the list of acceleration framework types). @param cn number of channels. */ inline void copyHppToMat(hppiMatrix* src, Mat& dst, hppAccel accel, int cn) { hppDataType type; hpp32u width, height; hppStatus sts; if (src == NULL) return dst.release(); sts = hppiInquireMatrix(src, &type, &width, &height); CV_Assert( sts == HPP_STATUS_NO_ERROR); int matType = CV_MAKETYPE(toCvType(type), cn); CV_Assert(width%cn == 0); width /= cn; dst.create((int)height, (int)width, (int)matType); size_t newSize = (size_t)(height*(hpp32u)(dst.step)); sts = hppiGetMatrixData(accel,src,(hpp32u)(dst.step),dst.data,&newSize); CV_Assert( sts == HPP_STATUS_NO_ERROR); } /** @brief Create Mat from hppiMatrix. This function allocates and initializes the Mat that has the same size and type as input matrix. Supports CV_8U, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F. @param src input hppiMatrix. @param accel accelerator instance (see hpp::getHpp for the list of acceleration framework types). @param cn number of channels. @sa howToUseIPPAconversion, hpp::copyHppToMat, hpp::getHpp. */ inline Mat getMat(hppiMatrix* src, hppAccel accel, int cn) { Mat dst; copyHppToMat(src, dst, accel, cn); return dst; } /** @brief Create hppiMatrix from Mat. This function allocates and initializes the hppiMatrix that has the same size and type as input matrix, returns the hppiMatrix*. If you want to use zero-copy for GPU you should to have 4KB aligned matrix data. See details [hppiCreateSharedMatrix](http://software.intel.com/ru-ru/node/501697). Supports CV_8U, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F. @note The hppiMatrix pointer to the image buffer in system memory refers to the src.data. Control the lifetime of the matrix and don't change its data, if there is no special need. @param src input matrix. @param accel accelerator instance. Supports type: - **HPP_ACCEL_TYPE_CPU** - accelerated by optimized CPU instructions. - **HPP_ACCEL_TYPE_GPU** - accelerated by GPU programmable units or fixed-function accelerators. - **HPP_ACCEL_TYPE_ANY** - any acceleration or no acceleration available. @sa howToUseIPPAconversion, hpp::getMat */ inline hppiMatrix* getHpp(const Mat& src, hppAccel accel) { int htype = toHppType(src.type()); int cn = src.channels(); CV_Assert(src.data); hppAccelType accelType = hppQueryAccelType(accel); if (accelType!=HPP_ACCEL_TYPE_CPU) { hpp32u pitch, size; hppQueryMatrixAllocParams(accel, src.cols*cn, src.rows, htype, &pitch, &size); if (pitch!=0 && size!=0) if ((int)(src.data)%4096==0 && pitch==(hpp32u)(src.step)) { return hppiCreateSharedMatrix(htype, src.cols*cn, src.rows, src.data, pitch, size); } } return hppiCreateMatrix(htype, src.cols*cn, src.rows, src.data, (hpp32s)(src.step));; } //! @} }} #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/mat.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_MAT_HPP__ #define __OPENCV_CORE_MAT_HPP__ #ifndef __cplusplus # error mat.hpp header must be compiled as C++ #endif #include "opencv2/core/matx.hpp" #include "opencv2/core/types.hpp" #include "opencv2/core/bufferpool.hpp" namespace cv { //! @addtogroup core_basic //! @{ enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25, ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 }; class CV_EXPORTS _OutputArray; //////////////////////// Input/Output Array Arguments ///////////////////////////////// /** @brief This is the proxy class for passing read-only input arrays into OpenCV functions. It is defined as: @code typedef const _InputArray& InputArray; @endcode where _InputArray is a class that can be constructed from `Mat`, `Mat_`, `Matx`, `std::vector`, `std::vector >` or `std::vector`. It can also be constructed from a matrix expression. Since this is mostly implementation-level class, and its interface may change in future versions, we do not describe it in details. There are a few key things, though, that should be kept in mind: - When you see in the reference manual or in OpenCV source code a function that takes InputArray, it means that you can actually pass `Mat`, `Matx`, `vector` etc. (see above the complete list). - Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or simply cv::Mat() as you probably did before). - The class is designed solely for passing parameters. That is, normally you *should not* declare class members, local and global variables of this type. - If you want to design your own function or a class method that can operate of arrays of multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside a function you should use _InputArray::getMat() method to construct a matrix header for the array (without copying data). _InputArray::kind() can be used to distinguish Mat from `vector<>` etc., but normally it is not needed. Here is how you can use a function that takes InputArray : @code std::vector vec; // points or a circle for( int i = 0; i < 30; i++ ) vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)), (float)(100 - 30*sin(i*CV_PI*2/5)))); cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20)); @endcode That is, we form an STL vector containing points, and apply in-place affine transformation to the vector using the 2x3 matrix created inline as `Matx` instance. Here is how such a function can be implemented (for simplicity, we implement a very specific case of it, according to the assertion statement inside) : @code void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m) { // get Mat headers for input arrays. This is O(1) operation, // unless _src and/or _m are matrix expressions. Mat src = _src.getMat(), m = _m.getMat(); CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) ); // [re]create the output array so that it has the proper size and type. // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize. _dst.create(src.size(), src.type()); Mat dst = _dst.getMat(); for( int i = 0; i < src.rows; i++ ) for( int j = 0; j < src.cols; j++ ) { Point2f pt = src.at(i, j); dst.at(i, j) = Point2f(m.at(0, 0)*pt.x + m.at(0, 1)*pt.y + m.at(0, 2), m.at(1, 0)*pt.x + m.at(1, 1)*pt.y + m.at(1, 2)); } } @endcode There is another related type, InputArrayOfArrays, which is currently defined as a synonym for InputArray: @code typedef InputArray InputArrayOfArrays; @endcode It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation level their use is similar, but _InputArray::getMat(idx) should be used to get header for the idx-th component of the outer vector and _InputArray::size().area() should be used to find the number of components (vectors/matrices) of the outer vector. */ class CV_EXPORTS _InputArray { public: enum { KIND_SHIFT = 16, FIXED_TYPE = 0x8000 << KIND_SHIFT, FIXED_SIZE = 0x4000 << KIND_SHIFT, KIND_MASK = 31 << KIND_SHIFT, NONE = 0 << KIND_SHIFT, MAT = 1 << KIND_SHIFT, MATX = 2 << KIND_SHIFT, STD_VECTOR = 3 << KIND_SHIFT, STD_VECTOR_VECTOR = 4 << KIND_SHIFT, STD_VECTOR_MAT = 5 << KIND_SHIFT, EXPR = 6 << KIND_SHIFT, OPENGL_BUFFER = 7 << KIND_SHIFT, CUDA_HOST_MEM = 8 << KIND_SHIFT, CUDA_GPU_MAT = 9 << KIND_SHIFT, UMAT =10 << KIND_SHIFT, STD_VECTOR_UMAT =11 << KIND_SHIFT, STD_BOOL_VECTOR =12 << KIND_SHIFT, STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT }; _InputArray(); _InputArray(int _flags, void* _obj); _InputArray(const Mat& m); _InputArray(const MatExpr& expr); _InputArray(const std::vector& vec); template _InputArray(const Mat_<_Tp>& m); template _InputArray(const std::vector<_Tp>& vec); _InputArray(const std::vector& vec); template _InputArray(const std::vector >& vec); template _InputArray(const std::vector >& vec); template _InputArray(const _Tp* vec, int n); template _InputArray(const Matx<_Tp, m, n>& matx); _InputArray(const double& val); _InputArray(const cuda::GpuMat& d_mat); _InputArray(const std::vector& d_mat_array); _InputArray(const ogl::Buffer& buf); _InputArray(const cuda::HostMem& cuda_mem); template _InputArray(const cudev::GpuMat_<_Tp>& m); _InputArray(const UMat& um); _InputArray(const std::vector& umv); Mat getMat(int idx=-1) const; Mat getMat_(int idx=-1) const; UMat getUMat(int idx=-1) const; void getMatVector(std::vector& mv) const; void getUMatVector(std::vector& umv) const; void getGpuMatVector(std::vector& gpumv) const; cuda::GpuMat getGpuMat() const; ogl::Buffer getOGlBuffer() const; int getFlags() const; void* getObj() const; Size getSz() const; int kind() const; int dims(int i=-1) const; int cols(int i=-1) const; int rows(int i=-1) const; Size size(int i=-1) const; int sizend(int* sz, int i=-1) const; bool sameSize(const _InputArray& arr) const; size_t total(int i=-1) const; int type(int i=-1) const; int depth(int i=-1) const; int channels(int i=-1) const; bool isContinuous(int i=-1) const; bool isSubmatrix(int i=-1) const; bool empty() const; void copyTo(const _OutputArray& arr) const; void copyTo(const _OutputArray& arr, const _InputArray & mask) const; size_t offset(int i=-1) const; size_t step(int i=-1) const; bool isMat() const; bool isUMat() const; bool isMatVector() const; bool isUMatVector() const; bool isMatx() const; bool isVector() const; bool isGpuMatVector() const; ~_InputArray(); protected: int flags; void* obj; Size sz; void init(int _flags, const void* _obj); void init(int _flags, const void* _obj, Size _sz); }; /** @brief This type is very similar to InputArray except that it is used for input/output and output function parameters. Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`, `vector` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly create OutputArray instances* applies here too. If you want to make your function polymorphic (i.e. accept different arrays as output parameters), it is also not very difficult. Take the sample above as the reference. Note that _OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee that the output array is properly allocated. Optional output parameters. If you do not need certain output array to be computed and returned to you, pass cv::noArray(), just like you would in the case of optional input array. At the implementation level, use _OutputArray::needed() to check if certain output array needs to be computed or not. There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper generators: @code typedef OutputArray OutputArrayOfArrays; typedef OutputArray InputOutputArray; typedef OutputArray InputOutputArrayOfArrays; @endcode */ class CV_EXPORTS _OutputArray : public _InputArray { public: enum { DEPTH_MASK_8U = 1 << CV_8U, DEPTH_MASK_8S = 1 << CV_8S, DEPTH_MASK_16U = 1 << CV_16U, DEPTH_MASK_16S = 1 << CV_16S, DEPTH_MASK_32S = 1 << CV_32S, DEPTH_MASK_32F = 1 << CV_32F, DEPTH_MASK_64F = 1 << CV_64F, DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F }; _OutputArray(); _OutputArray(int _flags, void* _obj); _OutputArray(Mat& m); _OutputArray(std::vector& vec); _OutputArray(cuda::GpuMat& d_mat); _OutputArray(std::vector& d_mat); _OutputArray(ogl::Buffer& buf); _OutputArray(cuda::HostMem& cuda_mem); template _OutputArray(cudev::GpuMat_<_Tp>& m); template _OutputArray(std::vector<_Tp>& vec); _OutputArray(std::vector& vec); template _OutputArray(std::vector >& vec); template _OutputArray(std::vector >& vec); template _OutputArray(Mat_<_Tp>& m); template _OutputArray(_Tp* vec, int n); template _OutputArray(Matx<_Tp, m, n>& matx); _OutputArray(UMat& m); _OutputArray(std::vector& vec); _OutputArray(const Mat& m); _OutputArray(const std::vector& vec); _OutputArray(const cuda::GpuMat& d_mat); _OutputArray(const std::vector& d_mat); _OutputArray(const ogl::Buffer& buf); _OutputArray(const cuda::HostMem& cuda_mem); template _OutputArray(const cudev::GpuMat_<_Tp>& m); template _OutputArray(const std::vector<_Tp>& vec); template _OutputArray(const std::vector >& vec); template _OutputArray(const std::vector >& vec); template _OutputArray(const Mat_<_Tp>& m); template _OutputArray(const _Tp* vec, int n); template _OutputArray(const Matx<_Tp, m, n>& matx); _OutputArray(const UMat& m); _OutputArray(const std::vector& vec); bool fixedSize() const; bool fixedType() const; bool needed() const; Mat& getMatRef(int i=-1) const; UMat& getUMatRef(int i=-1) const; cuda::GpuMat& getGpuMatRef() const; std::vector& getGpuMatVecRef() const; ogl::Buffer& getOGlBufferRef() const; cuda::HostMem& getHostMemRef() const; void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; void createSameSize(const _InputArray& arr, int mtype) const; void release() const; void clear() const; void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const; void assign(const UMat& u) const; void assign(const Mat& m) const; }; class CV_EXPORTS _InputOutputArray : public _OutputArray { public: _InputOutputArray(); _InputOutputArray(int _flags, void* _obj); _InputOutputArray(Mat& m); _InputOutputArray(std::vector& vec); _InputOutputArray(cuda::GpuMat& d_mat); _InputOutputArray(ogl::Buffer& buf); _InputOutputArray(cuda::HostMem& cuda_mem); template _InputOutputArray(cudev::GpuMat_<_Tp>& m); template _InputOutputArray(std::vector<_Tp>& vec); _InputOutputArray(std::vector& vec); template _InputOutputArray(std::vector >& vec); template _InputOutputArray(std::vector >& vec); template _InputOutputArray(Mat_<_Tp>& m); template _InputOutputArray(_Tp* vec, int n); template _InputOutputArray(Matx<_Tp, m, n>& matx); _InputOutputArray(UMat& m); _InputOutputArray(std::vector& vec); _InputOutputArray(const Mat& m); _InputOutputArray(const std::vector& vec); _InputOutputArray(const cuda::GpuMat& d_mat); _InputOutputArray(const std::vector& d_mat); _InputOutputArray(const ogl::Buffer& buf); _InputOutputArray(const cuda::HostMem& cuda_mem); template _InputOutputArray(const cudev::GpuMat_<_Tp>& m); template _InputOutputArray(const std::vector<_Tp>& vec); template _InputOutputArray(const std::vector >& vec); template _InputOutputArray(const std::vector >& vec); template _InputOutputArray(const Mat_<_Tp>& m); template _InputOutputArray(const _Tp* vec, int n); template _InputOutputArray(const Matx<_Tp, m, n>& matx); _InputOutputArray(const UMat& m); _InputOutputArray(const std::vector& vec); }; typedef const _InputArray& InputArray; typedef InputArray InputArrayOfArrays; typedef const _OutputArray& OutputArray; typedef OutputArray OutputArrayOfArrays; typedef const _InputOutputArray& InputOutputArray; typedef InputOutputArray InputOutputArrayOfArrays; CV_EXPORTS InputOutputArray noArray(); /////////////////////////////////// MatAllocator ////////////////////////////////////// //! Usage flags for allocator enum UMatUsageFlags { USAGE_DEFAULT = 0, // buffer allocation policy is platform and usage specific USAGE_ALLOCATE_HOST_MEMORY = 1 << 0, USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1, USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint }; struct CV_EXPORTS UMatData; /** @brief Custom array allocator */ class CV_EXPORTS MatAllocator { public: MatAllocator() {} virtual ~MatAllocator() {} // let's comment it off for now to detect and fix all the uses of allocator //virtual void allocate(int dims, const int* sizes, int type, int*& refcount, // uchar*& datastart, uchar*& data, size_t* step) = 0; //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; virtual UMatData* allocate(int dims, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0; virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0; virtual void deallocate(UMatData* data) const = 0; virtual void map(UMatData* data, int accessflags) const; virtual void unmap(UMatData* data) const; virtual void download(UMatData* data, void* dst, int dims, const size_t sz[], const size_t srcofs[], const size_t srcstep[], const size_t dststep[]) const; virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[], const size_t dstofs[], const size_t dststep[], const size_t srcstep[]) const; virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[], const size_t srcofs[], const size_t srcstep[], const size_t dstofs[], const size_t dststep[], bool sync) const; // default implementation returns DummyBufferPoolController virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const; }; //////////////////////////////// MatCommaInitializer ////////////////////////////////// /** @brief Comma-separated Matrix Initializer The class instances are usually not created explicitly. Instead, they are created on "matrix << firstValue" operator. The sample below initializes 2x2 rotation matrix: \code double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); Mat R = (Mat_(2,2) << a, -b, b, a); \endcode */ template class MatCommaInitializer_ { public: //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat MatCommaInitializer_(Mat_<_Tp>* _m); //! the operator that takes the next value and put it to the matrix template MatCommaInitializer_<_Tp>& operator , (T2 v); //! another form of conversion operator operator Mat_<_Tp>() const; protected: MatIterator_<_Tp> it; }; /////////////////////////////////////// Mat /////////////////////////////////////////// // note that umatdata might be allocated together // with the matrix data, not as a separate object. // therefore, it does not have constructor or destructor; // it should be explicitly initialized using init(). struct CV_EXPORTS UMatData { enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2, DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24, USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64}; UMatData(const MatAllocator* allocator); ~UMatData(); // provide atomic access to the structure void lock(); void unlock(); bool hostCopyObsolete() const; bool deviceCopyObsolete() const; bool deviceMemMapped() const; bool copyOnMap() const; bool tempUMat() const; bool tempCopiedUMat() const; void markHostCopyObsolete(bool flag); void markDeviceCopyObsolete(bool flag); void markDeviceMemMapped(bool flag); const MatAllocator* prevAllocator; const MatAllocator* currAllocator; int urefcount; int refcount; uchar* data; uchar* origdata; size_t size; int flags; void* handle; void* userdata; int allocatorFlags_; int mapcount; UMatData* originalUMatData; }; struct CV_EXPORTS UMatDataAutoLock { explicit UMatDataAutoLock(UMatData* u); ~UMatDataAutoLock(); UMatData* u; }; struct CV_EXPORTS MatSize { explicit MatSize(int* _p); Size operator()() const; const int& operator[](int i) const; int& operator[](int i); operator const int*() const; bool operator == (const MatSize& sz) const; bool operator != (const MatSize& sz) const; int* p; }; struct CV_EXPORTS MatStep { MatStep(); explicit MatStep(size_t s); const size_t& operator[](int i) const; size_t& operator[](int i); operator size_t() const; MatStep& operator = (size_t s); size_t* p; size_t buf[2]; protected: MatStep& operator = (const MatStep&); }; /** @example cout_mat.cpp An example demonstrating the serial out capabilities of cv::Mat */ /** @brief n-dimensional dense array class The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array `M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() . So, the data layout in Mat is fully compatible with CvMat, IplImage, and CvMatND types from OpenCV 1.x. It is also compatible with the majority of dense array types from the standard toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this compatibility, it is possible to make a Mat header for user-allocated data and process it in-place using OpenCV functions. There are many different ways to create a Mat object. The most popular options are listed below: - Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) constructor. A new array of the specified size and type is allocated. type has the same meaning as in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 means a 2-channel (complex) floating-point array, and so on. @code // make a 7x7 complex matrix filled with 1+3j. Mat M(7,7,CV_32FC2,Scalar(1,3)); // and now turn M to a 100x60 15-channel 8-bit matrix. // The old content will be deallocated M.create(100,60,CV_8UC(15)); @endcode As noted in the introduction to this chapter, create() allocates only a new array when the shape or type of the current array are different from the specified ones. - Create a multi-dimensional array: @code // create a 100x100x100 8-bit array int sz[] = {100, 100, 100}; Mat bigCube(3, sz, CV_8U, Scalar::all(0)); @endcode It passes the number of dimensions =1 to the Mat constructor but the created array will be 2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0 when the array is empty). - Use a copy constructor or assignment operator where there can be an array or expression on the right side (see below). As noted in the introduction, the array assignment is an O(1) operation because it only copies the header and increases the reference counter. The Mat::clone() method can be used to get a full (deep) copy of the array when you need it. - Construct a header for a part of another array. It can be a single row, single column, several rows, several columns, rectangular region in the array (called a *minor* in algebra) or a diagonal. Such operations are also O(1) because the new header references the same data. You can actually modify a part of the array using this feature, for example: @code // add the 5-th row, multiplied by 3 to the 3rd row M.row(3) = M.row(3) + M.row(5)*3; // now copy the 7-th column to the 1-st column // M.col(1) = M.col(7); // this will not work Mat M1 = M.col(1); M.col(7).copyTo(M1); // create a new 320x240 image Mat img(Size(320,240),CV_8UC3); // select a ROI Mat roi(img, Rect(10,10,100,100)); // fill the ROI with (0,255,0) (which is green in RGB space); // the original 320x240 image will be modified roi = Scalar(0,255,0); @endcode Due to the additional datastart and dataend members, it is possible to compute a relative sub-array position in the main *container* array using locateROI(): @code Mat A = Mat::eye(10, 10, CV_32S); // extracts A columns, 1 (inclusive) to 3 (exclusive). Mat B = A(Range::all(), Range(1, 3)); // extracts B rows, 5 (inclusive) to 9 (exclusive). // that is, C \~ A(Range(5, 9), Range(1, 3)) Mat C = B(Range(5, 9), Range::all()); Size size; Point ofs; C.locateROI(size, ofs); // size will be (width=10,height=10) and the ofs will be (x=1, y=5) @endcode As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted sub-matrices. - Make a header for user-allocated data. It can be useful to do the following: -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or a processing module for gstreamer, and so on). For example: @code void process_video_frame(const unsigned char* pixels, int width, int height, int step) { Mat img(height, width, CV_8UC3, pixels, step); GaussianBlur(img, img, Size(7,7), 1.5, 1.5); } @endcode -# Quickly initialize small matrices and/or get a super-fast element access. @code double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; Mat M = Mat(3, 3, CV_64F, m).inv(); @endcode . Partial yet very common cases of this *user-allocated data* case are conversions from CvMat and IplImage to Mat. For this purpose, there is function cv::cvarrToMat taking pointers to CvMat or IplImage and the optional flag indicating whether to copy the data or not. @snippet samples/cpp/image.cpp iplimage - Use MATLAB-style array initializers, zeros(), ones(), eye(), for example: @code // create a double-precision identity martix and add it to M. M += Mat::eye(M.rows, M.cols, CV_64F); @endcode - Use a comma-separated initializer: @code // create a 3x3 double-precision identity matrix Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); @endcode With this approach, you first call a constructor of the Mat class with the proper parameters, and then you just put `<< operator` followed by comma-separated values that can be constants, variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation errors. Once the array is created, it is automatically managed via a reference-counting mechanism. If the array header is built on top of user-allocated data, you should handle the data by yourself. The array data is deallocated when no one points to it. If you want to release the data pointed by a array header before the array destructor is called, use Mat::release(). The next important thing to learn about the array class is element access. This manual already described how to compute an address of each array element. Normally, you are not required to use the formula directly in the code. If you know the array element type (which can be retrieved using the method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as: @code M.at(i,j) += 1.f; @endcode assuming that `M` is a double-precision floating-point array. There are several variants of the method at for a different number of dimensions. If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to the row first, and then just use the plain C operator [] : @code // compute sum of positive matrix elements // (assuming that M isa double-precision matrix) double sum=0; for(int i = 0; i < M.rows; i++) { const double* Mi = M.ptr(i); for(int j = 0; j < M.cols; j++) sum += std::max(Mi[j], 0.); } @endcode Some operations, like the one above, do not actually depend on the array shape. They just process elements of an array one by one (or elements from multiple arrays that have the same coordinates, for example, array addition). Such operations are called *element-wise*. It makes sense to check whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If yes, process them as a long single row: @code // compute the sum of positive matrix elements, optimized variant double sum=0; int cols = M.cols, rows = M.rows; if(M.isContinuous()) { cols *= rows; rows = 1; } for(int i = 0; i < rows; i++) { const double* Mi = M.ptr(i); for(int j = 0; j < cols; j++) sum += std::max(Mi[j], 0.); } @endcode In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is smaller, which is especially noticeable in case of small matrices. Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: @code // compute sum of positive matrix elements, iterator-based variant double sum=0; MatConstIterator_ it = M.begin(), it_end = M.end(); for(; it != it_end; ++it) sum += std::max(*it, 0.); @endcode The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including std::sort(). */ class CV_EXPORTS Mat { public: /** These are various constructors that form a matrix. As noted in the AutomaticAllocation, often the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. The constructed matrix can further be assigned to another matrix or matrix expression or can be allocated with Mat::create . In the former case, the old content is de-referenced. */ Mat(); /** @overload @param rows Number of rows in a 2D array. @param cols Number of columns in a 2D array. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. */ Mat(int rows, int cols, int type); /** @overload @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. */ Mat(Size size, int type); /** @overload @param rows Number of rows in a 2D array. @param cols Number of columns in a 2D array. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param s An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) . */ Mat(int rows, int cols, int type, const Scalar& s); /** @overload @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param s An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) . */ Mat(Size size, int type, const Scalar& s); /** @overload @param ndims Array dimensionality. @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. */ Mat(int ndims, const int* sizes, int type); /** @overload @param ndims Array dimensionality. @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param s An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) . */ Mat(int ndims, const int* sizes, int type, const Scalar& s); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . */ Mat(const Mat& m); /** @overload @param rows Number of rows in a 2D array. @param cols Number of columns in a 2D array. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize. */ Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); /** @overload @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize. */ Mat(Size size, int type, void* data, size_t step=AUTO_STEP); /** @overload @param ndims Array dimensionality. @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous. */ Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range end is exclusive. Use Range::all() to take all the rows. @param colRange Range of the m columns to take. Use Range::all() to take all the columns. */ Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . @param roi Region of interest. */ Mat(const Mat& m, const Rect& roi); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . @param ranges Array of selected ranges of m along each dimensionality. */ Mat(const Mat& m, const Range* ranges); /** @overload @param vec STL vector whose elements form the matrix. The matrix has a single column and the number of rows equal to the number of vector elements. Type of the matrix matches the type of vector elements. The constructor can handle arbitrary types, for which there is a properly declared DataType . This means that the vector elements must be primitive numbers or uni-type numerical tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is explicit. Since STL vectors are not automatically converted to Mat instances, you should write Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements will be added to the vector because it can potentially yield vector data reallocation, and, thus, the matrix data pointer will be invalid. @param copyData Flag to specify whether the underlying data of the STL vector should be copied to (true) or shared with (false) the newly constructed matrix. When the data is copied, the allocated buffer is managed using Mat reference counting mechanism. While the data is shared, the reference counter is NULL, and you should not deallocate the data until the matrix is not destructed. */ template explicit Mat(const std::vector<_Tp>& vec, bool copyData=false); /** @overload */ template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); /** @overload */ template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); /** @overload */ template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); /** @overload */ template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); /** @overload */ template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); //! download data from GpuMat explicit Mat(const cuda::GpuMat& m); //! destructor - calls release() ~Mat(); /** @brief assignment operators These are available assignment operators. Since they all are very different, make sure to read the operator parameters description. @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is de-referenced via Mat::release . */ Mat& operator = (const Mat& m); /** @overload @param expr Assigned matrix expression object. As opposite to the first form of the assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result. It is automatically handled by the real function that the matrix expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of automatic C reallocation. */ Mat& operator = (const MatExpr& expr); //! retrieve UMat from Mat UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const; /** @brief Creates a matrix header for the specified matrix row. The method makes a new header for the specified matrix row and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. Here is the example of one of the classical basic matrix processing operations, axpy, used by LU and many other algorithms: @code inline void matrix_axpy(Mat& A, int i, int j, double alpha) { A.row(i) += A.row(j)*alpha; } @endcode @note In the current implementation, the following code does not work as expected: @code Mat A; ... A.row(i) = A.row(j); // will not work @endcode This happens because A.row(i) forms a temporary header that is further assigned to another header. Remember that each of these operations is O(1), that is, no data is copied. Thus, the above assignment is not true if you may have expected the j-th row to be copied to the i-th row. To achieve that, you should either turn this simple assignment into an expression or use the Mat::copyTo method: @code Mat A; ... // works, but looks a bit obscure. A.row(i) = A.row(j) + 0; // this is a bit longer, but the recommended method. A.row(j).copyTo(A.row(i)); @endcode @param y A 0-based row index. */ Mat row(int y) const; /** @brief Creates a matrix header for the specified matrix column. The method makes a new header for the specified matrix column and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. See also the Mat::row description. @param x A 0-based column index. */ Mat col(int x) const; /** @brief Creates a matrix header for the specified row span. The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and Mat::col , this is an O(1) operation. @param startrow An inclusive 0-based start index of the row span. @param endrow An exclusive 0-based ending index of the row span. */ Mat rowRange(int startrow, int endrow) const; /** @overload @param r Range structure containing both the start and the end indices. */ Mat rowRange(const Range& r) const; /** @brief Creates a matrix header for the specified column span. The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and Mat::col , this is an O(1) operation. @param startcol An inclusive 0-based start index of the column span. @param endcol An exclusive 0-based ending index of the column span. */ Mat colRange(int startcol, int endcol) const; /** @overload @param r Range structure containing both the start and the end indices. */ Mat colRange(const Range& r) const; /** @brief Extracts a diagonal from a matrix The method makes a new header for the specified matrix diagonal. The new matrix is represented as a single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. @param d index of the diagonal, with the following values: - `d=0` is the main diagonal. - `d>0` is a diagonal from the lower half. For example, d=1 means the diagonal is set immediately below the main one. - `d<0` is a diagonal from the upper half. For example, d=-1 means the diagonal is set immediately above the main one. */ Mat diag(int d=0) const; /** @brief creates a diagonal matrix The method makes a new header for the specified matrix diagonal. The new matrix is represented as a single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. @param d Single-column matrix that forms a diagonal matrix */ static Mat diag(const Mat& d); /** @brief Creates a full copy of the array and the underlying data. The method creates a full copy of the array. The original step[] is not taken into account. So, the array copy is a continuous array occupying total()*elemSize() bytes. */ Mat clone() const; /** @brief Copies the matrix to another one. The method copies the matrix data to another matrix. Before copying the data, the method invokes : @code m.create(this->size(), this->type()); @endcode so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices. When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. @param m Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. */ void copyTo( OutputArray m ) const; /** @overload @param m Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. @param mask Operation mask. Its non-zero elements indicate which matrix elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. */ void copyTo( OutputArray m, InputArray mask ) const; /** @brief Converts an array to another data type with optional scaling. The method converts source pixel values to the target data type. saturate_cast\<\> is applied at the end to avoid possible overflows: \f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] @param m output matrix; if it does not have a proper size or type before the operation, it is reallocated. @param rtype desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input. @param alpha optional scale factor. @param beta optional delta added to the scaled values. */ void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; /** @brief Provides a functional form of convertTo. This is an internally used method called by the @ref MatrixExpressions engine. @param m Destination array. @param type Desired destination array depth (or -1 if it should be the same as the source type). */ void assignTo( Mat& m, int type=-1 ) const; /** @brief Sets all or some of the array elements to the specified value. @param s Assigned scalar converted to the actual array type. */ Mat& operator = (const Scalar& s); /** @brief Sets all or some of the array elements to the specified value. This is an advanced variant of the Mat::operator=(const Scalar& s) operator. @param value Assigned scalar converted to the actual array type. @param mask Operation mask of the same size as \*this. */ Mat& setTo(InputArray value, InputArray mask=noArray()); /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data. The method makes a new matrix header for \*this elements. The new matrix may have a different size and/or different number of channels. Any combination is possible if: - No extra elements are included into the new matrix and no elements are excluded. Consequently, the product rows\*cols\*channels() must stay the same after the transformation. - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of rows, or the operation changes the indices of elements row in some other way, the matrix must be continuous. See Mat::isContinuous . For example, if there is a set of 3D points stored as an STL vector, and you want to represent the points as a 3xN matrix, do the following: @code std::vector vec; ... Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel. // Also, an O(1) operation t(); // finally, transpose the Nx3 matrix. // This involves copying all the elements @endcode @param cn New number of channels. If the parameter is 0, the number of channels remains the same. @param rows New number of rows. If the parameter is 0, the number of rows remains the same. */ Mat reshape(int cn, int rows=0) const; /** @overload */ Mat reshape(int cn, int newndims, const int* newsz) const; /** @brief Transposes a matrix. The method performs matrix transposition by means of matrix expressions. It does not perform the actual transposition but returns a temporary matrix transposition object that can be further used as a part of more complex matrix expressions or can be assigned to a matrix: @code Mat A1 = A + Mat::eye(A.size(), A.type())*lambda; Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I) @endcode */ MatExpr t() const; /** @brief Inverses a matrix. The method performs a matrix inversion by means of matrix expressions. This means that a temporary matrix inversion object is returned by the method and can be used further as a part of more complex matrix expressions or can be assigned to a matrix. @param method Matrix inversion method. One of cv::DecompTypes */ MatExpr inv(int method=DECOMP_LU) const; /** @brief Performs an element-wise multiplication or division of the two matrices. The method returns a temporary object encoding per-element array multiplication, with optional scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator. Example: @code Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5) @endcode @param m Another array of the same type and the same size as \*this, or a matrix expression. @param scale Optional scale factor. */ MatExpr mul(InputArray m, double scale=1) const; /** @brief Computes a cross-product of two 3-element vectors. The method computes a cross-product of two 3-element vectors. The vectors must be 3-element floating-point vectors of the same shape and size. The result is another 3-element vector of the same shape and type as operands. @param m Another cross-product operand. */ Mat cross(InputArray m) const; /** @brief Computes a dot-product of two vectors. The method computes a dot-product of two matrices. If the matrices are not single-column or single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D vectors. The vectors must have the same size and type. If the matrices have more than one channel, the dot products from all the channels are summed together. @param m another dot-product operand. */ double dot(InputArray m) const; /** @brief Returns a zero array of the specified size and type. The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant array as a function parameter, part of a matrix expression, or as a matrix initializer. : @code Mat A; A = Mat::zeros(3, 3, CV_32F); @endcode In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. Otherwise, the existing matrix A is filled with zeros. @param rows Number of rows. @param cols Number of columns. @param type Created matrix type. */ static MatExpr zeros(int rows, int cols, int type); /** @overload @param size Alternative to the matrix size specification Size(cols, rows) . @param type Created matrix type. */ static MatExpr zeros(Size size, int type); /** @overload @param ndims Array dimensionality. @param sz Array of integers specifying the array shape. @param type Created matrix type. */ static MatExpr zeros(int ndims, const int* sz, int type); /** @brief Returns an array of all 1's of the specified size and type. The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using this method you can initialize an array with an arbitrary value, using the following Matlab idiom: @code Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3. @endcode The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it just remembers the scale factor (3 in this case) and use it when actually invoking the matrix initializer. @param rows Number of rows. @param cols Number of columns. @param type Created matrix type. */ static MatExpr ones(int rows, int cols, int type); /** @overload @param size Alternative to the matrix size specification Size(cols, rows) . @param type Created matrix type. */ static MatExpr ones(Size size, int type); /** @overload @param ndims Array dimensionality. @param sz Array of integers specifying the array shape. @param type Created matrix type. */ static MatExpr ones(int ndims, const int* sz, int type); /** @brief Returns an identity matrix of the specified size and type. The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently: @code // make a 4x4 diagonal matrix with 0.1's on the diagonal. Mat A = Mat::eye(4, 4, CV_32F)*0.1; @endcode @param rows Number of rows. @param cols Number of columns. @param type Created matrix type. */ static MatExpr eye(int rows, int cols, int type); /** @overload @param size Alternative matrix size specification as Size(cols, rows) . @param type Created matrix type. */ static MatExpr eye(Size size, int type); /** @brief Allocates new array data if needed. This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays call this method for each output array. The method uses the following algorithm: -# If the current array shape and the type match the new ones, return immediately. Otherwise, de-reference the previous data by calling Mat::release. -# Initialize the new header. -# Allocate the new data of total()\*elemSize() bytes. -# Allocate the new, associated with the data, reference counter and set it to 1. Such a scheme makes the memory management robust and efficient at the same time and helps avoid extra typing for you. This means that usually there is no need to explicitly allocate output arrays. That is, instead of writing: @code Mat color; ... Mat gray(color.rows, color.cols, color.depth()); cvtColor(color, gray, COLOR_BGR2GRAY); @endcode you can simply write: @code Mat color; ... Mat gray; cvtColor(color, gray, COLOR_BGR2GRAY); @endcode because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array internally. @param rows New number of rows. @param cols New number of columns. @param type New matrix type. */ void create(int rows, int cols, int type); /** @overload @param size Alternative new matrix size specification: Size(cols, rows) @param type New matrix type. */ void create(Size size, int type); /** @overload @param ndims New array dimensionality. @param sizes Array of integers specifying a new array shape. @param type New matrix type. */ void create(int ndims, const int* sizes, int type); /** @brief Increments the reference counter. The method increments the reference counter associated with the matrix data. If the matrix header points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It is called implicitly by the matrix assignment operator. The reference counter increment is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads. */ void addref(); /** @brief Decrements the reference counter and deallocates the matrix if needed. The method decrements the reference counter associated with the matrix data. When the reference counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no effect in this case. This method can be called manually to force the matrix data deallocation. But since this method is automatically called in the destructor, or by any other method that changes the data pointer, it is usually not needed. The reference counter decrement and check for 0 is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads. */ void release(); //! deallocates the matrix data void deallocate(); //! internal use function; properly re-allocates _size, _step arrays void copySize(const Mat& m); /** @brief Reserves space for the certain number of rows. The method reserves space for sz rows. If the matrix already has enough space to store sz rows, nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method emulates the corresponding method of the STL vector class. @param sz Number of rows. */ void reserve(size_t sz); /** @brief Changes the number of matrix rows. The methods change the number of matrix rows. If the matrix is reallocated, the first min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL vector class. @param sz New number of rows. */ void resize(size_t sz); /** @overload @param sz New number of rows. @param s Value assigned to the newly added elements. */ void resize(size_t sz, const Scalar& s); //! internal function void push_back_(const void* elem); /** @brief Adds elements to the bottom of the matrix. The methods add one or more elements to the bottom of the matrix. They emulate the corresponding method of the STL vector class. When elem is Mat , its type and the number of columns must be the same as in the container matrix. @param elem Added element(s). */ template void push_back(const _Tp& elem); /** @overload @param elem Added element(s). */ template void push_back(const Mat_<_Tp>& elem); /** @overload @param m Added line(s). */ void push_back(const Mat& m); /** @brief Removes elements from the bottom of the matrix. The method removes one or more rows from the bottom of the matrix. @param nelems Number of removed rows. If it is greater than the total number of rows, an exception is thrown. */ void pop_back(size_t nelems=1); /** @brief Locates the matrix header within a parent matrix. After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, Mat::colRange, and others, the resultant submatrix points just to the part of the original big matrix. However, each submatrix contains information (represented by datastart and dataend fields) that helps reconstruct the original matrix size and the position of the extracted submatrix within the original matrix. The method locateROI does exactly that. @param wholeSize Output parameter that contains the size of the whole matrix containing *this* as a part. @param ofs Output parameter that contains an offset of *this* inside the whole matrix. */ void locateROI( Size& wholeSize, Point& ofs ) const; /** @brief Adjusts a submatrix size and position within the parent matrix. The method is complimentary to Mat::locateROI . The typical use of these functions is to determine the submatrix position within the parent matrix and then shift the position somehow. Typically, it can be required for filtering operations when pixels outside of the ROI should be taken into account. When all the method parameters are positive, the ROI needs to grow in all directions by the specified amount, for example: @code A.adjustROI(2, 2, 2, 2); @endcode In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the filtering with the 5x5 kernel. adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not be increased in the upward direction. The function is used internally by the OpenCV filtering functions, like filter2D , morphological operations, and so on. @param dtop Shift of the top submatrix boundary upwards. @param dbottom Shift of the bottom submatrix boundary downwards. @param dleft Shift of the left submatrix boundary to the left. @param dright Shift of the right submatrix boundary to the right. @sa copyMakeBorder */ Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); /** @brief Extracts a rectangular submatrix. The operators make a new header for the specified sub-array of \*this . They are the most generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above, the operators are O(1) operations, that is, no matrix data is copied. @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range::all(). @param colRange Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range::all(). */ Mat operator()( Range rowRange, Range colRange ) const; /** @overload @param roi Extracted submatrix specified as a rectangle. */ Mat operator()( const Rect& roi ) const; /** @overload @param ranges Array of selected ranges along each array dimension. */ Mat operator()( const Range* ranges ) const; // //! converts header to CvMat; no data is copied // operator CvMat() const; // //! converts header to CvMatND; no data is copied // operator CvMatND() const; // //! converts header to IplImage; no data is copied // operator IplImage() const; template operator std::vector<_Tp>() const; template operator Vec<_Tp, n>() const; template operator Matx<_Tp, m, n>() const; /** @brief Reports whether the matrix is continuous or not. The method returns true if the matrix elements are stored continuously without gaps at the end of each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. Matrices created with Mat::create are always continuous. But if you extract a part of the matrix using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, such matrices may no longer have this property. The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when you construct a matrix header. Thus, the continuity check is a very fast operation, though theoretically it could be done as follows: @code // alternative implementation of Mat::isContinuous() bool myCheckMatContinuity(const Mat& m) { //return (m.flags & Mat::CONTINUOUS_FLAG) != 0; return m.rows == 1 || m.step == m.cols*m.elemSize(); } @endcode The method is used in quite a few of OpenCV functions. The point is that element-wise operations (such as arithmetic and logical operations, math functions, alpha blending, color space transformations, and others) do not depend on the image geometry. Thus, if all the input and output arrays are continuous, the functions can process them as very long single-row vectors. The example below illustrates how an alpha-blending function can be implemented: @code template void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) { const float alpha_scale = (float)std::numeric_limits::max(), inv_scale = 1.f/alpha_scale; CV_Assert( src1.type() == src2.type() && src1.type() == CV_MAKETYPE(DataType::depth, 4) && src1.size() == src2.size()); Size size = src1.size(); dst.create(size, src1.type()); // here is the idiom: check the arrays for continuity and, // if this is the case, // treat the arrays as 1D vectors if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() ) { size.width *= size.height; size.height = 1; } size.width *= 4; for( int i = 0; i < size.height; i++ ) { // when the arrays are continuous, // the outer loop is executed only once const T* ptr1 = src1.ptr(i); const T* ptr2 = src2.ptr(i); T* dptr = dst.ptr(i); for( int j = 0; j < size.width; j += 4 ) { float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale; dptr[j] = saturate_cast(ptr1[j]*alpha + ptr2[j]*beta); dptr[j+1] = saturate_cast(ptr1[j+1]*alpha + ptr2[j+1]*beta); dptr[j+2] = saturate_cast(ptr1[j+2]*alpha + ptr2[j+2]*beta); dptr[j+3] = saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale); } } } @endcode This approach, while being very simple, can boost the performance of a simple element-operation by 10-20 percents, especially if the image is rather small and the operation is quite simple. Another OpenCV idiom in this function, a call of Mat::create for the destination array, that allocates the destination array unless it already has the proper size and type. And while the newly allocated arrays are always continuous, you still need to check the destination array because Mat::create does not always allocate a new matrix. */ bool isContinuous() const; //! returns true if the matrix is a submatrix of another matrix bool isSubmatrix() const; /** @brief Returns the matrix element size in bytes. The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , the method returns 3\*sizeof(short) or 6. */ size_t elemSize() const; /** @brief Returns the size of each matrix element channel in bytes. The method returns the matrix element channel size in bytes, that is, it ignores the number of channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2. */ size_t elemSize1() const; /** @brief Returns the type of a matrix element. The method returns a matrix element type. This is an identifier compatible with the CvMat type system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. */ int type() const; /** @brief Returns the depth of a matrix element. The method returns the identifier of the matrix element depth (the type of each individual channel). For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of matrix types contains the following values: - CV_8U - 8-bit unsigned integers ( 0..255 ) - CV_8S - 8-bit signed integers ( -128..127 ) - CV_16U - 16-bit unsigned integers ( 0..65535 ) - CV_16S - 16-bit signed integers ( -32768..32767 ) - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) */ int depth() const; /** @brief Returns the number of matrix channels. The method returns the number of matrix channels. */ int channels() const; /** @brief Returns a normalized step. The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an arbitrary matrix element. */ size_t step1(int i=0) const; /** @brief Returns true if the array has no elements. The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and resize() methods `M.total() == 0` does not imply that `M.data == NULL`. */ bool empty() const; /** @brief Returns the total number of array elements. The method returns the number of array elements (a number of pixels if the array represents an image). */ size_t total() const; //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; /** @brief Returns a pointer to the specified matrix row. The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in Mat::isContinuous to know how to use these methods. @param i0 A 0-based row index. */ uchar* ptr(int i0=0); /** @overload */ const uchar* ptr(int i0=0) const; /** @overload */ uchar* ptr(int i0, int i1); /** @overload */ const uchar* ptr(int i0, int i1) const; /** @overload */ uchar* ptr(int i0, int i1, int i2); /** @overload */ const uchar* ptr(int i0, int i1, int i2) const; /** @overload */ uchar* ptr(const int* idx); /** @overload */ const uchar* ptr(const int* idx) const; /** @overload */ template uchar* ptr(const Vec& idx); /** @overload */ template const uchar* ptr(const Vec& idx) const; /** @overload */ template _Tp* ptr(int i0=0); /** @overload */ template const _Tp* ptr(int i0=0) const; /** @overload */ template _Tp* ptr(int i0, int i1); /** @overload */ template const _Tp* ptr(int i0, int i1) const; /** @overload */ template _Tp* ptr(int i0, int i1, int i2); /** @overload */ template const _Tp* ptr(int i0, int i1, int i2) const; /** @overload */ template _Tp* ptr(const int* idx); /** @overload */ template const _Tp* ptr(const int* idx) const; /** @overload */ template _Tp* ptr(const Vec& idx); /** @overload */ template const _Tp* ptr(const Vec& idx) const; /** @brief Returns a reference to the specified array element. The template methods return a reference to the specified array element. For the sake of higher performance, the index range checks are only performed in the Debug configuration. Note that the variants with a single index (i) can be used to access elements of single-row or single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and B is an M x 1 integer matrix, you can simply write `A.at(k+4)` and `B.at(2*i+1)` instead of `A.at(0,k+4)` and `B.at(2*i+1,0)`, respectively. The example below initializes a Hilbert matrix: @code Mat H(100, 100, CV_64F); for(int i = 0; i < H.rows; i++) for(int j = 0; j < H.cols; j++) H.at(i,j)=1./(i+j+1); @endcode @param i0 Index along the dimension 0 */ template _Tp& at(int i0=0); /** @overload @param i0 Index along the dimension 0 */ template const _Tp& at(int i0=0) const; /** @overload @param i0 Index along the dimension 0 @param i1 Index along the dimension 1 */ template _Tp& at(int i0, int i1); /** @overload @param i0 Index along the dimension 0 @param i1 Index along the dimension 1 */ template const _Tp& at(int i0, int i1) const; /** @overload @param i0 Index along the dimension 0 @param i1 Index along the dimension 1 @param i2 Index along the dimension 2 */ template _Tp& at(int i0, int i1, int i2); /** @overload @param i0 Index along the dimension 0 @param i1 Index along the dimension 1 @param i2 Index along the dimension 2 */ template const _Tp& at(int i0, int i1, int i2) const; /** @overload @param idx Array of Mat::dims indices. */ template _Tp& at(const int* idx); /** @overload @param idx Array of Mat::dims indices. */ template const _Tp& at(const int* idx) const; /** @overload */ template _Tp& at(const Vec& idx); /** @overload */ template const _Tp& at(const Vec& idx) const; /** @overload special versions for 2D arrays (especially convenient for referencing image pixels) @param pt Element position specified as Point(j,i) . */ template _Tp& at(Point pt); /** @overload special versions for 2D arrays (especially convenient for referencing image pixels) @param pt Element position specified as Point(j,i) . */ template const _Tp& at(Point pt) const; /** @brief Returns the matrix iterator and sets it to the first matrix element. The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very similar to the use of bi-directional STL iterators. In the example below, the alpha blending function is rewritten using the matrix iterators: @code template void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) { typedef Vec VT; const float alpha_scale = (float)std::numeric_limits::max(), inv_scale = 1.f/alpha_scale; CV_Assert( src1.type() == src2.type() && src1.type() == DataType::type && src1.size() == src2.size()); Size size = src1.size(); dst.create(size, src1.type()); MatConstIterator_ it1 = src1.begin(), it1_end = src1.end(); MatConstIterator_ it2 = src2.begin(); MatIterator_ dst_it = dst.begin(); for( ; it1 != it1_end; ++it1, ++it2, ++dst_it ) { VT pix1 = *it1, pix2 = *it2; float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale; *dst_it = VT(saturate_cast(pix1[0]*alpha + pix2[0]*beta), saturate_cast(pix1[1]*alpha + pix2[1]*beta), saturate_cast(pix1[2]*alpha + pix2[2]*beta), saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale)); } } @endcode */ template MatIterator_<_Tp> begin(); template MatConstIterator_<_Tp> begin() const; /** @brief Returns the matrix iterator and sets it to the after-last matrix element. The methods return the matrix read-only or read-write iterators, set to the point following the last matrix element. */ template MatIterator_<_Tp> end(); template MatConstIterator_<_Tp> end() const; /** @brief Invoke with arguments functor, and runs the functor over all matrix element. The methods runs operation in parallel. Operation is passed by arguments. Operation have to be a function pointer, a function object or a lambda(C++11). All of below operation is equal. Put 0xFF to first channel of all matrix elements: @code Mat image(1920, 1080, CV_8UC3); typedef cv::Point3_ Pixel; // first. raw pointer access. for (int r = 0; r < image.rows; ++r) { Pixel* ptr = image.ptr(0, r); const Pixel* ptr_end = ptr + image.cols; for (; ptr != ptr_end; ++ptr) { ptr->x = 255; } } // Using MatIterator. (Simple but there are a Iterator's overhead) for (Pixel &p : cv::Mat_(image)) { p.x = 255; } // Parallel execution with function object. struct Operator { void operator ()(Pixel &pixel, const int * position) { pixel.x = 255; } }; image.forEach(Operator()); // Parallel execution using C++11 lambda. image.forEach([](Pixel &p, const int * position) -> void { p.x = 255; }); @endcode position parameter is index of current pixel: @code // Creating 3D matrix (255 x 255 x 255) typed uint8_t, // and initialize all elements by the value which equals elements position. // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3). int sizes[] = { 255, 255, 255 }; typedef cv::Point3_ Pixel; Mat_ image = Mat::zeros(3, sizes, CV_8UC3); image.forEachWithPosition([&](Pixel& pixel, const int position[]) -> void{ pixel.x = position[0]; pixel.y = position[1]; pixel.z = position[2]; }); @endcode */ template void forEach(const Functor& operation); /** @overload */ template void forEach(const Functor& operation) const; #ifdef CV_CXX_MOVE_SEMANTICS Mat(Mat&& m); Mat& operator = (Mat&& m); #endif enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; /*! includes several bit-fields: - the magic signature - continuity flag - depth - number of channels */ int flags; //! the matrix dimensionality, >= 2 int dims; //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions int rows, cols; //! pointer to the data uchar* data; //! helper fields used in locateROI and adjustROI const uchar* datastart; const uchar* dataend; const uchar* datalimit; //! custom allocator MatAllocator* allocator; //! and the standard allocator static MatAllocator* getStdAllocator(); static MatAllocator* getDefaultAllocator(); static void setDefaultAllocator(MatAllocator* allocator); //! interaction with UMat UMatData* u; MatSize size; MatStep step; protected: template void forEach_impl(const Functor& operation); }; ///////////////////////////////// Mat_<_Tp> //////////////////////////////////// /** @brief Template matrix class derived from Mat @code template class Mat_ : public Mat { public: // ... some specific methods // and // no new extra fields }; @endcode The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to these two classes can be freely but carefully converted one to another. For example: @code // create a 100x100 8-bit matrix Mat M(100,100,CV_8U); // this will be compiled fine. no any data conversion will be done. Mat_& M1 = (Mat_&)M; // the program is likely to crash at the statement below M1(99,99) = 1.f; @endcode While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element access operations and if you know matrix type at the compilation time. Note that `Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same and run at the same speed, but the latter is certainly shorter: @code Mat_ M(20,20); for(int i = 0; i < M.rows; i++) for(int j = 0; j < M.cols; j++) M(i,j) = 1./(i+j+1); Mat E, V; eigen(M,E,V); cout << E.at(0,0)/E.at(M.rows-1,0); @endcode To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter: @code // allocate a 320x240 color image and fill it with green (in RGB space) Mat_ img(240, 320, Vec3b(0,255,0)); // now draw a diagonal white line for(int i = 0; i < 100; i++) img(i,i)=Vec3b(255,255,255); // and now scramble the 2nd (red) channel of each pixel for(int i = 0; i < img.rows; i++) for(int j = 0; j < img.cols; j++) img(i,j)[2] ^= (uchar)(i ^ j); @endcode */ template class Mat_ : public Mat { public: typedef _Tp value_type; typedef typename DataType<_Tp>::channel_type channel_type; typedef MatIterator_<_Tp> iterator; typedef MatConstIterator_<_Tp> const_iterator; //! default constructor Mat_(); //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) Mat_(int _rows, int _cols); //! constructor that sets each matrix element to specified value Mat_(int _rows, int _cols, const _Tp& value); //! equivalent to Mat(_size, DataType<_Tp>::type) explicit Mat_(Size _size); //! constructor that sets each matrix element to specified value Mat_(Size _size, const _Tp& value); //! n-dim array constructor Mat_(int _ndims, const int* _sizes); //! n-dim array constructor that sets each matrix element to specified value Mat_(int _ndims, const int* _sizes, const _Tp& value); //! copy/conversion contructor. If m is of different type, it's converted Mat_(const Mat& m); //! copy constructor Mat_(const Mat_& m); //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); //! selects a submatrix Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); //! selects a submatrix Mat_(const Mat_& m, const Rect& roi); //! selects a submatrix, n-dim version Mat_(const Mat_& m, const Range* ranges); //! from a matrix expression explicit Mat_(const MatExpr& e); //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false); template explicit Mat_(const Vec::channel_type, n>& vec, bool copyData=true); template explicit Mat_(const Matx::channel_type, m, n>& mtx, bool copyData=true); explicit Mat_(const Point_::channel_type>& pt, bool copyData=true); explicit Mat_(const Point3_::channel_type>& pt, bool copyData=true); explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); Mat_& operator = (const Mat& m); Mat_& operator = (const Mat_& m); //! set all the elements to s. Mat_& operator = (const _Tp& s); //! assign a matrix expression Mat_& operator = (const MatExpr& e); //! iterators; they are smart enough to skip gaps in the end of rows iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; //! template methods for for operation over all matrix elements. // the operations take care of skipping gaps in the end of rows (if any) template void forEach(const Functor& operation); template void forEach(const Functor& operation) const; //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) void create(int _rows, int _cols); //! equivalent to Mat::create(_size, DataType<_Tp>::type) void create(Size _size); //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) void create(int _ndims, const int* _sizes); //! cross-product Mat_ cross(const Mat_& m) const; //! data type conversion template operator Mat_() const; //! overridden forms of Mat::row() etc. Mat_ row(int y) const; Mat_ col(int x) const; Mat_ diag(int d=0) const; Mat_ clone() const; //! overridden forms of Mat::elemSize() etc. size_t elemSize() const; size_t elemSize1() const; int type() const; int depth() const; int channels() const; size_t step1(int i=0) const; //! returns step()/sizeof(_Tp) size_t stepT(int i=0) const; //! overridden forms of Mat::zeros() etc. Data type is omitted, of course static MatExpr zeros(int rows, int cols); static MatExpr zeros(Size size); static MatExpr zeros(int _ndims, const int* _sizes); static MatExpr ones(int rows, int cols); static MatExpr ones(Size size); static MatExpr ones(int _ndims, const int* _sizes); static MatExpr eye(int rows, int cols); static MatExpr eye(Size size); //! some more overriden methods Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); Mat_ operator()( const Range& rowRange, const Range& colRange ) const; Mat_ operator()( const Rect& roi ) const; Mat_ operator()( const Range* ranges ) const; //! more convenient forms of row and element access operators _Tp* operator [](int y); const _Tp* operator [](int y) const; //! returns reference to the specified element _Tp& operator ()(const int* idx); //! returns read-only reference to the specified element const _Tp& operator ()(const int* idx) const; //! returns reference to the specified element template _Tp& operator ()(const Vec& idx); //! returns read-only reference to the specified element template const _Tp& operator ()(const Vec& idx) const; //! returns reference to the specified element (1D case) _Tp& operator ()(int idx0); //! returns read-only reference to the specified element (1D case) const _Tp& operator ()(int idx0) const; //! returns reference to the specified element (2D case) _Tp& operator ()(int idx0, int idx1); //! returns read-only reference to the specified element (2D case) const _Tp& operator ()(int idx0, int idx1) const; //! returns reference to the specified element (3D case) _Tp& operator ()(int idx0, int idx1, int idx2); //! returns read-only reference to the specified element (3D case) const _Tp& operator ()(int idx0, int idx1, int idx2) const; _Tp& operator ()(Point pt); const _Tp& operator ()(Point pt) const; //! conversion to vector. operator std::vector<_Tp>() const; //! conversion to Vec template operator Vec::channel_type, n>() const; //! conversion to Matx template operator Matx::channel_type, m, n>() const; #ifdef CV_CXX_MOVE_SEMANTICS Mat_(Mat_&& m); Mat_& operator = (Mat_&& m); Mat_(Mat&& m); Mat_& operator = (Mat&& m); Mat_(MatExpr&& e); #endif }; typedef Mat_ Mat1b; typedef Mat_ Mat2b; typedef Mat_ Mat3b; typedef Mat_ Mat4b; typedef Mat_ Mat1s; typedef Mat_ Mat2s; typedef Mat_ Mat3s; typedef Mat_ Mat4s; typedef Mat_ Mat1w; typedef Mat_ Mat2w; typedef Mat_ Mat3w; typedef Mat_ Mat4w; typedef Mat_ Mat1i; typedef Mat_ Mat2i; typedef Mat_ Mat3i; typedef Mat_ Mat4i; typedef Mat_ Mat1f; typedef Mat_ Mat2f; typedef Mat_ Mat3f; typedef Mat_ Mat4f; typedef Mat_ Mat1d; typedef Mat_ Mat2d; typedef Mat_ Mat3d; typedef Mat_ Mat4d; /** @todo document */ class CV_EXPORTS UMat { public: //! default constructor UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT); //! constructs 2D matrix of the specified size and type // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! constucts 2D matrix and fills it with the specified value _s. UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! constructs n-dimensional matrix UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! copy constructor UMat(const UMat& m); //! creates a matrix header for a part of the bigger matrix UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all()); UMat(const UMat& m, const Rect& roi); UMat(const UMat& m, const Range* ranges); //! builds matrix from std::vector with or without copying the data template explicit UMat(const std::vector<_Tp>& vec, bool copyData=false); //! builds matrix from cv::Vec; the data is copied by default template explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true); //! builds matrix from cv::Matx; the data is copied by default template explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true); //! builds matrix from a 2D point template explicit UMat(const Point_<_Tp>& pt, bool copyData=true); //! builds matrix from a 3D point template explicit UMat(const Point3_<_Tp>& pt, bool copyData=true); //! builds matrix from comma initializer template explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer); //! destructor - calls release() ~UMat(); //! assignment operators UMat& operator = (const UMat& m); Mat getMat(int flags) const; //! returns a new matrix header for the specified row UMat row(int y) const; //! returns a new matrix header for the specified column UMat col(int x) const; //! ... for the specified row span UMat rowRange(int startrow, int endrow) const; UMat rowRange(const Range& r) const; //! ... for the specified column span UMat colRange(int startcol, int endcol) const; UMat colRange(const Range& r) const; //! ... for the specified diagonal // (d=0 - the main diagonal, // >0 - a diagonal from the lower half, // <0 - a diagonal from the upper half) UMat diag(int d=0) const; //! constructs a square diagonal matrix which main diagonal is vector "d" static UMat diag(const UMat& d); //! returns deep copy of the matrix, i.e. the data is copied UMat clone() const; //! copies the matrix content to "m". // It calls m.create(this->size(), this->type()). void copyTo( OutputArray m ) const; //! copies those matrix elements to "m" that are marked with non-zero mask elements. void copyTo( OutputArray m, InputArray mask ) const; //! converts matrix to another datatype with optional scalng. See cvConvertScale. void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; void assignTo( UMat& m, int type=-1 ) const; //! sets every matrix element to s UMat& operator = (const Scalar& s); //! sets some of the matrix elements to s, according to the mask UMat& setTo(InputArray value, InputArray mask=noArray()); //! creates alternative matrix header for the same data, with different // number of channels and/or different number of rows. see cvReshape. UMat reshape(int cn, int rows=0) const; UMat reshape(int cn, int newndims, const int* newsz) const; //! matrix transposition by means of matrix expressions UMat t() const; //! matrix inversion by means of matrix expressions UMat inv(int method=DECOMP_LU) const; //! per-element matrix multiplication by means of matrix expressions UMat mul(InputArray m, double scale=1) const; //! computes dot-product double dot(InputArray m) const; //! Matlab-style matrix initialization static UMat zeros(int rows, int cols, int type); static UMat zeros(Size size, int type); static UMat zeros(int ndims, const int* sz, int type); static UMat ones(int rows, int cols, int type); static UMat ones(Size size, int type); static UMat ones(int ndims, const int* sz, int type); static UMat eye(int rows, int cols, int type); static UMat eye(Size size, int type); //! allocates new matrix data unless the matrix already has specified size and type. // previous data is unreferenced if needed. void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! increases the reference counter; use with care to avoid memleaks void addref(); //! decreases reference counter; // deallocates the data when reference counter reaches 0. void release(); //! deallocates the matrix data void deallocate(); //! internal use function; properly re-allocates _size, _step arrays void copySize(const UMat& m); //! locates matrix header within a parent matrix. See below void locateROI( Size& wholeSize, Point& ofs ) const; //! moves/resizes the current matrix ROI inside the parent matrix. UMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); //! extracts a rectangular sub-matrix // (this is a generalized form of row, rowRange etc.) UMat operator()( Range rowRange, Range colRange ) const; UMat operator()( const Rect& roi ) const; UMat operator()( const Range* ranges ) const; //! returns true iff the matrix data is continuous // (i.e. when there are no gaps between successive rows). // similar to CV_IS_MAT_CONT(cvmat->type) bool isContinuous() const; //! returns true if the matrix is a submatrix of another matrix bool isSubmatrix() const; //! returns element size in bytes, // similar to CV_ELEM_SIZE(cvmat->type) size_t elemSize() const; //! returns the size of element channel in bytes. size_t elemSize1() const; //! returns element type, similar to CV_MAT_TYPE(cvmat->type) int type() const; //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) int depth() const; //! returns element type, similar to CV_MAT_CN(cvmat->type) int channels() const; //! returns step/elemSize1() size_t step1(int i=0) const; //! returns true if matrix data is NULL bool empty() const; //! returns the total number of matrix elements size_t total() const; //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; #ifdef CV_CXX_MOVE_SEMANTICS UMat(UMat&& m); UMat& operator = (UMat&& m); #endif void* handle(int accessFlags) const; void ndoffset(size_t* ofs) const; enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; /*! includes several bit-fields: - the magic signature - continuity flag - depth - number of channels */ int flags; //! the matrix dimensionality, >= 2 int dims; //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions int rows, cols; //! custom allocator MatAllocator* allocator; UMatUsageFlags usageFlags; // usage flags for allocator //! and the standard allocator static MatAllocator* getStdAllocator(); // black-box container of UMat data UMatData* u; // offset of the submatrix (or 0) size_t offset; MatSize size; MatStep step; protected: }; /////////////////////////// multi-dimensional sparse matrix ////////////////////////// /** @brief The class SparseMat represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its stored elements can actually become 0. It is up to you to detect such elements and delete them using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is filled so that the search time is O(1) in average (regardless of whether element is there or not). Elements can be accessed using the following methods: - Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and SparseMat::find), for example: @code const int dims = 5; int size[] = {10, 10, 10, 10, 10}; SparseMat sparse_mat(dims, size, CV_32F); for(int i = 0; i < 1000; i++) { int idx[dims]; for(int k = 0; k < dims; k++) idx[k] = rand() sparse_mat.ref(idx) += 1.f; } @endcode - Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. That is, the iteration loop is familiar to STL users: @code // prints elements of a sparse floating-point matrix // and the sum of elements. SparseMatConstIterator_ it = sparse_mat.begin(), it_end = sparse_mat.end(); double s = 0; int dims = sparse_mat.dims(); for(; it != it_end; ++it) { // print element indices and the element value const SparseMat::Node* n = it.node(); printf("("); for(int i = 0; i < dims; i++) printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")"); printf(": %g\n", it.value()); s += *it; } printf("Element sum is %g\n", s); @endcode If you run this loop, you will notice that elements are not enumerated in a logical order (lexicographical, and so on). They come in the same order as they are stored in the hash table (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. Note, however, that pointers to the nodes may become invalid when you add more elements to the matrix. This may happen due to possible buffer reallocation. - Combination of the above 2 methods when you need to process 2 or more sparse matrices simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 floating-point sparse matrices: @code double cross_corr(const SparseMat& a, const SparseMat& b) { const SparseMat *_a = &a, *_b = &b; // if b contains less elements than a, // it is faster to iterate through b if(_a->nzcount() > _b->nzcount()) std::swap(_a, _b); SparseMatConstIterator_ it = _a->begin(), it_end = _a->end(); double ccorr = 0; for(; it != it_end; ++it) { // take the next element from the first matrix float avalue = *it; const Node* anode = it.node(); // and try to find an element with the same index in the second matrix. // since the hash value depends only on the element index, // reuse the hash value stored in the node float bvalue = _b->value(anode->idx,&anode->hashval); ccorr += avalue*bvalue; } return ccorr; } @endcode */ class CV_EXPORTS SparseMat { public: typedef SparseMatIterator iterator; typedef SparseMatConstIterator const_iterator; enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; //! the sparse matrix header struct CV_EXPORTS Hdr { Hdr(int _dims, const int* _sizes, int _type); void clear(); int refcount; int dims; int valueOffset; size_t nodeSize; size_t nodeCount; size_t freeList; std::vector pool; std::vector hashtab; int size[MAX_DIM]; }; //! sparse matrix node - element of a hash table struct CV_EXPORTS Node { //! hash value size_t hashval; //! index of the next node in the same hash table entry size_t next; //! index of the matrix element int idx[MAX_DIM]; }; /** @brief Various SparseMat constructors. */ SparseMat(); /** @overload @param dims Array dimensionality. @param _sizes Sparce matrix size on all dementions. @param _type Sparse matrix data type. */ SparseMat(int dims, const int* _sizes, int _type); /** @overload @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted to sparse representation. */ SparseMat(const SparseMat& m); /** @overload @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted to sparse representation. */ explicit SparseMat(const Mat& m); //! the destructor ~SparseMat(); //! assignment operator. This is O(1) operation, i.e. no data is copied SparseMat& operator = (const SparseMat& m); //! equivalent to the corresponding constructor SparseMat& operator = (const Mat& m); //! creates full copy of the matrix SparseMat clone() const; //! copies all the data to the destination matrix. All the previous content of m is erased void copyTo( SparseMat& m ) const; //! converts sparse matrix to dense matrix. void copyTo( Mat& m ) const; //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. /*! @param [out] m - output matrix; if it does not have a proper size or type before the operation, it is reallocated @param [in] rtype – desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input. @param [in] alpha – optional scale factor @param [in] beta – optional delta added to the scaled values */ void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; // not used now void assignTo( SparseMat& m, int type=-1 ) const; //! reallocates sparse matrix. /*! If the matrix already had the proper size and type, it is simply cleared with clear(), otherwise, the old matrix is released (using release()) and the new one is allocated. */ void create(int dims, const int* _sizes, int _type); //! sets all the sparse matrix elements to 0, which means clearing the hash table. void clear(); //! manually increments the reference counter to the header. void addref(); // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. void release(); //! converts sparse matrix to the old-style representation; all the elements are copied. //operator CvSparseMat*() const; //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) size_t elemSize() const; //! returns elemSize()/channels() size_t elemSize1() const; //! returns type of sparse matrix elements int type() const; //! returns the depth of sparse matrix elements int depth() const; //! returns the number of channels int channels() const; //! returns the array of sizes, or NULL if the matrix is not allocated const int* size() const; //! returns the size of i-th matrix dimension (or 0) int size(int i) const; //! returns the matrix dimensionality int dims() const; //! returns the number of non-zero elements (=the number of hash table nodes) size_t nzcount() const; //! computes the element hash value (1D case) size_t hash(int i0) const; //! computes the element hash value (2D case) size_t hash(int i0, int i1) const; //! computes the element hash value (3D case) size_t hash(int i0, int i1, int i2) const; //! computes the element hash value (nD case) size_t hash(const int* idx) const; //!@{ /*! specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. return pointer to the matrix element. - if the element is there (it's non-zero), the pointer to it is returned - if it's not there and createMissing=false, NULL pointer is returned - if it's not there and createMissing=true, then the new element is created and initialized with 0. Pointer to it is returned - if the optional hashval pointer is not NULL, the element hash value is not computed, but *hashval is taken instead. */ //! returns pointer to the specified element (1D case) uchar* ptr(int i0, bool createMissing, size_t* hashval=0); //! returns pointer to the specified element (2D case) uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); //! returns pointer to the specified element (3D case) uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); //! returns pointer to the specified element (nD case) uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); //!@} //!@{ /*! return read-write reference to the specified sparse matrix element. `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`. The methods always return a valid reference. If the element did not exist, it is created and initialiazed with 0. */ //! returns reference to the specified element (1D case) template _Tp& ref(int i0, size_t* hashval=0); //! returns reference to the specified element (2D case) template _Tp& ref(int i0, int i1, size_t* hashval=0); //! returns reference to the specified element (3D case) template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); //! returns reference to the specified element (nD case) template _Tp& ref(const int* idx, size_t* hashval=0); //!@} //!@{ /*! return value of the specified sparse matrix element. `value<_Tp>(i0,...[,hashval])` is equivalent to @code { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } @endcode That is, if the element did not exist, the methods return 0. */ //! returns value of the specified element (1D case) template _Tp value(int i0, size_t* hashval=0) const; //! returns value of the specified element (2D case) template _Tp value(int i0, int i1, size_t* hashval=0) const; //! returns value of the specified element (3D case) template _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; //! returns value of the specified element (nD case) template _Tp value(const int* idx, size_t* hashval=0) const; //!@} //!@{ /*! Return pointer to the specified sparse matrix element if it exists `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`. If the specified element does not exist, the methods return NULL. */ //! returns pointer to the specified element (1D case) template const _Tp* find(int i0, size_t* hashval=0) const; //! returns pointer to the specified element (2D case) template const _Tp* find(int i0, int i1, size_t* hashval=0) const; //! returns pointer to the specified element (3D case) template const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; //! returns pointer to the specified element (nD case) template const _Tp* find(const int* idx, size_t* hashval=0) const; //!@} //! erases the specified element (2D case) void erase(int i0, int i1, size_t* hashval=0); //! erases the specified element (3D case) void erase(int i0, int i1, int i2, size_t* hashval=0); //! erases the specified element (nD case) void erase(const int* idx, size_t* hashval=0); //!@{ /*! return the sparse matrix iterator pointing to the first sparse matrix element */ //! returns the sparse matrix iterator at the matrix beginning SparseMatIterator begin(); //! returns the sparse matrix iterator at the matrix beginning template SparseMatIterator_<_Tp> begin(); //! returns the read-only sparse matrix iterator at the matrix beginning SparseMatConstIterator begin() const; //! returns the read-only sparse matrix iterator at the matrix beginning template SparseMatConstIterator_<_Tp> begin() const; //!@} /*! return the sparse matrix iterator pointing to the element following the last sparse matrix element */ //! returns the sparse matrix iterator at the matrix end SparseMatIterator end(); //! returns the read-only sparse matrix iterator at the matrix end SparseMatConstIterator end() const; //! returns the typed sparse matrix iterator at the matrix end template SparseMatIterator_<_Tp> end(); //! returns the typed read-only sparse matrix iterator at the matrix end template SparseMatConstIterator_<_Tp> end() const; //! returns the value stored in the sparse martix node template _Tp& value(Node* n); //! returns the value stored in the sparse martix node template const _Tp& value(const Node* n) const; ////////////// some internal-use methods /////////////// Node* node(size_t nidx); const Node* node(size_t nidx) const; uchar* newNode(const int* idx, size_t hashval); void removeNode(size_t hidx, size_t nidx, size_t previdx); void resizeHashTab(size_t newsize); int flags; Hdr* hdr; }; ///////////////////////////////// SparseMat_<_Tp> //////////////////////////////////// /** @brief Template sparse n-dimensional array class derived from SparseMat SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies notation of some operations: @code int sz[] = {10, 20, 30}; SparseMat_ M(3, sz); ... M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9); @endcode */ template class SparseMat_ : public SparseMat { public: typedef SparseMatIterator_<_Tp> iterator; typedef SparseMatConstIterator_<_Tp> const_iterator; //! the default constructor SparseMat_(); //! the full constructor equivelent to SparseMat(dims, _sizes, DataType<_Tp>::type) SparseMat_(int dims, const int* _sizes); //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted SparseMat_(const SparseMat& m); //! the copy constructor. This is O(1) operation - no data is copied SparseMat_(const SparseMat_& m); //! converts dense matrix to the sparse form SparseMat_(const Mat& m); //! converts the old-style sparse matrix to the C++ class. All the elements are copied //SparseMat_(const CvSparseMat* m); //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted SparseMat_& operator = (const SparseMat& m); //! the assignment operator. This is O(1) operation - no data is copied SparseMat_& operator = (const SparseMat_& m); //! converts dense matrix to the sparse form SparseMat_& operator = (const Mat& m); //! makes full copy of the matrix. All the elements are duplicated SparseMat_ clone() const; //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) void create(int dims, const int* _sizes); //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied //operator CvSparseMat*() const; //! returns type of the matrix elements int type() const; //! returns depth of the matrix elements int depth() const; //! returns the number of channels in each matrix element int channels() const; //! equivalent to SparseMat::ref<_Tp>(i0, hashval) _Tp& ref(int i0, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) _Tp& ref(int i0, int i1, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(idx, hashval) _Tp& ref(const int* idx, size_t* hashval=0); //! equivalent to SparseMat::value<_Tp>(i0, hashval) _Tp operator()(int i0, size_t* hashval=0) const; //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) _Tp operator()(int i0, int i1, size_t* hashval=0) const; //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; //! equivalent to SparseMat::value<_Tp>(idx, hashval) _Tp operator()(const int* idx, size_t* hashval=0) const; //! returns sparse matrix iterator pointing to the first sparse matrix element SparseMatIterator_<_Tp> begin(); //! returns read-only sparse matrix iterator pointing to the first sparse matrix element SparseMatConstIterator_<_Tp> begin() const; //! returns sparse matrix iterator pointing to the element following the last sparse matrix element SparseMatIterator_<_Tp> end(); //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element SparseMatConstIterator_<_Tp> end() const; }; ////////////////////////////////// MatConstIterator ////////////////////////////////// class CV_EXPORTS MatConstIterator { public: typedef uchar* value_type; typedef ptrdiff_t difference_type; typedef const uchar** pointer; typedef uchar* reference; #ifndef OPENCV_NOSTL typedef std::random_access_iterator_tag iterator_category; #endif //! default constructor MatConstIterator(); //! constructor that sets the iterator to the beginning of the matrix MatConstIterator(const Mat* _m); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator(const Mat* _m, int _row, int _col=0); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator(const Mat* _m, Point _pt); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator(const Mat* _m, const int* _idx); //! copy constructor MatConstIterator(const MatConstIterator& it); //! copy operator MatConstIterator& operator = (const MatConstIterator& it); //! returns the current matrix element const uchar* operator *() const; //! returns the i-th matrix element, relative to the current const uchar* operator [](ptrdiff_t i) const; //! shifts the iterator forward by the specified number of elements MatConstIterator& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements MatConstIterator& operator -= (ptrdiff_t ofs); //! decrements the iterator MatConstIterator& operator --(); //! decrements the iterator MatConstIterator operator --(int); //! increments the iterator MatConstIterator& operator ++(); //! increments the iterator MatConstIterator operator ++(int); //! returns the current iterator position Point pos() const; //! returns the current iterator position void pos(int* _idx) const; ptrdiff_t lpos() const; void seek(ptrdiff_t ofs, bool relative = false); void seek(const int* _idx, bool relative = false); const Mat* m; size_t elemSize; const uchar* ptr; const uchar* sliceStart; const uchar* sliceEnd; }; ////////////////////////////////// MatConstIterator_ ///////////////////////////////// /** @brief Matrix read-only iterator */ template class MatConstIterator_ : public MatConstIterator { public: typedef _Tp value_type; typedef ptrdiff_t difference_type; typedef const _Tp* pointer; typedef const _Tp& reference; #ifndef OPENCV_NOSTL typedef std::random_access_iterator_tag iterator_category; #endif //! default constructor MatConstIterator_(); //! constructor that sets the iterator to the beginning of the matrix MatConstIterator_(const Mat_<_Tp>* _m); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); //! copy constructor MatConstIterator_(const MatConstIterator_& it); //! copy operator MatConstIterator_& operator = (const MatConstIterator_& it); //! returns the current matrix element _Tp operator *() const; //! returns the i-th matrix element, relative to the current _Tp operator [](ptrdiff_t i) const; //! shifts the iterator forward by the specified number of elements MatConstIterator_& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements MatConstIterator_& operator -= (ptrdiff_t ofs); //! decrements the iterator MatConstIterator_& operator --(); //! decrements the iterator MatConstIterator_ operator --(int); //! increments the iterator MatConstIterator_& operator ++(); //! increments the iterator MatConstIterator_ operator ++(int); //! returns the current iterator position Point pos() const; }; //////////////////////////////////// MatIterator_ //////////////////////////////////// /** @brief Matrix read-write iterator */ template class MatIterator_ : public MatConstIterator_<_Tp> { public: typedef _Tp* pointer; typedef _Tp& reference; #ifndef OPENCV_NOSTL typedef std::random_access_iterator_tag iterator_category; #endif //! the default constructor MatIterator_(); //! constructor that sets the iterator to the beginning of the matrix MatIterator_(Mat_<_Tp>* _m); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, Point _pt); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, const int* _idx); //! copy constructor MatIterator_(const MatIterator_& it); //! copy operator MatIterator_& operator = (const MatIterator_<_Tp>& it ); //! returns the current matrix element _Tp& operator *() const; //! returns the i-th matrix element, relative to the current _Tp& operator [](ptrdiff_t i) const; //! shifts the iterator forward by the specified number of elements MatIterator_& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements MatIterator_& operator -= (ptrdiff_t ofs); //! decrements the iterator MatIterator_& operator --(); //! decrements the iterator MatIterator_ operator --(int); //! increments the iterator MatIterator_& operator ++(); //! increments the iterator MatIterator_ operator ++(int); }; /////////////////////////////// SparseMatConstIterator /////////////////////////////// /** @brief Read-Only Sparse Matrix Iterator. Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: \code SparseMatConstIterator it = m.begin(), it_end = m.end(); double s = 0; CV_Assert( m.type() == CV_32F ); for( ; it != it_end; ++it ) s += it.value(); \endcode */ class CV_EXPORTS SparseMatConstIterator { public: //! the default constructor SparseMatConstIterator(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatConstIterator(const SparseMat* _m); //! the copy constructor SparseMatConstIterator(const SparseMatConstIterator& it); //! the assignment operator SparseMatConstIterator& operator = (const SparseMatConstIterator& it); //! template method returning the current matrix element template const _Tp& value() const; //! returns the current node of the sparse matrix. it.node->idx is the current element index const SparseMat::Node* node() const; //! moves iterator to the previous element SparseMatConstIterator& operator --(); //! moves iterator to the previous element SparseMatConstIterator operator --(int); //! moves iterator to the next element SparseMatConstIterator& operator ++(); //! moves iterator to the next element SparseMatConstIterator operator ++(int); //! moves iterator to the element after the last element void seekEnd(); const SparseMat* m; size_t hashidx; uchar* ptr; }; ////////////////////////////////// SparseMatIterator ///////////////////////////////// /** @brief Read-write Sparse Matrix Iterator The class is similar to cv::SparseMatConstIterator, but can be used for in-place modification of the matrix elements. */ class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator { public: //! the default constructor SparseMatIterator(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatIterator(SparseMat* _m); //! the full constructor setting the iterator to the specified sparse matrix element SparseMatIterator(SparseMat* _m, const int* idx); //! the copy constructor SparseMatIterator(const SparseMatIterator& it); //! the assignment operator SparseMatIterator& operator = (const SparseMatIterator& it); //! returns read-write reference to the current sparse matrix element template _Tp& value() const; //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) SparseMat::Node* node() const; //! moves iterator to the next element SparseMatIterator& operator ++(); //! moves iterator to the next element SparseMatIterator operator ++(int); }; /////////////////////////////// SparseMatConstIterator_ ////////////////////////////// /** @brief Template Read-Only Sparse Matrix Iterator Class. This is the derived from SparseMatConstIterator class that introduces more convenient operator *() for accessing the current element. */ template class SparseMatConstIterator_ : public SparseMatConstIterator { public: #ifndef OPENCV_NOSTL typedef std::forward_iterator_tag iterator_category; #endif //! the default constructor SparseMatConstIterator_(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatConstIterator_(const SparseMat_<_Tp>* _m); SparseMatConstIterator_(const SparseMat* _m); //! the copy constructor SparseMatConstIterator_(const SparseMatConstIterator_& it); //! the assignment operator SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); //! the element access operator const _Tp& operator *() const; //! moves iterator to the next element SparseMatConstIterator_& operator ++(); //! moves iterator to the next element SparseMatConstIterator_ operator ++(int); }; ///////////////////////////////// SparseMatIterator_ ///////////////////////////////// /** @brief Template Read-Write Sparse Matrix Iterator Class. This is the derived from cv::SparseMatConstIterator_ class that introduces more convenient operator *() for accessing the current element. */ template class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> { public: #ifndef OPENCV_NOSTL typedef std::forward_iterator_tag iterator_category; #endif //! the default constructor SparseMatIterator_(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatIterator_(SparseMat_<_Tp>* _m); SparseMatIterator_(SparseMat* _m); //! the copy constructor SparseMatIterator_(const SparseMatIterator_& it); //! the assignment operator SparseMatIterator_& operator = (const SparseMatIterator_& it); //! returns the reference to the current element _Tp& operator *() const; //! moves the iterator to the next element SparseMatIterator_& operator ++(); //! moves the iterator to the next element SparseMatIterator_ operator ++(int); }; /////////////////////////////////// NAryMatIterator ////////////////////////////////// /** @brief n-ary multi-dimensional array iterator. Use the class to implement unary, binary, and, generally, n-ary element-wise operations on multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of the iterators after each small operations may be a big overhead. In this case consider using NAryMatIterator to iterate through several matrices simultaneously as long as they have the same geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`, `it.planes[1]`,... will be the slices of the corresponding matrices. The example below illustrates how you can compute a normalized and threshold 3D color histogram: @code void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) { const int histSize[] = {N, N, N}; // make sure that the histogram has a proper size and type hist.create(3, histSize, CV_32F); // and clear it hist = Scalar(0); // the loop below assumes that the image // is a 8-bit 3-channel. check it. CV_Assert(image.type() == CV_8UC3); MatConstIterator_ it = image.begin(), it_end = image.end(); for( ; it != it_end; ++it ) { const Vec3b& pix = *it; hist.at(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; } minProb *= image.rows*image.cols; Mat plane; NAryMatIterator it(&hist, &plane, 1); double s = 0; // iterate through the matrix. on each iteration // it.planes[*] (of type Mat) will be set to the current plane. for(int p = 0; p < it.nplanes; p++, ++it) { threshold(it.planes[0], it.planes[0], minProb, 0, THRESH_TOZERO); s += sum(it.planes[0])[0]; } s = 1./s; it = NAryMatIterator(&hist, &plane, 1); for(int p = 0; p < it.nplanes; p++, ++it) it.planes[0] *= s; } @endcode */ class CV_EXPORTS NAryMatIterator { public: //! the default constructor NAryMatIterator(); //! the full constructor taking arbitrary number of n-dim matrices NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); //! the full constructor taking arbitrary number of n-dim matrices NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); //! the separate iterator initialization method void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); //! proceeds to the next plane of every iterated matrix NAryMatIterator& operator ++(); //! proceeds to the next plane of every iterated matrix (postfix increment operator) NAryMatIterator operator ++(int); //! the iterated arrays const Mat** arrays; //! the current planes Mat* planes; //! data pointers uchar** ptrs; //! the number of arrays int narrays; //! the number of hyper-planes that the iterator steps through size_t nplanes; //! the size of each segment (in elements) size_t size; protected: int iterdepth; size_t idx; }; ///////////////////////////////// Matrix Expressions ///////////////////////////////// class CV_EXPORTS MatOp { public: MatOp(); virtual ~MatOp(); virtual bool elementWise(const MatExpr& expr) const; virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; virtual void roi(const MatExpr& expr, const Range& rowRange, const Range& colRange, MatExpr& res) const; virtual void diag(const MatExpr& expr, int d, MatExpr& res) const; virtual void augAssignAdd(const MatExpr& expr, Mat& m) const; virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const; virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const; virtual void augAssignDivide(const MatExpr& expr, Mat& m) const; virtual void augAssignAnd(const MatExpr& expr, Mat& m) const; virtual void augAssignOr(const MatExpr& expr, Mat& m) const; virtual void augAssignXor(const MatExpr& expr, Mat& m) const; virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const; virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const; virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const; virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; virtual void divide(double s, const MatExpr& expr, MatExpr& res) const; virtual void abs(const MatExpr& expr, MatExpr& res) const; virtual void transpose(const MatExpr& expr, MatExpr& res) const; virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; virtual Size size(const MatExpr& expr) const; virtual int type(const MatExpr& expr) const; }; /** @brief Matrix expression representation @anchor MatrixExpressions This is a list of implemented matrix operations that can be combined in arbitrary complex expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a real-valued scalar ( double )): - Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A` - Scaling: `A*alpha` - Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A` - Matrix multiplication: `A*B` - Transposition: `A.t()` (means AT) - Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems: `A.inv([method]) (~ A-1)`, `A.inv([method])*B (~ X: AX=B)` - Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose elements are set to 255 (if the particular element or pair of elements satisfy the condition) or 0. - Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of `&`, `|`, `^`. - Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)` - Element-wise absolute value: `abs(A)` - Cross-product, dot-product: `A.cross(B)`, `A.dot(B)` - Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm, mean, sum, countNonZero, trace, determinant, repeat, and others. - Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated initializers, matrix constructors and operators that extract sub-matrices (see Mat description). - Mat_() constructors to cast the result to the proper type. @note Comma-separated initializers and probably some other operations may require additional explicit Mat() or Mat_() constructor calls to resolve a possible ambiguity. Here are examples of matrix expressions: @code // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD) SVD svd(A); Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t(); // compute the new vector of parameters in the Levenberg-Marquardt algorithm x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err); // sharpen image using "unsharp mask" algorithm Mat blurred; double sigma = 1, threshold = 5, amount = 1; GaussianBlur(img, blurred, Size(), sigma, sigma); Mat lowContrastMask = abs(img - blurred) < threshold; Mat sharpened = img*(1+amount) + blurred*(-amount); img.copyTo(sharpened, lowContrastMask); @endcode */ class CV_EXPORTS MatExpr { public: MatExpr(); explicit MatExpr(const Mat& m); MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(), const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar()); operator Mat() const; template operator Mat_<_Tp>() const; Size size() const; int type() const; MatExpr row(int y) const; MatExpr col(int x) const; MatExpr diag(int d = 0) const; MatExpr operator()( const Range& rowRange, const Range& colRange ) const; MatExpr operator()( const Rect& roi ) const; MatExpr t() const; MatExpr inv(int method = DECOMP_LU) const; MatExpr mul(const MatExpr& e, double scale=1) const; MatExpr mul(const Mat& m, double scale=1) const; Mat cross(const Mat& m) const; double dot(const Mat& m) const; const MatOp* op; int flags; Mat a, b, c; double alpha, beta; Scalar s; }; //! @} core_basic //! @relates cv::MatExpr //! @{ CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s); CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e); CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2); CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s); CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e); CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2); CV_EXPORTS MatExpr operator - (const Mat& m); CV_EXPORTS MatExpr operator - (const MatExpr& e); CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator * (const Mat& a, double s); CV_EXPORTS MatExpr operator * (double s, const Mat& a); CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator / (const Mat& a, double s); CV_EXPORTS MatExpr operator / (double s, const Mat& a); CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator < (const Mat& a, double s); CV_EXPORTS MatExpr operator < (double s, const Mat& a); CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator <= (const Mat& a, double s); CV_EXPORTS MatExpr operator <= (double s, const Mat& a); CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator == (const Mat& a, double s); CV_EXPORTS MatExpr operator == (double s, const Mat& a); CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator != (const Mat& a, double s); CV_EXPORTS MatExpr operator != (double s, const Mat& a); CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator >= (const Mat& a, double s); CV_EXPORTS MatExpr operator >= (double s, const Mat& a); CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator > (const Mat& a, double s); CV_EXPORTS MatExpr operator > (double s, const Mat& a); CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator ~(const Mat& m); CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); CV_EXPORTS MatExpr min(const Mat& a, double s); CV_EXPORTS MatExpr min(double s, const Mat& a); CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); CV_EXPORTS MatExpr max(const Mat& a, double s); CV_EXPORTS MatExpr max(double s, const Mat& a); /** @brief Calculates an absolute value of each matrix element. abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms: - C = abs(A-B) is equivalent to `absdiff(A, B, C)` - C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)` - C = `Mat_ >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha, beta)` The output matrix has the same size and the same type as the input one except for the last case, where C is depth=CV_8U . @param m matrix. @sa @ref MatrixExpressions, absdiff, convertScaleAbs */ CV_EXPORTS MatExpr abs(const Mat& m); /** @overload @param e matrix expression. */ CV_EXPORTS MatExpr abs(const MatExpr& e); //! @} relates cv::MatExpr } // cv #include "opencv2/core/mat.inl.hpp" #endif // __OPENCV_CORE_MAT_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/mat.inl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_MATRIX_OPERATIONS_HPP__ #define __OPENCV_CORE_MATRIX_OPERATIONS_HPP__ #ifndef __cplusplus # error mat.inl.hpp header must be compiled as C++ #endif namespace cv { //! @cond IGNORED //////////////////////// Input/Output Arrays //////////////////////// inline void _InputArray::init(int _flags, const void* _obj) { flags = _flags; obj = (void*)_obj; } inline void _InputArray::init(int _flags, const void* _obj, Size _sz) { flags = _flags; obj = (void*)_obj; sz = _sz; } inline void* _InputArray::getObj() const { return obj; } inline int _InputArray::getFlags() const { return flags; } inline Size _InputArray::getSz() const { return sz; } inline _InputArray::_InputArray() { init(NONE, 0); } inline _InputArray::_InputArray(int _flags, void* _obj) { init(_flags, _obj); } inline _InputArray::_InputArray(const Mat& m) { init(MAT+ACCESS_READ, &m); } inline _InputArray::_InputArray(const std::vector& vec) { init(STD_VECTOR_MAT+ACCESS_READ, &vec); } inline _InputArray::_InputArray(const UMat& m) { init(UMAT+ACCESS_READ, &m); } inline _InputArray::_InputArray(const std::vector& vec) { init(STD_VECTOR_UMAT+ACCESS_READ, &vec); } template inline _InputArray::_InputArray(const std::vector<_Tp>& vec) { init(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type + ACCESS_READ, &vec); } inline _InputArray::_InputArray(const std::vector& vec) { init(FIXED_TYPE + STD_BOOL_VECTOR + DataType::type + ACCESS_READ, &vec); } template inline _InputArray::_InputArray(const std::vector >& vec) { init(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_READ, &vec); } template inline _InputArray::_InputArray(const std::vector >& vec) { init(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_READ, &vec); } template inline _InputArray::_InputArray(const Matx<_Tp, m, n>& mtx) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_READ, &mtx, Size(n, m)); } template inline _InputArray::_InputArray(const _Tp* vec, int n) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_READ, vec, Size(n, 1)); } template inline _InputArray::_InputArray(const Mat_<_Tp>& m) { init(FIXED_TYPE + MAT + DataType<_Tp>::type + ACCESS_READ, &m); } inline _InputArray::_InputArray(const double& val) { init(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F + ACCESS_READ, &val, Size(1,1)); } inline _InputArray::_InputArray(const MatExpr& expr) { init(FIXED_TYPE + FIXED_SIZE + EXPR + ACCESS_READ, &expr); } inline _InputArray::_InputArray(const cuda::GpuMat& d_mat) { init(CUDA_GPU_MAT + ACCESS_READ, &d_mat); } inline _InputArray::_InputArray(const std::vector& d_mat) { init(STD_VECTOR_CUDA_GPU_MAT + ACCESS_READ, &d_mat);} inline _InputArray::_InputArray(const ogl::Buffer& buf) { init(OPENGL_BUFFER + ACCESS_READ, &buf); } inline _InputArray::_InputArray(const cuda::HostMem& cuda_mem) { init(CUDA_HOST_MEM + ACCESS_READ, &cuda_mem); } inline _InputArray::~_InputArray() {} inline Mat _InputArray::getMat(int i) const { if( kind() == MAT && i < 0 ) return *(const Mat*)obj; return getMat_(i); } inline bool _InputArray::isMat() const { return kind() == _InputArray::MAT; } inline bool _InputArray::isUMat() const { return kind() == _InputArray::UMAT; } inline bool _InputArray::isMatVector() const { return kind() == _InputArray::STD_VECTOR_MAT; } inline bool _InputArray::isUMatVector() const { return kind() == _InputArray::STD_VECTOR_UMAT; } inline bool _InputArray::isMatx() const { return kind() == _InputArray::MATX; } inline bool _InputArray::isVector() const { return kind() == _InputArray::STD_VECTOR || kind() == _InputArray::STD_BOOL_VECTOR; } inline bool _InputArray::isGpuMatVector() const { return kind() == _InputArray::STD_VECTOR_CUDA_GPU_MAT; } //////////////////////////////////////////////////////////////////////////////////////// inline _OutputArray::_OutputArray() { init(ACCESS_WRITE, 0); } inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags|ACCESS_WRITE, _obj); } inline _OutputArray::_OutputArray(Mat& m) { init(MAT+ACCESS_WRITE, &m); } inline _OutputArray::_OutputArray(std::vector& vec) { init(STD_VECTOR_MAT+ACCESS_WRITE, &vec); } inline _OutputArray::_OutputArray(UMat& m) { init(UMAT+ACCESS_WRITE, &m); } inline _OutputArray::_OutputArray(std::vector& vec) { init(STD_VECTOR_UMAT+ACCESS_WRITE, &vec); } template inline _OutputArray::_OutputArray(std::vector<_Tp>& vec) { init(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); } inline _OutputArray::_OutputArray(std::vector&) { CV_Error(Error::StsUnsupportedFormat, "std::vector cannot be an output array\n"); } template inline _OutputArray::_OutputArray(std::vector >& vec) { init(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); } template inline _OutputArray::_OutputArray(std::vector >& vec) { init(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_WRITE, &vec); } template inline _OutputArray::_OutputArray(Mat_<_Tp>& m) { init(FIXED_TYPE + MAT + DataType<_Tp>::type + ACCESS_WRITE, &m); } template inline _OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, &mtx, Size(n, m)); } template inline _OutputArray::_OutputArray(_Tp* vec, int n) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, vec, Size(n, 1)); } template inline _OutputArray::_OutputArray(const std::vector<_Tp>& vec) { init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); } template inline _OutputArray::_OutputArray(const std::vector >& vec) { init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); } template inline _OutputArray::_OutputArray(const std::vector >& vec) { init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_WRITE, &vec); } template inline _OutputArray::_OutputArray(const Mat_<_Tp>& m) { init(FIXED_TYPE + FIXED_SIZE + MAT + DataType<_Tp>::type + ACCESS_WRITE, &m); } template inline _OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, &mtx, Size(n, m)); } template inline _OutputArray::_OutputArray(const _Tp* vec, int n) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, vec, Size(n, 1)); } inline _OutputArray::_OutputArray(cuda::GpuMat& d_mat) { init(CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } inline _OutputArray::_OutputArray(std::vector& d_mat) { init(STD_VECTOR_CUDA_GPU_MAT + ACCESS_WRITE, &d_mat);} inline _OutputArray::_OutputArray(ogl::Buffer& buf) { init(OPENGL_BUFFER + ACCESS_WRITE, &buf); } inline _OutputArray::_OutputArray(cuda::HostMem& cuda_mem) { init(CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } inline _OutputArray::_OutputArray(const Mat& m) { init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_WRITE, &m); } inline _OutputArray::_OutputArray(const std::vector& vec) { init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_WRITE, &vec); } inline _OutputArray::_OutputArray(const UMat& m) { init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_WRITE, &m); } inline _OutputArray::_OutputArray(const std::vector& vec) { init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } inline _OutputArray::_OutputArray(const cuda::GpuMat& d_mat) { init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } inline _OutputArray::_OutputArray(const ogl::Buffer& buf) { init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_WRITE, &buf); } inline _OutputArray::_OutputArray(const cuda::HostMem& cuda_mem) { init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } /////////////////////////////////////////////////////////////////////////////////////////// inline _InputOutputArray::_InputOutputArray() { init(ACCESS_RW, 0); } inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags|ACCESS_RW, _obj); } inline _InputOutputArray::_InputOutputArray(Mat& m) { init(MAT+ACCESS_RW, &m); } inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(STD_VECTOR_MAT+ACCESS_RW, &vec); } inline _InputOutputArray::_InputOutputArray(UMat& m) { init(UMAT+ACCESS_RW, &m); } inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(STD_VECTOR_UMAT+ACCESS_RW, &vec); } template inline _InputOutputArray::_InputOutputArray(std::vector<_Tp>& vec) { init(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); } inline _InputOutputArray::_InputOutputArray(std::vector&) { CV_Error(Error::StsUnsupportedFormat, "std::vector cannot be an input/output array\n"); } template inline _InputOutputArray::_InputOutputArray(std::vector >& vec) { init(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); } template inline _InputOutputArray::_InputOutputArray(std::vector >& vec) { init(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_RW, &vec); } template inline _InputOutputArray::_InputOutputArray(Mat_<_Tp>& m) { init(FIXED_TYPE + MAT + DataType<_Tp>::type + ACCESS_RW, &m); } template inline _InputOutputArray::_InputOutputArray(Matx<_Tp, m, n>& mtx) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, &mtx, Size(n, m)); } template inline _InputOutputArray::_InputOutputArray(_Tp* vec, int n) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, vec, Size(n, 1)); } template inline _InputOutputArray::_InputOutputArray(const std::vector<_Tp>& vec) { init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); } template inline _InputOutputArray::_InputOutputArray(const std::vector >& vec) { init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); } template inline _InputOutputArray::_InputOutputArray(const std::vector >& vec) { init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_RW, &vec); } template inline _InputOutputArray::_InputOutputArray(const Mat_<_Tp>& m) { init(FIXED_TYPE + FIXED_SIZE + MAT + DataType<_Tp>::type + ACCESS_RW, &m); } template inline _InputOutputArray::_InputOutputArray(const Matx<_Tp, m, n>& mtx) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, &mtx, Size(n, m)); } template inline _InputOutputArray::_InputOutputArray(const _Tp* vec, int n) { init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, vec, Size(n, 1)); } inline _InputOutputArray::_InputOutputArray(cuda::GpuMat& d_mat) { init(CUDA_GPU_MAT + ACCESS_RW, &d_mat); } inline _InputOutputArray::_InputOutputArray(ogl::Buffer& buf) { init(OPENGL_BUFFER + ACCESS_RW, &buf); } inline _InputOutputArray::_InputOutputArray(cuda::HostMem& cuda_mem) { init(CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } inline _InputOutputArray::_InputOutputArray(const Mat& m) { init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_RW, &m); } inline _InputOutputArray::_InputOutputArray(const std::vector& vec) { init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_RW, &vec); } inline _InputOutputArray::_InputOutputArray(const UMat& m) { init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_RW, &m); } inline _InputOutputArray::_InputOutputArray(const std::vector& vec) { init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_RW, &vec); } inline _InputOutputArray::_InputOutputArray(const cuda::GpuMat& d_mat) { init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_RW, &d_mat); } inline _InputOutputArray::_InputOutputArray(const std::vector& d_mat) { init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} inline _InputOutputArray::_InputOutputArray(const ogl::Buffer& buf) { init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_RW, &buf); } inline _InputOutputArray::_InputOutputArray(const cuda::HostMem& cuda_mem) { init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } //////////////////////////////////////////// Mat ////////////////////////////////////////// inline Mat::Mat() : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) {} inline Mat::Mat(int _rows, int _cols, int _type) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { create(_rows, _cols, _type); } inline Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { create(_rows, _cols, _type); *this = _s; } inline Mat::Mat(Size _sz, int _type) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { create( _sz.height, _sz.width, _type ); } inline Mat::Mat(Size _sz, int _type, const Scalar& _s) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { create(_sz.height, _sz.width, _type); *this = _s; } inline Mat::Mat(int _dims, const int* _sz, int _type) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { create(_dims, _sz, _type); } inline Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { create(_dims, _sz, _type); *this = _s; } inline Mat::Mat(const Mat& m) : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data), datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit), allocator(m.allocator), u(m.u), size(&rows) { if( u ) CV_XADD(&u->refcount, 1); if( m.dims <= 2 ) { step[0] = m.step[0]; step[1] = m.step[1]; } else { dims = 0; copySize(m); } } inline Mat::Mat(int _rows, int _cols, int _type, void* _data, size_t _step) : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_rows), cols(_cols), data((uchar*)_data), datastart((uchar*)_data), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { CV_Assert(total() == 0 || data != NULL); size_t esz = CV_ELEM_SIZE(_type), esz1 = CV_ELEM_SIZE1(_type); size_t minstep = cols * esz; if( _step == AUTO_STEP ) { _step = minstep; flags |= CONTINUOUS_FLAG; } else { if( rows == 1 ) _step = minstep; CV_DbgAssert( _step >= minstep ); if (_step % esz1 != 0) { CV_Error(Error::BadStep, "Step must be a multiple of esz1"); } flags |= _step == minstep ? CONTINUOUS_FLAG : 0; } step[0] = _step; step[1] = esz; datalimit = datastart + _step * rows; dataend = datalimit - _step + minstep; } inline Mat::Mat(Size _sz, int _type, void* _data, size_t _step) : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_sz.height), cols(_sz.width), data((uchar*)_data), datastart((uchar*)_data), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) { CV_Assert(total() == 0 || data != NULL); size_t esz = CV_ELEM_SIZE(_type), esz1 = CV_ELEM_SIZE1(_type); size_t minstep = cols*esz; if( _step == AUTO_STEP ) { _step = minstep; flags |= CONTINUOUS_FLAG; } else { if( rows == 1 ) _step = minstep; CV_DbgAssert( _step >= minstep ); if (_step % esz1 != 0) { CV_Error(Error::BadStep, "Step must be a multiple of esz1"); } flags |= _step == minstep ? CONTINUOUS_FLAG : 0; } step[0] = _step; step[1] = esz; datalimit = datastart + _step*rows; dataend = datalimit - _step + minstep; } template inline Mat::Mat(const std::vector<_Tp>& vec, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), cols(1), data(0), datastart(0), dataend(0), allocator(0), u(0), size(&rows) { if(vec.empty()) return; if( !copyData ) { step[0] = step[1] = sizeof(_Tp); datastart = data = (uchar*)&vec[0]; datalimit = dataend = datastart + rows * step[0]; } else Mat((int)vec.size(), 1, DataType<_Tp>::type, (uchar*)&vec[0]).copyTo(*this); } template inline Mat::Mat(const Vec<_Tp, n>& vec, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0), datastart(0), dataend(0), allocator(0), u(0), size(&rows) { if( !copyData ) { step[0] = step[1] = sizeof(_Tp); datastart = data = (uchar*)vec.val; datalimit = dataend = datastart + rows * step[0]; } else Mat(n, 1, DataType<_Tp>::type, (void*)vec.val).copyTo(*this); } template inline Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0), datastart(0), dataend(0), allocator(0), u(0), size(&rows) { if( !copyData ) { step[0] = cols * sizeof(_Tp); step[1] = sizeof(_Tp); datastart = data = (uchar*)M.val; datalimit = dataend = datastart + rows * step[0]; } else Mat(m, n, DataType<_Tp>::type, (uchar*)M.val).copyTo(*this); } template inline Mat::Mat(const Point_<_Tp>& pt, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0), datastart(0), dataend(0), allocator(0), u(0), size(&rows) { if( !copyData ) { step[0] = step[1] = sizeof(_Tp); datastart = data = (uchar*)&pt.x; datalimit = dataend = datastart + rows * step[0]; } else { create(2, 1, DataType<_Tp>::type); ((_Tp*)data)[0] = pt.x; ((_Tp*)data)[1] = pt.y; } } template inline Mat::Mat(const Point3_<_Tp>& pt, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0), datastart(0), dataend(0), allocator(0), u(0), size(&rows) { if( !copyData ) { step[0] = step[1] = sizeof(_Tp); datastart = data = (uchar*)&pt.x; datalimit = dataend = datastart + rows * step[0]; } else { create(3, 1, DataType<_Tp>::type); ((_Tp*)data)[0] = pt.x; ((_Tp*)data)[1] = pt.y; ((_Tp*)data)[2] = pt.z; } } template inline Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), allocator(0), u(0), size(&rows) { *this = commaInitializer.operator Mat_<_Tp>(); } inline Mat::~Mat() { release(); if( step.p != step.buf ) fastFree(step.p); } inline Mat& Mat::operator = (const Mat& m) { if( this != &m ) { if( m.u ) CV_XADD(&m.u->refcount, 1); release(); flags = m.flags; if( dims <= 2 && m.dims <= 2 ) { dims = m.dims; rows = m.rows; cols = m.cols; step[0] = m.step[0]; step[1] = m.step[1]; } else copySize(m); data = m.data; datastart = m.datastart; dataend = m.dataend; datalimit = m.datalimit; allocator = m.allocator; u = m.u; } return *this; } inline Mat Mat::row(int y) const { return Mat(*this, Range(y, y + 1), Range::all()); } inline Mat Mat::col(int x) const { return Mat(*this, Range::all(), Range(x, x + 1)); } inline Mat Mat::rowRange(int startrow, int endrow) const { return Mat(*this, Range(startrow, endrow), Range::all()); } inline Mat Mat::rowRange(const Range& r) const { return Mat(*this, r, Range::all()); } inline Mat Mat::colRange(int startcol, int endcol) const { return Mat(*this, Range::all(), Range(startcol, endcol)); } inline Mat Mat::colRange(const Range& r) const { return Mat(*this, Range::all(), r); } inline Mat Mat::clone() const { Mat m; copyTo(m); return m; } inline void Mat::assignTo( Mat& m, int _type ) const { if( _type < 0 ) m = *this; else convertTo(m, _type); } inline void Mat::create(int _rows, int _cols, int _type) { _type &= TYPE_MASK; if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && data ) return; int sz[] = {_rows, _cols}; create(2, sz, _type); } inline void Mat::create(Size _sz, int _type) { create(_sz.height, _sz.width, _type); } inline void Mat::addref() { if( u ) CV_XADD(&u->refcount, 1); } inline void Mat::release() { if( u && CV_XADD(&u->refcount, -1) == 1 ) deallocate(); u = NULL; datastart = dataend = datalimit = data = 0; for(int i = 0; i < dims; i++) size.p[i] = 0; } inline Mat Mat::operator()( Range _rowRange, Range _colRange ) const { return Mat(*this, _rowRange, _colRange); } inline Mat Mat::operator()( const Rect& roi ) const { return Mat(*this, roi); } inline Mat Mat::operator()(const Range* ranges) const { return Mat(*this, ranges); } inline bool Mat::isContinuous() const { return (flags & CONTINUOUS_FLAG) != 0; } inline bool Mat::isSubmatrix() const { return (flags & SUBMATRIX_FLAG) != 0; } inline size_t Mat::elemSize() const { return dims > 0 ? step.p[dims - 1] : 0; } inline size_t Mat::elemSize1() const { return CV_ELEM_SIZE1(flags); } inline int Mat::type() const { return CV_MAT_TYPE(flags); } inline int Mat::depth() const { return CV_MAT_DEPTH(flags); } inline int Mat::channels() const { return CV_MAT_CN(flags); } inline size_t Mat::step1(int i) const { return step.p[i] / elemSize1(); } inline bool Mat::empty() const { return data == 0 || total() == 0; } inline size_t Mat::total() const { if( dims <= 2 ) return (size_t)rows * cols; size_t p = 1; for( int i = 0; i < dims; i++ ) p *= size[i]; return p; } inline uchar* Mat::ptr(int y) { CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); return data + step.p[0] * y; } inline const uchar* Mat::ptr(int y) const { CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); return data + step.p[0] * y; } template inline _Tp* Mat::ptr(int y) { CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); return (_Tp*)(data + step.p[0] * y); } template inline const _Tp* Mat::ptr(int y) const { CV_DbgAssert( y == 0 || (data && dims >= 1 && data && (unsigned)y < (unsigned)size.p[0]) ); return (const _Tp*)(data + step.p[0] * y); } inline uchar* Mat::ptr(int i0, int i1) { CV_DbgAssert(dims >= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); return data + i0 * step.p[0] + i1 * step.p[1]; } inline const uchar* Mat::ptr(int i0, int i1) const { CV_DbgAssert(dims >= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); return data + i0 * step.p[0] + i1 * step.p[1]; } template inline _Tp* Mat::ptr(int i0, int i1) { CV_DbgAssert(dims >= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); } template inline const _Tp* Mat::ptr(int i0, int i1) const { CV_DbgAssert(dims >= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); } inline uchar* Mat::ptr(int i0, int i1, int i2) { CV_DbgAssert(dims >= 3); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; } inline const uchar* Mat::ptr(int i0, int i1, int i2) const { CV_DbgAssert(dims >= 3); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; } template inline _Tp* Mat::ptr(int i0, int i1, int i2) { CV_DbgAssert(dims >= 3); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); } template inline const _Tp* Mat::ptr(int i0, int i1, int i2) const { CV_DbgAssert(dims >= 3); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); } inline uchar* Mat::ptr(const int* idx) { int i, d = dims; uchar* p = data; CV_DbgAssert( d >= 1 && p ); for( i = 0; i < d; i++ ) { CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); p += idx[i] * step.p[i]; } return p; } inline const uchar* Mat::ptr(const int* idx) const { int i, d = dims; uchar* p = data; CV_DbgAssert( d >= 1 && p ); for( i = 0; i < d; i++ ) { CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); p += idx[i] * step.p[i]; } return p; } template inline _Tp& Mat::at(int i0, int i1) { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); CV_DbgAssert(CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); return ((_Tp*)(data + step.p[0] * i0))[i1]; } template inline const _Tp& Mat::at(int i0, int i1) const { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); CV_DbgAssert(CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); return ((const _Tp*)(data + step.p[0] * i0))[i1]; } template inline _Tp& Mat::at(Point pt) { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); CV_DbgAssert(CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; } template inline const _Tp& Mat::at(Point pt) const { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); CV_DbgAssert(CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; } template inline _Tp& Mat::at(int i0) { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); CV_DbgAssert(elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type)); if( isContinuous() || size.p[0] == 1 ) return ((_Tp*)data)[i0]; if( size.p[1] == 1 ) return *(_Tp*)(data + step.p[0] * i0); int i = i0 / cols, j = i0 - i * cols; return ((_Tp*)(data + step.p[0] * i))[j]; } template inline const _Tp& Mat::at(int i0) const { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); CV_DbgAssert(elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type)); if( isContinuous() || size.p[0] == 1 ) return ((const _Tp*)data)[i0]; if( size.p[1] == 1 ) return *(const _Tp*)(data + step.p[0] * i0); int i = i0 / cols, j = i0 - i * cols; return ((const _Tp*)(data + step.p[0] * i))[j]; } template inline _Tp& Mat::at(int i0, int i1, int i2) { CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); return *(_Tp*)ptr(i0, i1, i2); } template inline const _Tp& Mat::at(int i0, int i1, int i2) const { CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); return *(const _Tp*)ptr(i0, i1, i2); } template inline _Tp& Mat::at(const int* idx) { CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); return *(_Tp*)ptr(idx); } template inline const _Tp& Mat::at(const int* idx) const { CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); return *(const _Tp*)ptr(idx); } template inline _Tp& Mat::at(const Vec& idx) { CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); return *(_Tp*)ptr(idx.val); } template inline const _Tp& Mat::at(const Vec& idx) const { CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); return *(const _Tp*)ptr(idx.val); } template inline MatConstIterator_<_Tp> Mat::begin() const { CV_DbgAssert( elemSize() == sizeof(_Tp) ); return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this); } template inline MatConstIterator_<_Tp> Mat::end() const { CV_DbgAssert( elemSize() == sizeof(_Tp) ); MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); it += total(); return it; } template inline MatIterator_<_Tp> Mat::begin() { CV_DbgAssert( elemSize() == sizeof(_Tp) ); return MatIterator_<_Tp>((Mat_<_Tp>*)this); } template inline MatIterator_<_Tp> Mat::end() { CV_DbgAssert( elemSize() == sizeof(_Tp) ); MatIterator_<_Tp> it((Mat_<_Tp>*)this); it += total(); return it; } template inline void Mat::forEach(const Functor& operation) { this->forEach_impl<_Tp>(operation); } template inline void Mat::forEach(const Functor& operation) const { // call as not const (const_cast(this))->forEach(operation); } template inline Mat::operator std::vector<_Tp>() const { std::vector<_Tp> v; copyTo(v); return v; } template inline Mat::operator Vec<_Tp, n>() const { CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) && rows + cols - 1 == n && channels() == 1 ); if( isContinuous() && type() == DataType<_Tp>::type ) return Vec<_Tp, n>((_Tp*)data); Vec<_Tp, n> v; Mat tmp(rows, cols, DataType<_Tp>::type, v.val); convertTo(tmp, tmp.type()); return v; } template inline Mat::operator Matx<_Tp, m, n>() const { CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 ); if( isContinuous() && type() == DataType<_Tp>::type ) return Matx<_Tp, m, n>((_Tp*)data); Matx<_Tp, m, n> mtx; Mat tmp(rows, cols, DataType<_Tp>::type, mtx.val); convertTo(tmp, tmp.type()); return mtx; } template inline void Mat::push_back(const _Tp& elem) { if( !data ) { *this = Mat(1, 1, DataType<_Tp>::type, (void*)&elem).clone(); return; } CV_Assert(DataType<_Tp>::type == type() && cols == 1 /* && dims == 2 (cols == 1 implies dims == 2) */); const uchar* tmp = dataend + step[0]; if( !isSubmatrix() && isContinuous() && tmp <= datalimit ) { *(_Tp*)(data + (size.p[0]++) * step.p[0]) = elem; dataend = tmp; } else push_back_(&elem); } template inline void Mat::push_back(const Mat_<_Tp>& m) { push_back((const Mat&)m); } template<> inline void Mat::push_back(const MatExpr& expr) { push_back(static_cast(expr)); } #ifdef CV_CXX_MOVE_SEMANTICS inline Mat::Mat(Mat&& m) : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data), datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit), allocator(m.allocator), u(m.u), size(&rows) { if (m.dims <= 2) // move new step/size info { step[0] = m.step[0]; step[1] = m.step[1]; } else { CV_DbgAssert(m.step.p != m.step.buf); step.p = m.step.p; size.p = m.size.p; m.step.p = m.step.buf; m.size.p = &m.rows; } m.flags = MAGIC_VAL; m.dims = m.rows = m.cols = 0; m.data = NULL; m.datastart = NULL; m.dataend = NULL; m.datalimit = NULL; m.allocator = NULL; m.u = NULL; } inline Mat& Mat::operator = (Mat&& m) { release(); flags = m.flags; dims = m.dims; rows = m.rows; cols = m.cols; data = m.data; datastart = m.datastart; dataend = m.dataend; datalimit = m.datalimit; allocator = m.allocator; u = m.u; if (step.p != step.buf) // release self step/size { fastFree(step.p); step.p = step.buf; size.p = &rows; } if (m.dims <= 2) // move new step/size info { step[0] = m.step[0]; step[1] = m.step[1]; } else { CV_DbgAssert(m.step.p != m.step.buf); step.p = m.step.p; size.p = m.size.p; m.step.p = m.step.buf; m.size.p = &m.rows; } m.flags = MAGIC_VAL; m.dims = m.rows = m.cols = 0; m.data = NULL; m.datastart = NULL; m.dataend = NULL; m.datalimit = NULL; m.allocator = NULL; m.u = NULL; return *this; } #endif ///////////////////////////// MatSize //////////////////////////// inline MatSize::MatSize(int* _p) : p(_p) {} inline Size MatSize::operator()() const { CV_DbgAssert(p[-1] <= 2); return Size(p[1], p[0]); } inline const int& MatSize::operator[](int i) const { return p[i]; } inline int& MatSize::operator[](int i) { return p[i]; } inline MatSize::operator const int*() const { return p; } inline bool MatSize::operator == (const MatSize& sz) const { int d = p[-1]; int dsz = sz.p[-1]; if( d != dsz ) return false; if( d == 2 ) return p[0] == sz.p[0] && p[1] == sz.p[1]; for( int i = 0; i < d; i++ ) if( p[i] != sz.p[i] ) return false; return true; } inline bool MatSize::operator != (const MatSize& sz) const { return !(*this == sz); } ///////////////////////////// MatStep //////////////////////////// inline MatStep::MatStep() { p = buf; p[0] = p[1] = 0; } inline MatStep::MatStep(size_t s) { p = buf; p[0] = s; p[1] = 0; } inline const size_t& MatStep::operator[](int i) const { return p[i]; } inline size_t& MatStep::operator[](int i) { return p[i]; } inline MatStep::operator size_t() const { CV_DbgAssert( p == buf ); return buf[0]; } inline MatStep& MatStep::operator = (size_t s) { CV_DbgAssert( p == buf ); buf[0] = s; return *this; } ////////////////////////////// Mat_<_Tp> //////////////////////////// template inline Mat_<_Tp>::Mat_() : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; } template inline Mat_<_Tp>::Mat_(int _rows, int _cols) : Mat(_rows, _cols, DataType<_Tp>::type) { } template inline Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& value) : Mat(_rows, _cols, DataType<_Tp>::type) { *this = value; } template inline Mat_<_Tp>::Mat_(Size _sz) : Mat(_sz.height, _sz.width, DataType<_Tp>::type) {} template inline Mat_<_Tp>::Mat_(Size _sz, const _Tp& value) : Mat(_sz.height, _sz.width, DataType<_Tp>::type) { *this = value; } template inline Mat_<_Tp>::Mat_(int _dims, const int* _sz) : Mat(_dims, _sz, DataType<_Tp>::type) {} template inline Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s) : Mat(_dims, _sz, DataType<_Tp>::type, Scalar(_s)) {} template inline Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges) : Mat(m, ranges) {} template inline Mat_<_Tp>::Mat_(const Mat& m) : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; *this = m; } template inline Mat_<_Tp>::Mat_(const Mat_& m) : Mat(m) {} template inline Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps) : Mat(_rows, _cols, DataType<_Tp>::type, _data, steps) {} template inline Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange) : Mat(m, _rowRange, _colRange) {} template inline Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi) : Mat(m, roi) {} template template inline Mat_<_Tp>::Mat_(const Vec::channel_type, n>& vec, bool copyData) : Mat(n / DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&vec) { CV_Assert(n%DataType<_Tp>::channels == 0); if( copyData ) *this = clone(); } template template inline Mat_<_Tp>::Mat_(const Matx::channel_type, m, n>& M, bool copyData) : Mat(m, n / DataType<_Tp>::channels, DataType<_Tp>::type, (void*)&M) { CV_Assert(n % DataType<_Tp>::channels == 0); if( copyData ) *this = clone(); } template inline Mat_<_Tp>::Mat_(const Point_::channel_type>& pt, bool copyData) : Mat(2 / DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&pt) { CV_Assert(2 % DataType<_Tp>::channels == 0); if( copyData ) *this = clone(); } template inline Mat_<_Tp>::Mat_(const Point3_::channel_type>& pt, bool copyData) : Mat(3 / DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&pt) { CV_Assert(3 % DataType<_Tp>::channels == 0); if( copyData ) *this = clone(); } template inline Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer) : Mat(commaInitializer) {} template inline Mat_<_Tp>::Mat_(const std::vector<_Tp>& vec, bool copyData) : Mat(vec, copyData) {} template inline Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m) { if( DataType<_Tp>::type == m.type() ) { Mat::operator = (m); return *this; } if( DataType<_Tp>::depth == m.depth() ) { return (*this = m.reshape(DataType<_Tp>::channels, m.dims, 0)); } CV_DbgAssert(DataType<_Tp>::channels == m.channels()); m.convertTo(*this, type()); return *this; } template inline Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat_& m) { Mat::operator=(m); return *this; } template inline Mat_<_Tp>& Mat_<_Tp>::operator = (const _Tp& s) { typedef typename DataType<_Tp>::vec_type VT; Mat::operator=(Scalar((const VT&)s)); return *this; } template inline void Mat_<_Tp>::create(int _rows, int _cols) { Mat::create(_rows, _cols, DataType<_Tp>::type); } template inline void Mat_<_Tp>::create(Size _sz) { Mat::create(_sz, DataType<_Tp>::type); } template inline void Mat_<_Tp>::create(int _dims, const int* _sz) { Mat::create(_dims, _sz, DataType<_Tp>::type); } template inline Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const { return Mat_<_Tp>(Mat::cross(m)); } template template inline Mat_<_Tp>::operator Mat_() const { return Mat_(*this); } template inline Mat_<_Tp> Mat_<_Tp>::row(int y) const { return Mat_(*this, Range(y, y+1), Range::all()); } template inline Mat_<_Tp> Mat_<_Tp>::col(int x) const { return Mat_(*this, Range::all(), Range(x, x+1)); } template inline Mat_<_Tp> Mat_<_Tp>::diag(int d) const { return Mat_(Mat::diag(d)); } template inline Mat_<_Tp> Mat_<_Tp>::clone() const { return Mat_(Mat::clone()); } template inline size_t Mat_<_Tp>::elemSize() const { CV_DbgAssert( Mat::elemSize() == sizeof(_Tp) ); return sizeof(_Tp); } template inline size_t Mat_<_Tp>::elemSize1() const { CV_DbgAssert( Mat::elemSize1() == sizeof(_Tp) / DataType<_Tp>::channels ); return sizeof(_Tp) / DataType<_Tp>::channels; } template inline int Mat_<_Tp>::type() const { CV_DbgAssert( Mat::type() == DataType<_Tp>::type ); return DataType<_Tp>::type; } template inline int Mat_<_Tp>::depth() const { CV_DbgAssert( Mat::depth() == DataType<_Tp>::depth ); return DataType<_Tp>::depth; } template inline int Mat_<_Tp>::channels() const { CV_DbgAssert( Mat::channels() == DataType<_Tp>::channels ); return DataType<_Tp>::channels; } template inline size_t Mat_<_Tp>::stepT(int i) const { return step.p[i] / elemSize(); } template inline size_t Mat_<_Tp>::step1(int i) const { return step.p[i] / elemSize1(); } template inline Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright ) { return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); } template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const { return Mat_<_Tp>(*this, _rowRange, _colRange); } template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const { return Mat_<_Tp>(*this, roi); } template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const { return Mat_<_Tp>(*this, ranges); } template inline _Tp* Mat_<_Tp>::operator [](int y) { CV_DbgAssert( 0 <= y && y < rows ); return (_Tp*)(data + y*step.p[0]); } template inline const _Tp* Mat_<_Tp>::operator [](int y) const { CV_DbgAssert( 0 <= y && y < rows ); return (const _Tp*)(data + y*step.p[0]); } template inline _Tp& Mat_<_Tp>::operator ()(int i0, int i1) { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); CV_DbgAssert(type() == DataType<_Tp>::type); return ((_Tp*)(data + step.p[0] * i0))[i1]; } template inline const _Tp& Mat_<_Tp>::operator ()(int i0, int i1) const { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); CV_DbgAssert(type() == DataType<_Tp>::type); return ((const _Tp*)(data + step.p[0] * i0))[i1]; } template inline _Tp& Mat_<_Tp>::operator ()(Point pt) { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); CV_DbgAssert(type() == DataType<_Tp>::type); return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; } template inline const _Tp& Mat_<_Tp>::operator ()(Point pt) const { CV_DbgAssert(dims <= 2); CV_DbgAssert(data); CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); CV_DbgAssert(type() == DataType<_Tp>::type); return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; } template inline _Tp& Mat_<_Tp>::operator ()(const int* idx) { return Mat::at<_Tp>(idx); } template inline const _Tp& Mat_<_Tp>::operator ()(const int* idx) const { return Mat::at<_Tp>(idx); } template template inline _Tp& Mat_<_Tp>::operator ()(const Vec& idx) { return Mat::at<_Tp>(idx); } template template inline const _Tp& Mat_<_Tp>::operator ()(const Vec& idx) const { return Mat::at<_Tp>(idx); } template inline _Tp& Mat_<_Tp>::operator ()(int i0) { return this->at<_Tp>(i0); } template inline const _Tp& Mat_<_Tp>::operator ()(int i0) const { return this->at<_Tp>(i0); } template inline _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) { return this->at<_Tp>(i0, i1, i2); } template inline const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const { return this->at<_Tp>(i0, i1, i2); } template inline Mat_<_Tp>::operator std::vector<_Tp>() const { std::vector<_Tp> v; copyTo(v); return v; } template template inline Mat_<_Tp>::operator Vec::channel_type, n>() const { CV_Assert(n % DataType<_Tp>::channels == 0); #if defined _MSC_VER const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) return pMat->operator Vec::channel_type, n>(); #else return this->Mat::operator Vec::channel_type, n>(); #endif } template template inline Mat_<_Tp>::operator Matx::channel_type, m, n>() const { CV_Assert(n % DataType<_Tp>::channels == 0); #if defined _MSC_VER const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) Matx::channel_type, m, n> res = pMat->operator Matx::channel_type, m, n>(); return res; #else Matx::channel_type, m, n> res = this->Mat::operator Matx::channel_type, m, n>(); return res; #endif } template inline MatConstIterator_<_Tp> Mat_<_Tp>::begin() const { return Mat::begin<_Tp>(); } template inline MatConstIterator_<_Tp> Mat_<_Tp>::end() const { return Mat::end<_Tp>(); } template inline MatIterator_<_Tp> Mat_<_Tp>::begin() { return Mat::begin<_Tp>(); } template inline MatIterator_<_Tp> Mat_<_Tp>::end() { return Mat::end<_Tp>(); } template template inline void Mat_<_Tp>::forEach(const Functor& operation) { Mat::forEach<_Tp, Functor>(operation); } template template inline void Mat_<_Tp>::forEach(const Functor& operation) const { Mat::forEach<_Tp, Functor>(operation); } #ifdef CV_CXX_MOVE_SEMANTICS template inline Mat_<_Tp>::Mat_(Mat_&& m) : Mat(m) { } template inline Mat_<_Tp>& Mat_<_Tp>::operator = (Mat_&& m) { Mat::operator = (m); return *this; } template inline Mat_<_Tp>::Mat_(Mat&& m) : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; *this = m; } template inline Mat_<_Tp>& Mat_<_Tp>::operator = (Mat&& m) { if( DataType<_Tp>::type == m.type() ) { Mat::operator = ((Mat&&)m); return *this; } if( DataType<_Tp>::depth == m.depth() ) { Mat::operator = ((Mat&&)m.reshape(DataType<_Tp>::channels, m.dims, 0)); return *this; } CV_DbgAssert(DataType<_Tp>::channels == m.channels()); m.convertTo(*this, type()); return *this; } template inline Mat_<_Tp>::Mat_(MatExpr&& e) : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; *this = Mat(e); } #endif ///////////////////////////// SparseMat ///////////////////////////// inline SparseMat::SparseMat() : flags(MAGIC_VAL), hdr(0) {} inline SparseMat::SparseMat(int _dims, const int* _sizes, int _type) : flags(MAGIC_VAL), hdr(0) { create(_dims, _sizes, _type); } inline SparseMat::SparseMat(const SparseMat& m) : flags(m.flags), hdr(m.hdr) { addref(); } inline SparseMat::~SparseMat() { release(); } inline SparseMat& SparseMat::operator = (const SparseMat& m) { if( this != &m ) { if( m.hdr ) CV_XADD(&m.hdr->refcount, 1); release(); flags = m.flags; hdr = m.hdr; } return *this; } inline SparseMat& SparseMat::operator = (const Mat& m) { return (*this = SparseMat(m)); } inline SparseMat SparseMat::clone() const { SparseMat temp; this->copyTo(temp); return temp; } inline void SparseMat::assignTo( SparseMat& m, int _type ) const { if( _type < 0 ) m = *this; else convertTo(m, _type); } inline void SparseMat::addref() { if( hdr ) CV_XADD(&hdr->refcount, 1); } inline void SparseMat::release() { if( hdr && CV_XADD(&hdr->refcount, -1) == 1 ) delete hdr; hdr = 0; } inline size_t SparseMat::elemSize() const { return CV_ELEM_SIZE(flags); } inline size_t SparseMat::elemSize1() const { return CV_ELEM_SIZE1(flags); } inline int SparseMat::type() const { return CV_MAT_TYPE(flags); } inline int SparseMat::depth() const { return CV_MAT_DEPTH(flags); } inline int SparseMat::channels() const { return CV_MAT_CN(flags); } inline const int* SparseMat::size() const { return hdr ? hdr->size : 0; } inline int SparseMat::size(int i) const { if( hdr ) { CV_DbgAssert((unsigned)i < (unsigned)hdr->dims); return hdr->size[i]; } return 0; } inline int SparseMat::dims() const { return hdr ? hdr->dims : 0; } inline size_t SparseMat::nzcount() const { return hdr ? hdr->nodeCount : 0; } inline size_t SparseMat::hash(int i0) const { return (size_t)i0; } inline size_t SparseMat::hash(int i0, int i1) const { return (size_t)(unsigned)i0 * HASH_SCALE + (unsigned)i1; } inline size_t SparseMat::hash(int i0, int i1, int i2) const { return ((size_t)(unsigned)i0 * HASH_SCALE + (unsigned)i1) * HASH_SCALE + (unsigned)i2; } inline size_t SparseMat::hash(const int* idx) const { size_t h = (unsigned)idx[0]; if( !hdr ) return 0; int d = hdr->dims; for(int i = 1; i < d; i++ ) h = h * HASH_SCALE + (unsigned)idx[i]; return h; } template inline _Tp& SparseMat::ref(int i0, size_t* hashval) { return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval); } template inline _Tp& SparseMat::ref(int i0, int i1, size_t* hashval) { return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval); } template inline _Tp& SparseMat::ref(int i0, int i1, int i2, size_t* hashval) { return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, i2, true, hashval); } template inline _Tp& SparseMat::ref(const int* idx, size_t* hashval) { return *(_Tp*)((SparseMat*)this)->ptr(idx, true, hashval); } template inline _Tp SparseMat::value(int i0, size_t* hashval) const { const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); return p ? *p : _Tp(); } template inline _Tp SparseMat::value(int i0, int i1, size_t* hashval) const { const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); return p ? *p : _Tp(); } template inline _Tp SparseMat::value(int i0, int i1, int i2, size_t* hashval) const { const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); return p ? *p : _Tp(); } template inline _Tp SparseMat::value(const int* idx, size_t* hashval) const { const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); return p ? *p : _Tp(); } template inline const _Tp* SparseMat::find(int i0, size_t* hashval) const { return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); } template inline const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const { return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); } template inline const _Tp* SparseMat::find(int i0, int i1, int i2, size_t* hashval) const { return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); } template inline const _Tp* SparseMat::find(const int* idx, size_t* hashval) const { return (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); } template inline _Tp& SparseMat::value(Node* n) { return *(_Tp*)((uchar*)n + hdr->valueOffset); } template inline const _Tp& SparseMat::value(const Node* n) const { return *(const _Tp*)((const uchar*)n + hdr->valueOffset); } inline SparseMat::Node* SparseMat::node(size_t nidx) { return (Node*)(void*)&hdr->pool[nidx]; } inline const SparseMat::Node* SparseMat::node(size_t nidx) const { return (const Node*)(const void*)&hdr->pool[nidx]; } inline SparseMatIterator SparseMat::begin() { return SparseMatIterator(this); } inline SparseMatConstIterator SparseMat::begin() const { return SparseMatConstIterator(this); } inline SparseMatIterator SparseMat::end() { SparseMatIterator it(this); it.seekEnd(); return it; } inline SparseMatConstIterator SparseMat::end() const { SparseMatConstIterator it(this); it.seekEnd(); return it; } template inline SparseMatIterator_<_Tp> SparseMat::begin() { return SparseMatIterator_<_Tp>(this); } template inline SparseMatConstIterator_<_Tp> SparseMat::begin() const { return SparseMatConstIterator_<_Tp>(this); } template inline SparseMatIterator_<_Tp> SparseMat::end() { SparseMatIterator_<_Tp> it(this); it.seekEnd(); return it; } template inline SparseMatConstIterator_<_Tp> SparseMat::end() const { SparseMatConstIterator_<_Tp> it(this); it.seekEnd(); return it; } ///////////////////////////// SparseMat_ //////////////////////////// template inline SparseMat_<_Tp>::SparseMat_() { flags = MAGIC_VAL | DataType<_Tp>::type; } template inline SparseMat_<_Tp>::SparseMat_(int _dims, const int* _sizes) : SparseMat(_dims, _sizes, DataType<_Tp>::type) {} template inline SparseMat_<_Tp>::SparseMat_(const SparseMat& m) { if( m.type() == DataType<_Tp>::type ) *this = (const SparseMat_<_Tp>&)m; else m.convertTo(*this, DataType<_Tp>::type); } template inline SparseMat_<_Tp>::SparseMat_(const SparseMat_<_Tp>& m) { this->flags = m.flags; this->hdr = m.hdr; if( this->hdr ) CV_XADD(&this->hdr->refcount, 1); } template inline SparseMat_<_Tp>::SparseMat_(const Mat& m) { SparseMat sm(m); *this = sm; } template inline SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat_<_Tp>& m) { if( this != &m ) { if( m.hdr ) CV_XADD(&m.hdr->refcount, 1); release(); flags = m.flags; hdr = m.hdr; } return *this; } template inline SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat& m) { if( m.type() == DataType<_Tp>::type ) return (*this = (const SparseMat_<_Tp>&)m); m.convertTo(*this, DataType<_Tp>::type); return *this; } template inline SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const Mat& m) { return (*this = SparseMat(m)); } template inline SparseMat_<_Tp> SparseMat_<_Tp>::clone() const { SparseMat_<_Tp> m; this->copyTo(m); return m; } template inline void SparseMat_<_Tp>::create(int _dims, const int* _sizes) { SparseMat::create(_dims, _sizes, DataType<_Tp>::type); } template inline int SparseMat_<_Tp>::type() const { return DataType<_Tp>::type; } template inline int SparseMat_<_Tp>::depth() const { return DataType<_Tp>::depth; } template inline int SparseMat_<_Tp>::channels() const { return DataType<_Tp>::channels; } template inline _Tp& SparseMat_<_Tp>::ref(int i0, size_t* hashval) { return SparseMat::ref<_Tp>(i0, hashval); } template inline _Tp SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const { return SparseMat::value<_Tp>(i0, hashval); } template inline _Tp& SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval) { return SparseMat::ref<_Tp>(i0, i1, hashval); } template inline _Tp SparseMat_<_Tp>::operator()(int i0, int i1, size_t* hashval) const { return SparseMat::value<_Tp>(i0, i1, hashval); } template inline _Tp& SparseMat_<_Tp>::ref(int i0, int i1, int i2, size_t* hashval) { return SparseMat::ref<_Tp>(i0, i1, i2, hashval); } template inline _Tp SparseMat_<_Tp>::operator()(int i0, int i1, int i2, size_t* hashval) const { return SparseMat::value<_Tp>(i0, i1, i2, hashval); } template inline _Tp& SparseMat_<_Tp>::ref(const int* idx, size_t* hashval) { return SparseMat::ref<_Tp>(idx, hashval); } template inline _Tp SparseMat_<_Tp>::operator()(const int* idx, size_t* hashval) const { return SparseMat::value<_Tp>(idx, hashval); } template inline SparseMatIterator_<_Tp> SparseMat_<_Tp>::begin() { return SparseMatIterator_<_Tp>(this); } template inline SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begin() const { return SparseMatConstIterator_<_Tp>(this); } template inline SparseMatIterator_<_Tp> SparseMat_<_Tp>::end() { SparseMatIterator_<_Tp> it(this); it.seekEnd(); return it; } template inline SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const { SparseMatConstIterator_<_Tp> it(this); it.seekEnd(); return it; } ////////////////////////// MatConstIterator ///////////////////////// inline MatConstIterator::MatConstIterator() : m(0), elemSize(0), ptr(0), sliceStart(0), sliceEnd(0) {} inline MatConstIterator::MatConstIterator(const Mat* _m) : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) { if( m && m->isContinuous() ) { sliceStart = m->ptr(); sliceEnd = sliceStart + m->total()*elemSize; } seek((const int*)0); } inline MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col) : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) { CV_Assert(m && m->dims <= 2); if( m->isContinuous() ) { sliceStart = m->ptr(); sliceEnd = sliceStart + m->total()*elemSize; } int idx[] = {_row, _col}; seek(idx); } inline MatConstIterator::MatConstIterator(const Mat* _m, Point _pt) : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) { CV_Assert(m && m->dims <= 2); if( m->isContinuous() ) { sliceStart = m->ptr(); sliceEnd = sliceStart + m->total()*elemSize; } int idx[] = {_pt.y, _pt.x}; seek(idx); } inline MatConstIterator::MatConstIterator(const MatConstIterator& it) : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd) {} inline MatConstIterator& MatConstIterator::operator = (const MatConstIterator& it ) { m = it.m; elemSize = it.elemSize; ptr = it.ptr; sliceStart = it.sliceStart; sliceEnd = it.sliceEnd; return *this; } inline const uchar* MatConstIterator::operator *() const { return ptr; } inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs) { if( !m || ofs == 0 ) return *this; ptrdiff_t ofsb = ofs*elemSize; ptr += ofsb; if( ptr < sliceStart || sliceEnd <= ptr ) { ptr -= ofsb; seek(ofs, true); } return *this; } inline MatConstIterator& MatConstIterator::operator -= (ptrdiff_t ofs) { return (*this += -ofs); } inline MatConstIterator& MatConstIterator::operator --() { if( m && (ptr -= elemSize) < sliceStart ) { ptr += elemSize; seek(-1, true); } return *this; } inline MatConstIterator MatConstIterator::operator --(int) { MatConstIterator b = *this; *this += -1; return b; } inline MatConstIterator& MatConstIterator::operator ++() { if( m && (ptr += elemSize) >= sliceEnd ) { ptr -= elemSize; seek(1, true); } return *this; } inline MatConstIterator MatConstIterator::operator ++(int) { MatConstIterator b = *this; *this += 1; return b; } static inline bool operator == (const MatConstIterator& a, const MatConstIterator& b) { return a.m == b.m && a.ptr == b.ptr; } static inline bool operator != (const MatConstIterator& a, const MatConstIterator& b) { return !(a == b); } static inline bool operator < (const MatConstIterator& a, const MatConstIterator& b) { return a.ptr < b.ptr; } static inline bool operator > (const MatConstIterator& a, const MatConstIterator& b) { return a.ptr > b.ptr; } static inline bool operator <= (const MatConstIterator& a, const MatConstIterator& b) { return a.ptr <= b.ptr; } static inline bool operator >= (const MatConstIterator& a, const MatConstIterator& b) { return a.ptr >= b.ptr; } static inline ptrdiff_t operator - (const MatConstIterator& b, const MatConstIterator& a) { if( a.m != b.m ) return ((size_t)(-1) >> 1); if( a.sliceEnd == b.sliceEnd ) return (b.ptr - a.ptr)/b.elemSize; return b.lpos() - a.lpos(); } static inline MatConstIterator operator + (const MatConstIterator& a, ptrdiff_t ofs) { MatConstIterator b = a; return b += ofs; } static inline MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator& a) { MatConstIterator b = a; return b += ofs; } static inline MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs) { MatConstIterator b = a; return b += -ofs; } inline const uchar* MatConstIterator::operator [](ptrdiff_t i) const { return *(*this + i); } ///////////////////////// MatConstIterator_ ///////////////////////// template inline MatConstIterator_<_Tp>::MatConstIterator_() {} template inline MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m) : MatConstIterator(_m) {} template inline MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col) : MatConstIterator(_m, _row, _col) {} template inline MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, Point _pt) : MatConstIterator(_m, _pt) {} template inline MatConstIterator_<_Tp>::MatConstIterator_(const MatConstIterator_& it) : MatConstIterator(it) {} template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator = (const MatConstIterator_& it ) { MatConstIterator::operator = (it); return *this; } template inline _Tp MatConstIterator_<_Tp>::operator *() const { return *(_Tp*)(this->ptr); } template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator += (ptrdiff_t ofs) { MatConstIterator::operator += (ofs); return *this; } template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator -= (ptrdiff_t ofs) { return (*this += -ofs); } template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator --() { MatConstIterator::operator --(); return *this; } template inline MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator --(int) { MatConstIterator_ b = *this; MatConstIterator::operator --(); return b; } template inline MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator ++() { MatConstIterator::operator ++(); return *this; } template inline MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator ++(int) { MatConstIterator_ b = *this; MatConstIterator::operator ++(); return b; } template inline Point MatConstIterator_<_Tp>::pos() const { if( !m ) return Point(); CV_DbgAssert( m->dims <= 2 ); if( m->isContinuous() ) { ptrdiff_t ofs = (const _Tp*)ptr - (const _Tp*)m->data; int y = (int)(ofs / m->cols); int x = (int)(ofs - (ptrdiff_t)y * m->cols); return Point(x, y); } else { ptrdiff_t ofs = (uchar*)ptr - m->data; int y = (int)(ofs / m->step); int x = (int)((ofs - y * m->step)/sizeof(_Tp)); return Point(x, y); } } template static inline bool operator == (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) { return a.m == b.m && a.ptr == b.ptr; } template static inline bool operator != (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) { return a.m != b.m || a.ptr != b.ptr; } template static inline MatConstIterator_<_Tp> operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) { MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatConstIterator_<_Tp>&)t; } template static inline MatConstIterator_<_Tp> operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a) { MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatConstIterator_<_Tp>&)t; } template static inline MatConstIterator_<_Tp> operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) { MatConstIterator t = (const MatConstIterator&)a - ofs; return (MatConstIterator_<_Tp>&)t; } template inline _Tp MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const { return *(_Tp*)MatConstIterator::operator [](i); } //////////////////////////// MatIterator_ /////////////////////////// template inline MatIterator_<_Tp>::MatIterator_() : MatConstIterator_<_Tp>() {} template inline MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m) : MatConstIterator_<_Tp>(_m) {} template inline MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int _row, int _col) : MatConstIterator_<_Tp>(_m, _row, _col) {} template inline MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, Point _pt) : MatConstIterator_<_Tp>(_m, _pt) {} template inline MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, const int* _idx) : MatConstIterator_<_Tp>(_m, _idx) {} template inline MatIterator_<_Tp>::MatIterator_(const MatIterator_& it) : MatConstIterator_<_Tp>(it) {} template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator = (const MatIterator_<_Tp>& it ) { MatConstIterator::operator = (it); return *this; } template inline _Tp& MatIterator_<_Tp>::operator *() const { return *(_Tp*)(this->ptr); } template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator += (ptrdiff_t ofs) { MatConstIterator::operator += (ofs); return *this; } template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator -= (ptrdiff_t ofs) { MatConstIterator::operator += (-ofs); return *this; } template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator --() { MatConstIterator::operator --(); return *this; } template inline MatIterator_<_Tp> MatIterator_<_Tp>::operator --(int) { MatIterator_ b = *this; MatConstIterator::operator --(); return b; } template inline MatIterator_<_Tp>& MatIterator_<_Tp>::operator ++() { MatConstIterator::operator ++(); return *this; } template inline MatIterator_<_Tp> MatIterator_<_Tp>::operator ++(int) { MatIterator_ b = *this; MatConstIterator::operator ++(); return b; } template inline _Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const { return *(*this + i); } template static inline bool operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) { return a.m == b.m && a.ptr == b.ptr; } template static inline bool operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) { return a.m != b.m || a.ptr != b.ptr; } template static inline MatIterator_<_Tp> operator + (const MatIterator_<_Tp>& a, ptrdiff_t ofs) { MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatIterator_<_Tp>&)t; } template static inline MatIterator_<_Tp> operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a) { MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatIterator_<_Tp>&)t; } template static inline MatIterator_<_Tp> operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs) { MatConstIterator t = (const MatConstIterator&)a - ofs; return (MatIterator_<_Tp>&)t; } /////////////////////// SparseMatConstIterator ////////////////////// inline SparseMatConstIterator::SparseMatConstIterator() : m(0), hashidx(0), ptr(0) {} inline SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterator& it) : m(it.m), hashidx(it.hashidx), ptr(it.ptr) {} inline SparseMatConstIterator& SparseMatConstIterator::operator = (const SparseMatConstIterator& it) { if( this != &it ) { m = it.m; hashidx = it.hashidx; ptr = it.ptr; } return *this; } template inline const _Tp& SparseMatConstIterator::value() const { return *(const _Tp*)ptr; } inline const SparseMat::Node* SparseMatConstIterator::node() const { return (ptr && m && m->hdr) ? (const SparseMat::Node*)(const void*)(ptr - m->hdr->valueOffset) : 0; } inline SparseMatConstIterator SparseMatConstIterator::operator ++(int) { SparseMatConstIterator it = *this; ++*this; return it; } inline void SparseMatConstIterator::seekEnd() { if( m && m->hdr ) { hashidx = m->hdr->hashtab.size(); ptr = 0; } } static inline bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) { return it1.m == it2.m && it1.ptr == it2.ptr; } static inline bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) { return !(it1 == it2); } ///////////////////////// SparseMatIterator ///////////////////////// inline SparseMatIterator::SparseMatIterator() {} inline SparseMatIterator::SparseMatIterator(SparseMat* _m) : SparseMatConstIterator(_m) {} inline SparseMatIterator::SparseMatIterator(const SparseMatIterator& it) : SparseMatConstIterator(it) {} inline SparseMatIterator& SparseMatIterator::operator = (const SparseMatIterator& it) { (SparseMatConstIterator&)*this = it; return *this; } template inline _Tp& SparseMatIterator::value() const { return *(_Tp*)ptr; } inline SparseMat::Node* SparseMatIterator::node() const { return (SparseMat::Node*)SparseMatConstIterator::node(); } inline SparseMatIterator& SparseMatIterator::operator ++() { SparseMatConstIterator::operator ++(); return *this; } inline SparseMatIterator SparseMatIterator::operator ++(int) { SparseMatIterator it = *this; ++*this; return it; } ////////////////////// SparseMatConstIterator_ ////////////////////// template inline SparseMatConstIterator_<_Tp>::SparseMatConstIterator_() {} template inline SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat_<_Tp>* _m) : SparseMatConstIterator(_m) {} template inline SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat* _m) : SparseMatConstIterator(_m) { CV_Assert( _m->type() == DataType<_Tp>::type ); } template inline SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterator_<_Tp>& it) : SparseMatConstIterator(it) {} template inline SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it) { return reinterpret_cast&> (*reinterpret_cast(this) = reinterpret_cast(it)); } template inline const _Tp& SparseMatConstIterator_<_Tp>::operator *() const { return *(const _Tp*)this->ptr; } template inline SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator ++() { SparseMatConstIterator::operator ++(); return *this; } template inline SparseMatConstIterator_<_Tp> SparseMatConstIterator_<_Tp>::operator ++(int) { SparseMatConstIterator_<_Tp> it = *this; SparseMatConstIterator::operator ++(); return it; } ///////////////////////// SparseMatIterator_ //////////////////////// template inline SparseMatIterator_<_Tp>::SparseMatIterator_() {} template inline SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat_<_Tp>* _m) : SparseMatConstIterator_<_Tp>(_m) {} template inline SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat* _m) : SparseMatConstIterator_<_Tp>(_m) {} template inline SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it) : SparseMatConstIterator_<_Tp>(it) {} template inline SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it) { return reinterpret_cast&> (*reinterpret_cast(this) = reinterpret_cast(it)); } template inline _Tp& SparseMatIterator_<_Tp>::operator *() const { return *(_Tp*)this->ptr; } template inline SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator ++() { SparseMatConstIterator::operator ++(); return *this; } template inline SparseMatIterator_<_Tp> SparseMatIterator_<_Tp>::operator ++(int) { SparseMatIterator_<_Tp> it = *this; SparseMatConstIterator::operator ++(); return it; } //////////////////////// MatCommaInitializer_ /////////////////////// template inline MatCommaInitializer_<_Tp>::MatCommaInitializer_(Mat_<_Tp>* _m) : it(_m) {} template template inline MatCommaInitializer_<_Tp>& MatCommaInitializer_<_Tp>::operator , (T2 v) { CV_DbgAssert( this->it < ((const Mat_<_Tp>*)this->it.m)->end() ); *this->it = _Tp(v); ++this->it; return *this; } template inline MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() const { CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); return Mat_<_Tp>(*this->it.m); } template static inline MatCommaInitializer_<_Tp> operator << (const Mat_<_Tp>& m, T2 val) { MatCommaInitializer_<_Tp> commaInitializer((Mat_<_Tp>*)&m); return (commaInitializer, val); } ///////////////////////// Matrix Expressions //////////////////////// inline Mat& Mat::operator = (const MatExpr& e) { e.op->assign(e, *this); return *this; } template inline Mat_<_Tp>::Mat_(const MatExpr& e) { e.op->assign(e, *this, DataType<_Tp>::type); } template inline Mat_<_Tp>& Mat_<_Tp>::operator = (const MatExpr& e) { e.op->assign(e, *this, DataType<_Tp>::type); return *this; } template inline MatExpr Mat_<_Tp>::zeros(int rows, int cols) { return Mat::zeros(rows, cols, DataType<_Tp>::type); } template inline MatExpr Mat_<_Tp>::zeros(Size sz) { return Mat::zeros(sz, DataType<_Tp>::type); } template inline MatExpr Mat_<_Tp>::ones(int rows, int cols) { return Mat::ones(rows, cols, DataType<_Tp>::type); } template inline MatExpr Mat_<_Tp>::ones(Size sz) { return Mat::ones(sz, DataType<_Tp>::type); } template inline MatExpr Mat_<_Tp>::eye(int rows, int cols) { return Mat::eye(rows, cols, DataType<_Tp>::type); } template inline MatExpr Mat_<_Tp>::eye(Size sz) { return Mat::eye(sz, DataType<_Tp>::type); } inline MatExpr::MatExpr() : op(0), flags(0), a(Mat()), b(Mat()), c(Mat()), alpha(0), beta(0), s() {} inline MatExpr::MatExpr(const MatOp* _op, int _flags, const Mat& _a, const Mat& _b, const Mat& _c, double _alpha, double _beta, const Scalar& _s) : op(_op), flags(_flags), a(_a), b(_b), c(_c), alpha(_alpha), beta(_beta), s(_s) {} inline MatExpr::operator Mat() const { Mat m; op->assign(*this, m); return m; } template inline MatExpr::operator Mat_<_Tp>() const { Mat_<_Tp> m; op->assign(*this, m, DataType<_Tp>::type); return m; } template static inline MatExpr min(const Mat_<_Tp>& a, const Mat_<_Tp>& b) { return cv::min((const Mat&)a, (const Mat&)b); } template static inline MatExpr min(const Mat_<_Tp>& a, double s) { return cv::min((const Mat&)a, s); } template static inline MatExpr min(double s, const Mat_<_Tp>& a) { return cv::min((const Mat&)a, s); } template static inline MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b) { return cv::max((const Mat&)a, (const Mat&)b); } template static inline MatExpr max(const Mat_<_Tp>& a, double s) { return cv::max((const Mat&)a, s); } template static inline MatExpr max(double s, const Mat_<_Tp>& a) { return cv::max((const Mat&)a, s); } template static inline MatExpr abs(const Mat_<_Tp>& m) { return cv::abs((const Mat&)m); } static inline Mat& operator += (Mat& a, const MatExpr& b) { b.op->augAssignAdd(b, a); return a; } static inline const Mat& operator += (const Mat& a, const MatExpr& b) { b.op->augAssignAdd(b, (Mat&)a); return a; } template static inline Mat_<_Tp>& operator += (Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignAdd(b, a); return a; } template static inline const Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignAdd(b, (Mat&)a); return a; } static inline Mat& operator -= (Mat& a, const MatExpr& b) { b.op->augAssignSubtract(b, a); return a; } static inline const Mat& operator -= (const Mat& a, const MatExpr& b) { b.op->augAssignSubtract(b, (Mat&)a); return a; } template static inline Mat_<_Tp>& operator -= (Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignSubtract(b, a); return a; } template static inline const Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignSubtract(b, (Mat&)a); return a; } static inline Mat& operator *= (Mat& a, const MatExpr& b) { b.op->augAssignMultiply(b, a); return a; } static inline const Mat& operator *= (const Mat& a, const MatExpr& b) { b.op->augAssignMultiply(b, (Mat&)a); return a; } template static inline Mat_<_Tp>& operator *= (Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignMultiply(b, a); return a; } template static inline const Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignMultiply(b, (Mat&)a); return a; } static inline Mat& operator /= (Mat& a, const MatExpr& b) { b.op->augAssignDivide(b, a); return a; } static inline const Mat& operator /= (const Mat& a, const MatExpr& b) { b.op->augAssignDivide(b, (Mat&)a); return a; } template static inline Mat_<_Tp>& operator /= (Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignDivide(b, a); return a; } template static inline const Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignDivide(b, (Mat&)a); return a; } //////////////////////////////// UMat //////////////////////////////// inline UMat::UMat(UMatUsageFlags _usageFlags) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows) {} inline UMat::UMat(int _rows, int _cols, int _type, UMatUsageFlags _usageFlags) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows) { create(_rows, _cols, _type); } inline UMat::UMat(int _rows, int _cols, int _type, const Scalar& _s, UMatUsageFlags _usageFlags) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows) { create(_rows, _cols, _type); *this = _s; } inline UMat::UMat(Size _sz, int _type, UMatUsageFlags _usageFlags) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows) { create( _sz.height, _sz.width, _type ); } inline UMat::UMat(Size _sz, int _type, const Scalar& _s, UMatUsageFlags _usageFlags) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows) { create(_sz.height, _sz.width, _type); *this = _s; } inline UMat::UMat(int _dims, const int* _sz, int _type, UMatUsageFlags _usageFlags) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows) { create(_dims, _sz, _type); } inline UMat::UMat(int _dims, const int* _sz, int _type, const Scalar& _s, UMatUsageFlags _usageFlags) : flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows) { create(_dims, _sz, _type); *this = _s; } inline UMat::UMat(const UMat& m) : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), allocator(m.allocator), usageFlags(m.usageFlags), u(m.u), offset(m.offset), size(&rows) { addref(); if( m.dims <= 2 ) { step[0] = m.step[0]; step[1] = m.step[1]; } else { dims = 0; copySize(m); } } template inline UMat::UMat(const std::vector<_Tp>& vec, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), cols(1), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows) { if(vec.empty()) return; if( !copyData ) { // !!!TODO!!! CV_Error(Error::StsNotImplemented, ""); } else Mat((int)vec.size(), 1, DataType<_Tp>::type, (uchar*)&vec[0]).copyTo(*this); } inline UMat& UMat::operator = (const UMat& m) { if( this != &m ) { const_cast(m).addref(); release(); flags = m.flags; if( dims <= 2 && m.dims <= 2 ) { dims = m.dims; rows = m.rows; cols = m.cols; step[0] = m.step[0]; step[1] = m.step[1]; } else copySize(m); allocator = m.allocator; if (usageFlags == USAGE_DEFAULT) usageFlags = m.usageFlags; u = m.u; offset = m.offset; } return *this; } inline UMat UMat::row(int y) const { return UMat(*this, Range(y, y + 1), Range::all()); } inline UMat UMat::col(int x) const { return UMat(*this, Range::all(), Range(x, x + 1)); } inline UMat UMat::rowRange(int startrow, int endrow) const { return UMat(*this, Range(startrow, endrow), Range::all()); } inline UMat UMat::rowRange(const Range& r) const { return UMat(*this, r, Range::all()); } inline UMat UMat::colRange(int startcol, int endcol) const { return UMat(*this, Range::all(), Range(startcol, endcol)); } inline UMat UMat::colRange(const Range& r) const { return UMat(*this, Range::all(), r); } inline UMat UMat::clone() const { UMat m; copyTo(m); return m; } inline void UMat::assignTo( UMat& m, int _type ) const { if( _type < 0 ) m = *this; else convertTo(m, _type); } inline void UMat::create(int _rows, int _cols, int _type, UMatUsageFlags _usageFlags) { _type &= TYPE_MASK; if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && u ) return; int sz[] = {_rows, _cols}; create(2, sz, _type, _usageFlags); } inline void UMat::create(Size _sz, int _type, UMatUsageFlags _usageFlags) { create(_sz.height, _sz.width, _type, _usageFlags); } inline void UMat::addref() { if( u ) CV_XADD(&(u->urefcount), 1); } inline void UMat::release() { if( u && CV_XADD(&(u->urefcount), -1) == 1 ) deallocate(); for(int i = 0; i < dims; i++) size.p[i] = 0; u = 0; } inline UMat UMat::operator()( Range _rowRange, Range _colRange ) const { return UMat(*this, _rowRange, _colRange); } inline UMat UMat::operator()( const Rect& roi ) const { return UMat(*this, roi); } inline UMat UMat::operator()(const Range* ranges) const { return UMat(*this, ranges); } inline bool UMat::isContinuous() const { return (flags & CONTINUOUS_FLAG) != 0; } inline bool UMat::isSubmatrix() const { return (flags & SUBMATRIX_FLAG) != 0; } inline size_t UMat::elemSize() const { return dims > 0 ? step.p[dims - 1] : 0; } inline size_t UMat::elemSize1() const { return CV_ELEM_SIZE1(flags); } inline int UMat::type() const { return CV_MAT_TYPE(flags); } inline int UMat::depth() const { return CV_MAT_DEPTH(flags); } inline int UMat::channels() const { return CV_MAT_CN(flags); } inline size_t UMat::step1(int i) const { return step.p[i] / elemSize1(); } inline bool UMat::empty() const { return u == 0 || total() == 0; } inline size_t UMat::total() const { if( dims <= 2 ) return (size_t)rows * cols; size_t p = 1; for( int i = 0; i < dims; i++ ) p *= size[i]; return p; } #ifdef CV_CXX_MOVE_SEMANTICS inline UMat::UMat(UMat&& m) : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), allocator(m.allocator), usageFlags(m.usageFlags), u(m.u), offset(m.offset), size(&rows) { if (m.dims <= 2) // move new step/size info { step[0] = m.step[0]; step[1] = m.step[1]; } else { CV_DbgAssert(m.step.p != m.step.buf); step.p = m.step.p; size.p = m.size.p; m.step.p = m.step.buf; m.size.p = &m.rows; } m.flags = MAGIC_VAL; m.dims = m.rows = m.cols = 0; m.allocator = NULL; m.u = NULL; m.offset = 0; } inline UMat& UMat::operator = (UMat&& m) { release(); flags = m.flags; dims = m.dims; rows = m.rows; cols = m.cols; allocator = m.allocator; usageFlags = m.usageFlags; u = m.u; offset = m.offset; if (step.p != step.buf) // release self step/size { fastFree(step.p); step.p = step.buf; size.p = &rows; } if (m.dims <= 2) // move new step/size info { step[0] = m.step[0]; step[1] = m.step[1]; } else { CV_DbgAssert(m.step.p != m.step.buf); step.p = m.step.p; size.p = m.size.p; m.step.p = m.step.buf; m.size.p = &m.rows; } m.flags = MAGIC_VAL; m.dims = m.rows = m.cols = 0; m.allocator = NULL; m.u = NULL; m.offset = 0; return *this; } #endif inline bool UMatData::hostCopyObsolete() const { return (flags & HOST_COPY_OBSOLETE) != 0; } inline bool UMatData::deviceCopyObsolete() const { return (flags & DEVICE_COPY_OBSOLETE) != 0; } inline bool UMatData::deviceMemMapped() const { return (flags & DEVICE_MEM_MAPPED) != 0; } inline bool UMatData::copyOnMap() const { return (flags & COPY_ON_MAP) != 0; } inline bool UMatData::tempUMat() const { return (flags & TEMP_UMAT) != 0; } inline bool UMatData::tempCopiedUMat() const { return (flags & TEMP_COPIED_UMAT) == TEMP_COPIED_UMAT; } inline void UMatData::markDeviceMemMapped(bool flag) { if(flag) flags |= DEVICE_MEM_MAPPED; else flags &= ~DEVICE_MEM_MAPPED; } inline void UMatData::markHostCopyObsolete(bool flag) { if(flag) flags |= HOST_COPY_OBSOLETE; else flags &= ~HOST_COPY_OBSOLETE; } inline void UMatData::markDeviceCopyObsolete(bool flag) { if(flag) flags |= DEVICE_COPY_OBSOLETE; else flags &= ~DEVICE_COPY_OBSOLETE; } inline UMatDataAutoLock::UMatDataAutoLock(UMatData* _u) : u(_u) { u->lock(); } inline UMatDataAutoLock::~UMatDataAutoLock() { u->unlock(); } //! @endcond } //cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/matx.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_MATX_HPP__ #define __OPENCV_CORE_MATX_HPP__ #ifndef __cplusplus # error matx.hpp header must be compiled as C++ #endif #include "opencv2/core/cvdef.h" #include "opencv2/core/base.hpp" #include "opencv2/core/traits.hpp" #include "opencv2/core/saturate.hpp" namespace cv { //! @addtogroup core_basic //! @{ ////////////////////////////// Small Matrix /////////////////////////// //! @cond IGNORED struct CV_EXPORTS Matx_AddOp {}; struct CV_EXPORTS Matx_SubOp {}; struct CV_EXPORTS Matx_ScaleOp {}; struct CV_EXPORTS Matx_MulOp {}; struct CV_EXPORTS Matx_DivOp {}; struct CV_EXPORTS Matx_MatMulOp {}; struct CV_EXPORTS Matx_TOp {}; //! @endcond /** @brief Template class for small matrices whose type and size are known at compilation time If you need a more flexible type, use Mat . The elements of the matrix M are accessible using the M(i,j) notation. Most of the common matrix operations (see also @ref MatrixExpressions ) are available. To do an operation on Matx that is not implemented, you can easily convert the matrix to Mat and backwards: @code Matx33f m(1, 2, 3, 4, 5, 6, 7, 8, 9); cout << sum(Mat(m*m.t())) << endl; @endcode */ template class Matx { public: enum { depth = DataType<_Tp>::depth, rows = m, cols = n, channels = rows*cols, type = CV_MAKETYPE(depth, channels), shortdim = (m < n ? m : n) }; typedef _Tp value_type; typedef Matx<_Tp, m, n> mat_type; typedef Matx<_Tp, shortdim, 1> diag_type; //! default constructor Matx(); Matx(_Tp v0); //!< 1x1 matrix Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 1x10, 2x5 or 5x2 or 10x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13); //!< 1x14, 2x7, 7x2 or 14x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix explicit Matx(const _Tp* vals); //!< initialize from a plain array static Matx all(_Tp alpha); static Matx zeros(); static Matx ones(); static Matx eye(); static Matx diag(const diag_type& d); static Matx randu(_Tp a, _Tp b); static Matx randn(_Tp a, _Tp b); //! dot product computed with the default precision _Tp dot(const Matx<_Tp, m, n>& v) const; //! dot product computed in double-precision arithmetics double ddot(const Matx<_Tp, m, n>& v) const; //! conversion to another data type template operator Matx() const; //! change the matrix shape template Matx<_Tp, m1, n1> reshape() const; //! extract part of the matrix template Matx<_Tp, m1, n1> get_minor(int i, int j) const; //! extract the matrix row Matx<_Tp, 1, n> row(int i) const; //! extract the matrix column Matx<_Tp, m, 1> col(int i) const; //! extract the matrix diagonal diag_type diag() const; //! transpose the matrix Matx<_Tp, n, m> t() const; //! invert the matrix Matx<_Tp, n, m> inv(int method=DECOMP_LU, bool *p_is_ok = NULL) const; //! solve linear system template Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const; Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const; //! multiply two matrices element-wise Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const; //! divide two matrices element-wise Matx<_Tp, m, n> div(const Matx<_Tp, m, n>& a) const; //! element access const _Tp& operator ()(int i, int j) const; _Tp& operator ()(int i, int j); //! 1D element access const _Tp& operator ()(int i) const; _Tp& operator ()(int i); Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp); Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp); template Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp); Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp); Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp); template Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp); Matx(const Matx<_Tp, n, m>& a, Matx_TOp); _Tp val[m*n]; //< matrix elements }; typedef Matx Matx12f; typedef Matx Matx12d; typedef Matx Matx13f; typedef Matx Matx13d; typedef Matx Matx14f; typedef Matx Matx14d; typedef Matx Matx16f; typedef Matx Matx16d; typedef Matx Matx21f; typedef Matx Matx21d; typedef Matx Matx31f; typedef Matx Matx31d; typedef Matx Matx41f; typedef Matx Matx41d; typedef Matx Matx61f; typedef Matx Matx61d; typedef Matx Matx22f; typedef Matx Matx22d; typedef Matx Matx23f; typedef Matx Matx23d; typedef Matx Matx32f; typedef Matx Matx32d; typedef Matx Matx33f; typedef Matx Matx33d; typedef Matx Matx34f; typedef Matx Matx34d; typedef Matx Matx43f; typedef Matx Matx43d; typedef Matx Matx44f; typedef Matx Matx44d; typedef Matx Matx66f; typedef Matx Matx66d; /*! traits */ template class DataType< Matx<_Tp, m, n> > { public: typedef Matx<_Tp, m, n> value_type; typedef Matx::work_type, m, n> work_type; typedef _Tp channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = DataType::depth, channels = m * n, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; }; /** @brief Comma-separated Matrix Initializer */ template class MatxCommaInitializer { public: MatxCommaInitializer(Matx<_Tp, m, n>* _mtx); template MatxCommaInitializer<_Tp, m, n>& operator , (T2 val); Matx<_Tp, m, n> operator *() const; Matx<_Tp, m, n>* dst; int idx; }; /* Utility methods */ template static double determinant(const Matx<_Tp, m, m>& a); template static double trace(const Matx<_Tp, m, n>& a); template static double norm(const Matx<_Tp, m, n>& M); template static double norm(const Matx<_Tp, m, n>& M, int normType); /////////////////////// Vec (used as element of multi-channel images ///////////////////// /** @brief Template class for short numerical vectors, a partial case of Matx This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) on which you can perform basic arithmetical operations, access individual elements using [] operator etc. The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., which elements are dynamically allocated in the heap. The template takes 2 parameters: @tparam _Tp element type @tparam cn the number of elements In addition to the universal notation like Vec, you can use shorter aliases for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. It is possible to convert Vec\ to/from Point_, Vec\ to/from Point3_ , and Vec\ to CvScalar or Scalar_. Use operator[] to access the elements of Vec. All the expected vector operations are also implemented: - v1 = v2 + v3 - v1 = v2 - v3 - v1 = v2 \* scale - v1 = scale \* v2 - v1 = -v2 - v1 += v2 and other augmenting operations - v1 == v2, v1 != v2 - norm(v1) (euclidean norm) The Vec class is commonly used to describe pixel types of multi-channel arrays. See Mat for details. */ template class Vec : public Matx<_Tp, cn, 1> { public: typedef _Tp value_type; enum { depth = Matx<_Tp, cn, 1>::depth, channels = cn, type = CV_MAKETYPE(depth, channels) }; //! default constructor Vec(); Vec(_Tp v0); //!< 1-element vector constructor Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13); //!< 14-element vector constructor explicit Vec(const _Tp* values); Vec(const Vec<_Tp, cn>& v); static Vec all(_Tp alpha); //! per-element multiplication Vec mul(const Vec<_Tp, cn>& v) const; //! conjugation (makes sense for complex numbers and quaternions) Vec conj() const; /*! cross product of the two 3D vectors. For other dimensionalities the exception is raised */ Vec cross(const Vec& v) const; //! conversion to another data type template operator Vec() const; /*! element access */ const _Tp& operator [](int i) const; _Tp& operator[](int i); const _Tp& operator ()(int i) const; _Tp& operator ()(int i); Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp); Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp); template Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp); }; /** @name Shorter aliases for the most popular specializations of Vec @{ */ typedef Vec Vec2b; typedef Vec Vec3b; typedef Vec Vec4b; typedef Vec Vec2s; typedef Vec Vec3s; typedef Vec Vec4s; typedef Vec Vec2w; typedef Vec Vec3w; typedef Vec Vec4w; typedef Vec Vec2i; typedef Vec Vec3i; typedef Vec Vec4i; typedef Vec Vec6i; typedef Vec Vec8i; typedef Vec Vec2f; typedef Vec Vec3f; typedef Vec Vec4f; typedef Vec Vec6f; typedef Vec Vec2d; typedef Vec Vec3d; typedef Vec Vec4d; typedef Vec Vec6d; /** @} */ /*! traits */ template class DataType< Vec<_Tp, cn> > { public: typedef Vec<_Tp, cn> value_type; typedef Vec::work_type, cn> work_type; typedef _Tp channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = DataType::depth, channels = cn, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; }; /** @brief Comma-separated Vec Initializer */ template class VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1> { public: VecCommaInitializer(Vec<_Tp, m>* _vec); template VecCommaInitializer<_Tp, m>& operator , (T2 val); Vec<_Tp, m> operator *() const; }; template static Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v); //! @} core_basic //! @cond IGNORED ///////////////////////////////////// helper classes ///////////////////////////////////// namespace internal { template struct Matx_DetOp { double operator ()(const Matx<_Tp, m, m>& a) const { Matx<_Tp, m, m> temp = a; double p = LU(temp.val, m*sizeof(_Tp), m, 0, 0, 0); if( p == 0 ) return p; for( int i = 0; i < m; i++ ) p *= temp(i, i); return 1./p; } }; template struct Matx_DetOp<_Tp, 1> { double operator ()(const Matx<_Tp, 1, 1>& a) const { return a(0,0); } }; template struct Matx_DetOp<_Tp, 2> { double operator ()(const Matx<_Tp, 2, 2>& a) const { return a(0,0)*a(1,1) - a(0,1)*a(1,0); } }; template struct Matx_DetOp<_Tp, 3> { double operator ()(const Matx<_Tp, 3, 3>& a) const { return a(0,0)*(a(1,1)*a(2,2) - a(2,1)*a(1,2)) - a(0,1)*(a(1,0)*a(2,2) - a(2,0)*a(1,2)) + a(0,2)*(a(1,0)*a(2,1) - a(2,0)*a(1,1)); } }; template Vec<_Tp, 2> inline conjugate(const Vec<_Tp, 2>& v) { return Vec<_Tp, 2>(v[0], -v[1]); } template Vec<_Tp, 4> inline conjugate(const Vec<_Tp, 4>& v) { return Vec<_Tp, 4>(v[0], -v[1], -v[2], -v[3]); } } // internal ////////////////////////////////// Matx Implementation /////////////////////////////////// template inline Matx<_Tp, m, n>::Matx() { for(int i = 0; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0) { val[0] = v0; for(int i = 1; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1) { CV_StaticAssert(channels >= 2, "Matx should have at least 2 elements."); val[0] = v0; val[1] = v1; for(int i = 2; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2) { CV_StaticAssert(channels >= 3, "Matx should have at least 3 elements."); val[0] = v0; val[1] = v1; val[2] = v2; for(int i = 3; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3) { CV_StaticAssert(channels >= 4, "Matx should have at least 4 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; for(int i = 4; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) { CV_StaticAssert(channels >= 5, "Matx should have at least 5 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; for(int i = 5; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) { CV_StaticAssert(channels >= 6, "Matx should have at least 6 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; for(int i = 6; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) { CV_StaticAssert(channels >= 7, "Matx should have at least 7 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; val[6] = v6; for(int i = 7; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) { CV_StaticAssert(channels >= 8, "Matx should have at least 8 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; for(int i = 8; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) { CV_StaticAssert(channels >= 9, "Matx should have at least 9 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; val[8] = v8; for(int i = 9; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) { CV_StaticAssert(channels >= 10, "Matx should have at least 10 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; val[8] = v8; val[9] = v9; for(int i = 10; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11) { CV_StaticAssert(channels >= 12, "Matx should have at least 12 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; for(int i = 12; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) { CV_StaticAssert(channels == 14, "Matx should have at least 14 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; val[12] = v12; val[13] = v13; } template inline Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13, _Tp v14, _Tp v15) { CV_StaticAssert(channels >= 16, "Matx should have at least 16 elements."); val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; val[12] = v12; val[13] = v13; val[14] = v14; val[15] = v15; for(int i = 16; i < channels; i++) val[i] = _Tp(0); } template inline Matx<_Tp, m, n>::Matx(const _Tp* values) { for( int i = 0; i < channels; i++ ) val[i] = values[i]; } template inline Matx<_Tp, m, n> Matx<_Tp, m, n>::all(_Tp alpha) { Matx<_Tp, m, n> M; for( int i = 0; i < m*n; i++ ) M.val[i] = alpha; return M; } template inline Matx<_Tp,m,n> Matx<_Tp,m,n>::zeros() { return all(0); } template inline Matx<_Tp,m,n> Matx<_Tp,m,n>::ones() { return all(1); } template inline Matx<_Tp,m,n> Matx<_Tp,m,n>::eye() { Matx<_Tp,m,n> M; for(int i = 0; i < shortdim; i++) M(i,i) = 1; return M; } template inline _Tp Matx<_Tp, m, n>::dot(const Matx<_Tp, m, n>& M) const { _Tp s = 0; for( int i = 0; i < channels; i++ ) s += val[i]*M.val[i]; return s; } template inline double Matx<_Tp, m, n>::ddot(const Matx<_Tp, m, n>& M) const { double s = 0; for( int i = 0; i < channels; i++ ) s += (double)val[i]*M.val[i]; return s; } template inline Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const typename Matx<_Tp,m,n>::diag_type& d) { Matx<_Tp,m,n> M; for(int i = 0; i < shortdim; i++) M(i,i) = d(i, 0); return M; } template template inline Matx<_Tp, m, n>::operator Matx() const { Matx M; for( int i = 0; i < m*n; i++ ) M.val[i] = saturate_cast(val[i]); return M; } template template inline Matx<_Tp, m1, n1> Matx<_Tp, m, n>::reshape() const { CV_StaticAssert(m1*n1 == m*n, "Input and destnarion matrices must have the same number of elements"); return (const Matx<_Tp, m1, n1>&)*this; } template template inline Matx<_Tp, m1, n1> Matx<_Tp, m, n>::get_minor(int i, int j) const { CV_DbgAssert(0 <= i && i+m1 <= m && 0 <= j && j+n1 <= n); Matx<_Tp, m1, n1> s; for( int di = 0; di < m1; di++ ) for( int dj = 0; dj < n1; dj++ ) s(di, dj) = (*this)(i+di, j+dj); return s; } template inline Matx<_Tp, 1, n> Matx<_Tp, m, n>::row(int i) const { CV_DbgAssert((unsigned)i < (unsigned)m); return Matx<_Tp, 1, n>(&val[i*n]); } template inline Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const { CV_DbgAssert((unsigned)j < (unsigned)n); Matx<_Tp, m, 1> v; for( int i = 0; i < m; i++ ) v.val[i] = val[i*n + j]; return v; } template inline typename Matx<_Tp, m, n>::diag_type Matx<_Tp, m, n>::diag() const { diag_type d; for( int i = 0; i < shortdim; i++ ) d.val[i] = val[i*n + i]; return d; } template inline const _Tp& Matx<_Tp, m, n>::operator()(int i, int j) const { CV_DbgAssert( (unsigned)i < (unsigned)m && (unsigned)j < (unsigned)n ); return this->val[i*n + j]; } template inline _Tp& Matx<_Tp, m, n>::operator ()(int i, int j) { CV_DbgAssert( (unsigned)i < (unsigned)m && (unsigned)j < (unsigned)n ); return val[i*n + j]; } template inline const _Tp& Matx<_Tp, m, n>::operator ()(int i) const { CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); return val[i]; } template inline _Tp& Matx<_Tp, m, n>::operator ()(int i) { CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); return val[i]; } template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp) { for( int i = 0; i < channels; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] + b.val[i]); } template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp) { for( int i = 0; i < channels; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] - b.val[i]); } template template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp) { for( int i = 0; i < channels; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] * alpha); } template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp) { for( int i = 0; i < channels; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] * b.val[i]); } template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp) { for( int i = 0; i < channels; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] / b.val[i]); } template template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp) { for( int i = 0; i < m; i++ ) for( int j = 0; j < n; j++ ) { _Tp s = 0; for( int k = 0; k < l; k++ ) s += a(i, k) * b(k, j); val[i*n + j] = s; } } template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) { for( int i = 0; i < m; i++ ) for( int j = 0; j < n; j++ ) val[i*n + j] = a(j, i); } template inline Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const { return Matx<_Tp, m, n>(*this, a, Matx_MulOp()); } template inline Matx<_Tp, m, n> Matx<_Tp, m, n>::div(const Matx<_Tp, m, n>& a) const { return Matx<_Tp, m, n>(*this, a, Matx_DivOp()); } template inline Matx<_Tp, n, m> Matx<_Tp, m, n>::t() const { return Matx<_Tp, n, m>(*this, Matx_TOp()); } template inline Vec<_Tp, n> Matx<_Tp, m, n>::solve(const Vec<_Tp, m>& rhs, int method) const { Matx<_Tp, n, 1> x = solve((const Matx<_Tp, m, 1>&)(rhs), method); return (Vec<_Tp, n>&)(x); } template static inline double determinant(const Matx<_Tp, m, m>& a) { return cv::internal::Matx_DetOp<_Tp, m>()(a); } template static inline double trace(const Matx<_Tp, m, n>& a) { _Tp s = 0; for( int i = 0; i < std::min(m, n); i++ ) s += a(i,i); return s; } template static inline double norm(const Matx<_Tp, m, n>& M) { return std::sqrt(normL2Sqr<_Tp, double>(M.val, m*n)); } template static inline double norm(const Matx<_Tp, m, n>& M, int normType) { switch(normType) { case NORM_INF: return (double)normInf<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); case NORM_L1: return (double)normL1<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); case NORM_L2SQR: return (double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); default: case NORM_L2: return std::sqrt((double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n)); } } //////////////////////////////// matx comma initializer ////////////////////////////////// template static inline MatxCommaInitializer<_Tp, m, n> operator << (const Matx<_Tp, m, n>& mtx, _T2 val) { MatxCommaInitializer<_Tp, m, n> commaInitializer((Matx<_Tp, m, n>*)&mtx); return (commaInitializer, val); } template inline MatxCommaInitializer<_Tp, m, n>::MatxCommaInitializer(Matx<_Tp, m, n>* _mtx) : dst(_mtx), idx(0) {} template template inline MatxCommaInitializer<_Tp, m, n>& MatxCommaInitializer<_Tp, m, n>::operator , (_T2 value) { CV_DbgAssert( idx < m*n ); dst->val[idx++] = saturate_cast<_Tp>(value); return *this; } template inline Matx<_Tp, m, n> MatxCommaInitializer<_Tp, m, n>::operator *() const { CV_DbgAssert( idx == n*m ); return *dst; } /////////////////////////////////// Vec Implementation /////////////////////////////////// template inline Vec<_Tp, cn>::Vec() {} template inline Vec<_Tp, cn>::Vec(_Tp v0) : Matx<_Tp, cn, 1>(v0) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1) : Matx<_Tp, cn, 1>(v0, v1) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2) : Matx<_Tp, cn, 1>(v0, v1, v2) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3) : Matx<_Tp, cn, 1>(v0, v1, v2, v3) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {} template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) {} template inline Vec<_Tp, cn>::Vec(const _Tp* values) : Matx<_Tp, cn, 1>(values) {} template inline Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m) : Matx<_Tp, cn, 1>(m.val) {} template inline Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp op) : Matx<_Tp, cn, 1>(a, b, op) {} template inline Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp op) : Matx<_Tp, cn, 1>(a, b, op) {} template template inline Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp op) : Matx<_Tp, cn, 1>(a, alpha, op) {} template inline Vec<_Tp, cn> Vec<_Tp, cn>::all(_Tp alpha) { Vec v; for( int i = 0; i < cn; i++ ) v.val[i] = alpha; return v; } template inline Vec<_Tp, cn> Vec<_Tp, cn>::mul(const Vec<_Tp, cn>& v) const { Vec<_Tp, cn> w; for( int i = 0; i < cn; i++ ) w.val[i] = saturate_cast<_Tp>(this->val[i]*v.val[i]); return w; } template<> inline Vec Vec::conj() const { return cv::internal::conjugate(*this); } template<> inline Vec Vec::conj() const { return cv::internal::conjugate(*this); } template<> inline Vec Vec::conj() const { return cv::internal::conjugate(*this); } template<> inline Vec Vec::conj() const { return cv::internal::conjugate(*this); } template inline Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const { CV_StaticAssert(cn == 3, "for arbitrary-size vector there is no cross-product defined"); return Vec<_Tp, cn>(); } template<> inline Vec Vec::cross(const Vec& v) const { return Vec(val[1]*v.val[2] - val[2]*v.val[1], val[2]*v.val[0] - val[0]*v.val[2], val[0]*v.val[1] - val[1]*v.val[0]); } template<> inline Vec Vec::cross(const Vec& v) const { return Vec(val[1]*v.val[2] - val[2]*v.val[1], val[2]*v.val[0] - val[0]*v.val[2], val[0]*v.val[1] - val[1]*v.val[0]); } template template inline Vec<_Tp, cn>::operator Vec() const { Vec v; for( int i = 0; i < cn; i++ ) v.val[i] = saturate_cast(this->val[i]); return v; } template inline const _Tp& Vec<_Tp, cn>::operator [](int i) const { CV_DbgAssert( (unsigned)i < (unsigned)cn ); return this->val[i]; } template inline _Tp& Vec<_Tp, cn>::operator [](int i) { CV_DbgAssert( (unsigned)i < (unsigned)cn ); return this->val[i]; } template inline const _Tp& Vec<_Tp, cn>::operator ()(int i) const { CV_DbgAssert( (unsigned)i < (unsigned)cn ); return this->val[i]; } template inline _Tp& Vec<_Tp, cn>::operator ()(int i) { CV_DbgAssert( (unsigned)i < (unsigned)cn ); return this->val[i]; } template inline Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v) { double nv = norm(v); return v * (nv ? 1./nv : 0.); } //////////////////////////////// matx comma initializer ////////////////////////////////// template static inline VecCommaInitializer<_Tp, cn> operator << (const Vec<_Tp, cn>& vec, _T2 val) { VecCommaInitializer<_Tp, cn> commaInitializer((Vec<_Tp, cn>*)&vec); return (commaInitializer, val); } template inline VecCommaInitializer<_Tp, cn>::VecCommaInitializer(Vec<_Tp, cn>* _vec) : MatxCommaInitializer<_Tp, cn, 1>(_vec) {} template template inline VecCommaInitializer<_Tp, cn>& VecCommaInitializer<_Tp, cn>::operator , (_T2 value) { CV_DbgAssert( this->idx < cn ); this->dst->val[this->idx++] = saturate_cast<_Tp>(value); return *this; } template inline Vec<_Tp, cn> VecCommaInitializer<_Tp, cn>::operator *() const { CV_DbgAssert( this->idx == cn ); return *this->dst; } //! @endcond ///////////////////////////// Matx out-of-class operators //////////////////////////////// //! @relates cv::Matx //! @{ template static inline Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); return a; } template static inline Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); return a; } template static inline Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { return Matx<_Tp, m, n>(a, b, Matx_AddOp()); } template static inline Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { return Matx<_Tp, m, n>(a, b, Matx_SubOp()); } template static inline Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); return a; } template static inline Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); return a; } template static inline Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); return a; } template static inline Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); } template static inline Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); } template static inline Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); } template static inline Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); } template static inline Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); } template static inline Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); } template static inline Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a) { return Matx<_Tp, m, n>(a, -1, Matx_ScaleOp()); } template static inline Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b) { return Matx<_Tp, m, n>(a, b, Matx_MatMulOp()); } template static inline Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b) { Matx<_Tp, m, 1> c(a, b, Matx_MatMulOp()); return (const Vec<_Tp, m>&)(c); } template static inline bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { for( int i = 0; i < m*n; i++ ) if( a.val[i] != b.val[i] ) return false; return true; } template static inline bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { return !(a == b); } //! @} ////////////////////////////// Vec out-of-class operators //////////////////////////////// //! @relates cv::Vec //! @{ template static inline Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) { for( int i = 0; i < cn; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); return a; } template static inline Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) { for( int i = 0; i < cn; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); return a; } template static inline Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) { return Vec<_Tp, cn>(a, b, Matx_AddOp()); } template static inline Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) { return Vec<_Tp, cn>(a, b, Matx_SubOp()); } template static inline Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha) { for( int i = 0; i < cn; i++ ) a[i] = saturate_cast<_Tp>(a[i]*alpha); return a; } template static inline Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha) { for( int i = 0; i < cn; i++ ) a[i] = saturate_cast<_Tp>(a[i]*alpha); return a; } template static inline Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha) { for( int i = 0; i < cn; i++ ) a[i] = saturate_cast<_Tp>(a[i]*alpha); return a; } template static inline Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha) { double ialpha = 1./alpha; for( int i = 0; i < cn; i++ ) a[i] = saturate_cast<_Tp>(a[i]*ialpha); return a; } template static inline Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha) { float ialpha = 1.f/alpha; for( int i = 0; i < cn; i++ ) a[i] = saturate_cast<_Tp>(a[i]*ialpha); return a; } template static inline Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha) { double ialpha = 1./alpha; for( int i = 0; i < cn; i++ ) a[i] = saturate_cast<_Tp>(a[i]*ialpha); return a; } template static inline Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha) { return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a) { return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha) { return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a) { return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha) { return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a) { return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha) { return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha) { return Vec<_Tp, cn>(a, 1.f/alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha) { return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); } template static inline Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a) { Vec<_Tp,cn> t; for( int i = 0; i < cn; i++ ) t.val[i] = saturate_cast<_Tp>(-a.val[i]); return t; } template inline Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) { return Vec<_Tp, 4>(saturate_cast<_Tp>(v1[0]*v2[0] - v1[1]*v2[1] - v1[2]*v2[2] - v1[3]*v2[3]), saturate_cast<_Tp>(v1[0]*v2[1] + v1[1]*v2[0] + v1[2]*v2[3] - v1[3]*v2[2]), saturate_cast<_Tp>(v1[0]*v2[2] - v1[1]*v2[3] + v1[2]*v2[0] + v1[3]*v2[1]), saturate_cast<_Tp>(v1[0]*v2[3] + v1[1]*v2[2] - v1[2]*v2[1] + v1[3]*v2[0])); } template inline Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) { v1 = v1 * v2; return v1; } //! @} } // cv #endif // __OPENCV_CORE_MATX_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/neon_utils.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HAL_NEON_UTILS_HPP__ #define __OPENCV_HAL_NEON_UTILS_HPP__ #include "opencv2/core/cvdef.h" //! @addtogroup core_utils_neon //! @{ #if CV_NEON inline int32x2_t cv_vrnd_s32_f32(float32x2_t v) { static int32x2_t v_sign = vdup_n_s32(1 << 31), v_05 = vreinterpret_s32_f32(vdup_n_f32(0.5f)); int32x2_t v_addition = vorr_s32(v_05, vand_s32(v_sign, vreinterpret_s32_f32(v))); return vcvt_s32_f32(vadd_f32(v, vreinterpret_f32_s32(v_addition))); } inline int32x4_t cv_vrndq_s32_f32(float32x4_t v) { static int32x4_t v_sign = vdupq_n_s32(1 << 31), v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f)); int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(v))); return vcvtq_s32_f32(vaddq_f32(v, vreinterpretq_f32_s32(v_addition))); } inline uint32x2_t cv_vrnd_u32_f32(float32x2_t v) { static float32x2_t v_05 = vdup_n_f32(0.5f); return vcvt_u32_f32(vadd_f32(v, v_05)); } inline uint32x4_t cv_vrndq_u32_f32(float32x4_t v) { static float32x4_t v_05 = vdupq_n_f32(0.5f); return vcvtq_u32_f32(vaddq_f32(v, v_05)); } inline float32x4_t cv_vrecpq_f32(float32x4_t val) { float32x4_t reciprocal = vrecpeq_f32(val); reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); return reciprocal; } inline float32x2_t cv_vrecp_f32(float32x2_t val) { float32x2_t reciprocal = vrecpe_f32(val); reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); return reciprocal; } inline float32x4_t cv_vrsqrtq_f32(float32x4_t val) { float32x4_t e = vrsqrteq_f32(val); e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); return e; } inline float32x2_t cv_vrsqrt_f32(float32x2_t val) { float32x2_t e = vrsqrte_f32(val); e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); return e; } inline float32x4_t cv_vsqrtq_f32(float32x4_t val) { return cv_vrecpq_f32(cv_vrsqrtq_f32(val)); } inline float32x2_t cv_vsqrt_f32(float32x2_t val) { return cv_vrecp_f32(cv_vrsqrt_f32(val)); } #endif //! @} #endif // __OPENCV_HAL_NEON_UTILS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/ocl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the OpenCV Foundation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OPENCL_HPP__ #define __OPENCV_OPENCL_HPP__ #include "opencv2/core.hpp" namespace cv { namespace ocl { //! @addtogroup core_opencl //! @{ CV_EXPORTS_W bool haveOpenCL(); CV_EXPORTS_W bool useOpenCL(); CV_EXPORTS_W bool haveAmdBlas(); CV_EXPORTS_W bool haveAmdFft(); CV_EXPORTS_W void setUseOpenCL(bool flag); CV_EXPORTS_W void finish(); CV_EXPORTS bool haveSVM(); class CV_EXPORTS Context; class CV_EXPORTS Device; class CV_EXPORTS Kernel; class CV_EXPORTS Program; class CV_EXPORTS ProgramSource; class CV_EXPORTS Queue; class CV_EXPORTS PlatformInfo; class CV_EXPORTS Image2D; class CV_EXPORTS Device { public: Device(); explicit Device(void* d); Device(const Device& d); Device& operator = (const Device& d); ~Device(); void set(void* d); enum { TYPE_DEFAULT = (1 << 0), TYPE_CPU = (1 << 1), TYPE_GPU = (1 << 2), TYPE_ACCELERATOR = (1 << 3), TYPE_DGPU = TYPE_GPU + (1 << 16), TYPE_IGPU = TYPE_GPU + (1 << 17), TYPE_ALL = 0xFFFFFFFF }; String name() const; String extensions() const; String version() const; String vendorName() const; String OpenCL_C_Version() const; String OpenCLVersion() const; int deviceVersionMajor() const; int deviceVersionMinor() const; String driverVersion() const; void* ptr() const; int type() const; int addressBits() const; bool available() const; bool compilerAvailable() const; bool linkerAvailable() const; enum { FP_DENORM=(1 << 0), FP_INF_NAN=(1 << 1), FP_ROUND_TO_NEAREST=(1 << 2), FP_ROUND_TO_ZERO=(1 << 3), FP_ROUND_TO_INF=(1 << 4), FP_FMA=(1 << 5), FP_SOFT_FLOAT=(1 << 6), FP_CORRECTLY_ROUNDED_DIVIDE_SQRT=(1 << 7) }; int doubleFPConfig() const; int singleFPConfig() const; int halfFPConfig() const; bool endianLittle() const; bool errorCorrectionSupport() const; enum { EXEC_KERNEL=(1 << 0), EXEC_NATIVE_KERNEL=(1 << 1) }; int executionCapabilities() const; size_t globalMemCacheSize() const; enum { NO_CACHE=0, READ_ONLY_CACHE=1, READ_WRITE_CACHE=2 }; int globalMemCacheType() const; int globalMemCacheLineSize() const; size_t globalMemSize() const; size_t localMemSize() const; enum { NO_LOCAL_MEM=0, LOCAL_IS_LOCAL=1, LOCAL_IS_GLOBAL=2 }; int localMemType() const; bool hostUnifiedMemory() const; bool imageSupport() const; bool imageFromBufferSupport() const; uint imagePitchAlignment() const; uint imageBaseAddressAlignment() const; size_t image2DMaxWidth() const; size_t image2DMaxHeight() const; size_t image3DMaxWidth() const; size_t image3DMaxHeight() const; size_t image3DMaxDepth() const; size_t imageMaxBufferSize() const; size_t imageMaxArraySize() const; enum { UNKNOWN_VENDOR=0, VENDOR_AMD=1, VENDOR_INTEL=2, VENDOR_NVIDIA=3 }; int vendorID() const; // FIXIT // dev.isAMD() doesn't work for OpenCL CPU devices from AMD OpenCL platform. // This method should use platform name instead of vendor name. // After fix restore code in arithm.cpp: ocl_compare() inline bool isAMD() const { return vendorID() == VENDOR_AMD; } inline bool isIntel() const { return vendorID() == VENDOR_INTEL; } inline bool isNVidia() const { return vendorID() == VENDOR_NVIDIA; } int maxClockFrequency() const; int maxComputeUnits() const; int maxConstantArgs() const; size_t maxConstantBufferSize() const; size_t maxMemAllocSize() const; size_t maxParameterSize() const; int maxReadImageArgs() const; int maxWriteImageArgs() const; int maxSamplers() const; size_t maxWorkGroupSize() const; int maxWorkItemDims() const; void maxWorkItemSizes(size_t*) const; int memBaseAddrAlign() const; int nativeVectorWidthChar() const; int nativeVectorWidthShort() const; int nativeVectorWidthInt() const; int nativeVectorWidthLong() const; int nativeVectorWidthFloat() const; int nativeVectorWidthDouble() const; int nativeVectorWidthHalf() const; int preferredVectorWidthChar() const; int preferredVectorWidthShort() const; int preferredVectorWidthInt() const; int preferredVectorWidthLong() const; int preferredVectorWidthFloat() const; int preferredVectorWidthDouble() const; int preferredVectorWidthHalf() const; size_t printfBufferSize() const; size_t profilingTimerResolution() const; static const Device& getDefault(); protected: struct Impl; Impl* p; }; class CV_EXPORTS Context { public: Context(); explicit Context(int dtype); ~Context(); Context(const Context& c); Context& operator = (const Context& c); bool create(); bool create(int dtype); size_t ndevices() const; const Device& device(size_t idx) const; Program getProg(const ProgramSource& prog, const String& buildopt, String& errmsg); static Context& getDefault(bool initialize = true); void* ptr() const; friend void initializeContextFromHandle(Context& ctx, void* platform, void* context, void* device); bool useSVM() const; void setUseSVM(bool enabled); struct Impl; Impl* p; }; class CV_EXPORTS Platform { public: Platform(); ~Platform(); Platform(const Platform& p); Platform& operator = (const Platform& p); void* ptr() const; static Platform& getDefault(); friend void initializeContextFromHandle(Context& ctx, void* platform, void* context, void* device); protected: struct Impl; Impl* p; }; /* //! @brief Attaches OpenCL context to OpenCV // //! @note Note: // OpenCV will check if available OpenCL platform has platformName name, // then assign context to OpenCV and call clRetainContext function. // The deviceID device will be used as target device and new command queue // will be created. // // Params: //! @param platformName - name of OpenCL platform to attach, //! this string is used to check if platform is available //! to OpenCV at runtime //! @param platfromID - ID of platform attached context was created for //! @param context - OpenCL context to be attached to OpenCV //! @param deviceID - ID of device, must be created from attached context */ CV_EXPORTS void attachContext(const String& platformName, void* platformID, void* context, void* deviceID); /* //! @brief Convert OpenCL buffer to UMat // //! @note Note: // OpenCL buffer (cl_mem_buffer) should contain 2D image data, compatible with OpenCV. // Memory content is not copied from clBuffer to UMat. Instead, buffer handle assigned // to UMat and clRetainMemObject is called. // // Params: //! @param cl_mem_buffer - source clBuffer handle //! @param step - num of bytes in single row //! @param rows - number of rows //! @param cols - number of cols //! @param type - OpenCV type of image //! @param dst - destination UMat */ CV_EXPORTS void convertFromBuffer(void* cl_mem_buffer, size_t step, int rows, int cols, int type, UMat& dst); /* //! @brief Convert OpenCL image2d_t to UMat // //! @note Note: // OpenCL image2d_t (cl_mem_image), should be compatible with OpenCV // UMat formats. // Memory content is copied from image to UMat with // clEnqueueCopyImageToBuffer function. // // Params: //! @param cl_mem_image - source image2d_t handle //! @param dst - destination UMat */ CV_EXPORTS void convertFromImage(void* cl_mem_image, UMat& dst); // TODO Move to internal header void initializeContextFromHandle(Context& ctx, void* platform, void* context, void* device); class CV_EXPORTS Queue { public: Queue(); explicit Queue(const Context& c, const Device& d=Device()); ~Queue(); Queue(const Queue& q); Queue& operator = (const Queue& q); bool create(const Context& c=Context(), const Device& d=Device()); void finish(); void* ptr() const; static Queue& getDefault(); protected: struct Impl; Impl* p; }; class CV_EXPORTS KernelArg { public: enum { LOCAL=1, READ_ONLY=2, WRITE_ONLY=4, READ_WRITE=6, CONSTANT=8, PTR_ONLY = 16, NO_SIZE=256 }; KernelArg(int _flags, UMat* _m, int wscale=1, int iwscale=1, const void* _obj=0, size_t _sz=0); KernelArg(); static KernelArg Local() { return KernelArg(LOCAL, 0); } static KernelArg PtrWriteOnly(const UMat& m) { return KernelArg(PTR_ONLY+WRITE_ONLY, (UMat*)&m); } static KernelArg PtrReadOnly(const UMat& m) { return KernelArg(PTR_ONLY+READ_ONLY, (UMat*)&m); } static KernelArg PtrReadWrite(const UMat& m) { return KernelArg(PTR_ONLY+READ_WRITE, (UMat*)&m); } static KernelArg ReadWrite(const UMat& m, int wscale=1, int iwscale=1) { return KernelArg(READ_WRITE, (UMat*)&m, wscale, iwscale); } static KernelArg ReadWriteNoSize(const UMat& m, int wscale=1, int iwscale=1) { return KernelArg(READ_WRITE+NO_SIZE, (UMat*)&m, wscale, iwscale); } static KernelArg ReadOnly(const UMat& m, int wscale=1, int iwscale=1) { return KernelArg(READ_ONLY, (UMat*)&m, wscale, iwscale); } static KernelArg WriteOnly(const UMat& m, int wscale=1, int iwscale=1) { return KernelArg(WRITE_ONLY, (UMat*)&m, wscale, iwscale); } static KernelArg ReadOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) { return KernelArg(READ_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } static KernelArg WriteOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) { return KernelArg(WRITE_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } static KernelArg Constant(const Mat& m); template static KernelArg Constant(const _Tp* arr, size_t n) { return KernelArg(CONSTANT, 0, 1, 1, (void*)arr, n); } int flags; UMat* m; const void* obj; size_t sz; int wscale, iwscale; }; class CV_EXPORTS Kernel { public: Kernel(); Kernel(const char* kname, const Program& prog); Kernel(const char* kname, const ProgramSource& prog, const String& buildopts = String(), String* errmsg=0); ~Kernel(); Kernel(const Kernel& k); Kernel& operator = (const Kernel& k); bool empty() const; bool create(const char* kname, const Program& prog); bool create(const char* kname, const ProgramSource& prog, const String& buildopts, String* errmsg=0); int set(int i, const void* value, size_t sz); int set(int i, const Image2D& image2D); int set(int i, const UMat& m); int set(int i, const KernelArg& arg); template int set(int i, const _Tp& value) { return set(i, &value, sizeof(value)); } template Kernel& args(const _Tp0& a0) { set(0, a0); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1) { int i = set(0, a0); set(i, a1); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2) { int i = set(0, a0); i = set(i, a1); set(i, a2); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); set(i, a4); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); set(i, a5); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); set(i, a6); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); set(i, a7); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); set(i, a8); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8, const _Tp9& a9) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); i = set(i, a8); set(i, a9); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8, const _Tp9& a9, const _Tp10& a10) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); set(i, a10); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); set(i, a11); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11, const _Tp12& a12) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11); set(i, a12); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11, const _Tp12& a12, const _Tp13& a13) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11); i = set(i, a12); set(i, a13); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11, const _Tp12& a12, const _Tp13& a13, const _Tp14& a14) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11); i = set(i, a12); i = set(i, a13); set(i, a14); return *this; } template Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3, const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7, const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11, const _Tp12& a12, const _Tp13& a13, const _Tp14& a14, const _Tp15& a15) { int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5); i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11); i = set(i, a12); i = set(i, a13); i = set(i, a14); set(i, a15); return *this; } bool run(int dims, size_t globalsize[], size_t localsize[], bool sync, const Queue& q=Queue()); bool runTask(bool sync, const Queue& q=Queue()); size_t workGroupSize() const; size_t preferedWorkGroupSizeMultiple() const; bool compileWorkGroupSize(size_t wsz[]) const; size_t localMemSize() const; void* ptr() const; struct Impl; protected: Impl* p; }; class CV_EXPORTS Program { public: Program(); Program(const ProgramSource& src, const String& buildflags, String& errmsg); explicit Program(const String& buf); Program(const Program& prog); Program& operator = (const Program& prog); ~Program(); bool create(const ProgramSource& src, const String& buildflags, String& errmsg); bool read(const String& buf, const String& buildflags); bool write(String& buf) const; const ProgramSource& source() const; void* ptr() const; String getPrefix() const; static String getPrefix(const String& buildflags); protected: struct Impl; Impl* p; }; class CV_EXPORTS ProgramSource { public: typedef uint64 hash_t; ProgramSource(); explicit ProgramSource(const String& prog); explicit ProgramSource(const char* prog); ~ProgramSource(); ProgramSource(const ProgramSource& prog); ProgramSource& operator = (const ProgramSource& prog); const String& source() const; hash_t hash() const; protected: struct Impl; Impl* p; }; class CV_EXPORTS PlatformInfo { public: PlatformInfo(); explicit PlatformInfo(void* id); ~PlatformInfo(); PlatformInfo(const PlatformInfo& i); PlatformInfo& operator =(const PlatformInfo& i); String name() const; String vendor() const; String version() const; int deviceNumber() const; void getDevice(Device& device, int d) const; protected: struct Impl; Impl* p; }; CV_EXPORTS const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf); CV_EXPORTS const char* typeToStr(int t); CV_EXPORTS const char* memopTypeToStr(int t); CV_EXPORTS const char* vecopTypeToStr(int t); CV_EXPORTS String kernelToStr(InputArray _kernel, int ddepth = -1, const char * name = NULL); CV_EXPORTS void getPlatfomsInfo(std::vector& platform_info); enum OclVectorStrategy { // all matrices have its own vector width OCL_VECTOR_OWN = 0, // all matrices have maximal vector width among all matrices // (useful for cases when matrices have different data types) OCL_VECTOR_MAX = 1, // default strategy OCL_VECTOR_DEFAULT = OCL_VECTOR_OWN }; CV_EXPORTS int predictOptimalVectorWidth(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), OclVectorStrategy strat = OCL_VECTOR_DEFAULT); CV_EXPORTS int checkOptimalVectorWidth(const int *vectorWidths, InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), OclVectorStrategy strat = OCL_VECTOR_DEFAULT); // with OCL_VECTOR_MAX strategy CV_EXPORTS int predictOptimalVectorWidthMax(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray()); CV_EXPORTS void buildOptionsAddMatrixDescription(String& buildOptions, const String& name, InputArray _m); class CV_EXPORTS Image2D { public: Image2D(); // src: The UMat from which to get image properties and data // norm: Flag to enable the use of normalized channel data types // alias: Flag indicating that the image should alias the src UMat. // If true, changes to the image or src will be reflected in // both objects. explicit Image2D(const UMat &src, bool norm = false, bool alias = false); Image2D(const Image2D & i); ~Image2D(); Image2D & operator = (const Image2D & i); // Indicates if creating an aliased image should succeed. Depends on the // underlying platform and the dimensions of the UMat. static bool canCreateAlias(const UMat &u); // Indicates if the image format is supported. static bool isFormatSupported(int depth, int cn, bool norm); void* ptr() const; protected: struct Impl; Impl* p; }; CV_EXPORTS MatAllocator* getOpenCLAllocator(); #ifdef __OPENCV_BUILD namespace internal { CV_EXPORTS bool isPerformanceCheckBypassed(); #define OCL_PERFORMANCE_CHECK(condition) (cv::ocl::internal::isPerformanceCheckBypassed() || (condition)) CV_EXPORTS bool isCLBuffer(UMat& u); } // namespace internal #endif //! @} }} #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/ocl_genbase.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the OpenCV Foundation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OPENCL_GENBASE_HPP__ #define __OPENCV_OPENCL_GENBASE_HPP__ namespace cv { namespace ocl { //! @cond IGNORED struct ProgramEntry { const char* name; const char* programStr; const char* programHash; }; //! @endcond } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/opengl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_OPENGL_HPP__ #define __OPENCV_CORE_OPENGL_HPP__ #ifndef __cplusplus # error opengl.hpp header must be compiled as C++ #endif #include "opencv2/core.hpp" #include "ocl.hpp" namespace cv { namespace ogl { /** @addtogroup core_opengl This section describes OpenGL interoperability. To enable OpenGL support, configure OpenCV using CMake with WITH_OPENGL=ON . Currently OpenGL is supported only with WIN32, GTK and Qt backends on Windows and Linux (MacOS and Android are not supported). For GTK backend gtkglext-1.0 library is required. To use OpenGL functionality you should first create OpenGL context (window or frame buffer). You can do this with namedWindow function or with other OpenGL toolkit (GLUT, for example). */ //! @{ /////////////////// OpenGL Objects /////////////////// /** @brief Smart pointer for OpenGL buffer object with reference counting. Buffer Objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL context. These can be used to store vertex data, pixel data retrieved from images or the framebuffer, and a variety of other things. ogl::Buffer has interface similar with Mat interface and represents 2D array memory. ogl::Buffer supports memory transfers between host and device and also can be mapped to CUDA memory. */ class CV_EXPORTS Buffer { public: /** @brief The target defines how you intend to use the buffer object. */ enum Target { ARRAY_BUFFER = 0x8892, //!< The buffer will be used as a source for vertex data ELEMENT_ARRAY_BUFFER = 0x8893, //!< The buffer will be used for indices (in glDrawElements, for example) PIXEL_PACK_BUFFER = 0x88EB, //!< The buffer will be used for reading from OpenGL textures PIXEL_UNPACK_BUFFER = 0x88EC //!< The buffer will be used for writing to OpenGL textures }; enum Access { READ_ONLY = 0x88B8, WRITE_ONLY = 0x88B9, READ_WRITE = 0x88BA }; /** @brief The constructors. Creates empty ogl::Buffer object, creates ogl::Buffer object from existed buffer ( abufId parameter), allocates memory for ogl::Buffer object or copies from host/device memory. */ Buffer(); /** @overload @param arows Number of rows in a 2D array. @param acols Number of columns in a 2D array. @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. @param abufId Buffer object name. @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ Buffer(int arows, int acols, int atype, unsigned int abufId, bool autoRelease = false); /** @overload @param asize 2D array size. @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. @param abufId Buffer object name. @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ Buffer(Size asize, int atype, unsigned int abufId, bool autoRelease = false); /** @overload @param arows Number of rows in a 2D array. @param acols Number of columns in a 2D array. @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. @param target Buffer usage. See cv::ogl::Buffer::Target . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ Buffer(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); /** @overload @param asize 2D array size. @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. @param target Buffer usage. See cv::ogl::Buffer::Target . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ Buffer(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); /** @overload @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). @param target Buffer usage. See cv::ogl::Buffer::Target . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ explicit Buffer(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); /** @brief Allocates memory for ogl::Buffer object. @param arows Number of rows in a 2D array. @param acols Number of columns in a 2D array. @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. @param target Buffer usage. See cv::ogl::Buffer::Target . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ void create(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); /** @overload @param asize 2D array size. @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. @param target Buffer usage. See cv::ogl::Buffer::Target . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ void create(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); /** @brief Decrements the reference counter and destroys the buffer object if needed. The function will call setAutoRelease(true) . */ void release(); /** @brief Sets auto release mode. The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was bound to a window it could be released at any time (user can close a window). If object's destructor is called after destruction of the context it will cause an error. Thus ogl::Buffer doesn't destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). This function can force ogl::Buffer destructor to destroy OpenGL object. @param flag Auto release mode (if true, release will be called in object's destructor). */ void setAutoRelease(bool flag); /** @brief Copies from host/device memory to OpenGL buffer. @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). @param target Buffer usage. See cv::ogl::Buffer::Target . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ void copyFrom(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); /** @overload */ void copyFrom(InputArray arr, cuda::Stream& stream, Target target = ARRAY_BUFFER, bool autoRelease = false); /** @brief Copies from OpenGL buffer to host/device memory or another OpenGL buffer object. @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , std::vector or ogl::Buffer ). */ void copyTo(OutputArray arr) const; /** @overload */ void copyTo(OutputArray arr, cuda::Stream& stream) const; /** @brief Creates a full copy of the buffer object and the underlying data. @param target Buffer usage for destination buffer. @param autoRelease Auto release mode for destination buffer. */ Buffer clone(Target target = ARRAY_BUFFER, bool autoRelease = false) const; /** @brief Binds OpenGL buffer to the specified buffer binding point. @param target Binding point. See cv::ogl::Buffer::Target . */ void bind(Target target) const; /** @brief Unbind any buffers from the specified binding point. @param target Binding point. See cv::ogl::Buffer::Target . */ static void unbind(Target target); /** @brief Maps OpenGL buffer to host memory. mapHost maps to the client's address space the entire data store of the buffer object. The data can then be directly read and/or written relative to the returned pointer, depending on the specified access policy. A mapped data store must be unmapped with ogl::Buffer::unmapHost before its buffer object is used. This operation can lead to memory transfers between host and device. Only one buffer object can be mapped at a time. @param access Access policy, indicating whether it will be possible to read from, write to, or both read from and write to the buffer object's mapped data store. The symbolic constant must be ogl::Buffer::READ_ONLY , ogl::Buffer::WRITE_ONLY or ogl::Buffer::READ_WRITE . */ Mat mapHost(Access access); /** @brief Unmaps OpenGL buffer. */ void unmapHost(); //! map to device memory (blocking) cuda::GpuMat mapDevice(); void unmapDevice(); /** @brief Maps OpenGL buffer to CUDA device memory. This operatation doesn't copy data. Several buffer objects can be mapped to CUDA memory at a time. A mapped data store must be unmapped with ogl::Buffer::unmapDevice before its buffer object is used. */ cuda::GpuMat mapDevice(cuda::Stream& stream); /** @brief Unmaps OpenGL buffer. */ void unmapDevice(cuda::Stream& stream); int rows() const; int cols() const; Size size() const; bool empty() const; int type() const; int depth() const; int channels() const; int elemSize() const; int elemSize1() const; //! get OpenGL opject id unsigned int bufId() const; class Impl; private: Ptr impl_; int rows_; int cols_; int type_; }; /** @brief Smart pointer for OpenGL 2D texture memory with reference counting. */ class CV_EXPORTS Texture2D { public: /** @brief An Image Format describes the way that the images in Textures store their data. */ enum Format { NONE = 0, DEPTH_COMPONENT = 0x1902, //!< Depth RGB = 0x1907, //!< Red, Green, Blue RGBA = 0x1908 //!< Red, Green, Blue, Alpha }; /** @brief The constructors. Creates empty ogl::Texture2D object, allocates memory for ogl::Texture2D object or copies from host/device memory. */ Texture2D(); /** @overload */ Texture2D(int arows, int acols, Format aformat, unsigned int atexId, bool autoRelease = false); /** @overload */ Texture2D(Size asize, Format aformat, unsigned int atexId, bool autoRelease = false); /** @overload @param arows Number of rows. @param acols Number of columns. @param aformat Image format. See cv::ogl::Texture2D::Format . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ Texture2D(int arows, int acols, Format aformat, bool autoRelease = false); /** @overload @param asize 2D array size. @param aformat Image format. See cv::ogl::Texture2D::Format . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ Texture2D(Size asize, Format aformat, bool autoRelease = false); /** @overload @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ explicit Texture2D(InputArray arr, bool autoRelease = false); /** @brief Allocates memory for ogl::Texture2D object. @param arows Number of rows. @param acols Number of columns. @param aformat Image format. See cv::ogl::Texture2D::Format . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ void create(int arows, int acols, Format aformat, bool autoRelease = false); /** @overload @param asize 2D array size. @param aformat Image format. See cv::ogl::Texture2D::Format . @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ void create(Size asize, Format aformat, bool autoRelease = false); /** @brief Decrements the reference counter and destroys the texture object if needed. The function will call setAutoRelease(true) . */ void release(); /** @brief Sets auto release mode. @param flag Auto release mode (if true, release will be called in object's destructor). The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was bound to a window it could be released at any time (user can close a window). If object's destructor is called after destruction of the context it will cause an error. Thus ogl::Texture2D doesn't destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). This function can force ogl::Texture2D destructor to destroy OpenGL object. */ void setAutoRelease(bool flag); /** @brief Copies from host/device memory to OpenGL texture. @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). @param autoRelease Auto release mode (if true, release will be called in object's destructor). */ void copyFrom(InputArray arr, bool autoRelease = false); /** @brief Copies from OpenGL texture to host/device memory or another OpenGL texture object. @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , ogl::Buffer or ogl::Texture2D ). @param ddepth Destination depth. @param autoRelease Auto release mode for destination buffer (if arr is OpenGL buffer or texture). */ void copyTo(OutputArray arr, int ddepth = CV_32F, bool autoRelease = false) const; /** @brief Binds texture to current active texture unit for GL_TEXTURE_2D target. */ void bind() const; int rows() const; int cols() const; Size size() const; bool empty() const; Format format() const; //! get OpenGL opject id unsigned int texId() const; class Impl; private: Ptr impl_; int rows_; int cols_; Format format_; }; /** @brief Wrapper for OpenGL Client-Side Vertex arrays. ogl::Arrays stores vertex data in ogl::Buffer objects. */ class CV_EXPORTS Arrays { public: /** @brief Default constructor */ Arrays(); /** @brief Sets an array of vertex coordinates. @param vertex array with vertex coordinates, can be both host and device memory. */ void setVertexArray(InputArray vertex); /** @brief Resets vertex coordinates. */ void resetVertexArray(); /** @brief Sets an array of vertex colors. @param color array with vertex colors, can be both host and device memory. */ void setColorArray(InputArray color); /** @brief Resets vertex colors. */ void resetColorArray(); /** @brief Sets an array of vertex normals. @param normal array with vertex normals, can be both host and device memory. */ void setNormalArray(InputArray normal); /** @brief Resets vertex normals. */ void resetNormalArray(); /** @brief Sets an array of vertex texture coordinates. @param texCoord array with vertex texture coordinates, can be both host and device memory. */ void setTexCoordArray(InputArray texCoord); /** @brief Resets vertex texture coordinates. */ void resetTexCoordArray(); /** @brief Releases all inner buffers. */ void release(); /** @brief Sets auto release mode all inner buffers. @param flag Auto release mode. */ void setAutoRelease(bool flag); /** @brief Binds all vertex arrays. */ void bind() const; /** @brief Returns the vertex count. */ int size() const; bool empty() const; private: int size_; Buffer vertex_; Buffer color_; Buffer normal_; Buffer texCoord_; }; /////////////////// Render Functions /////////////////// //! render mode enum RenderModes { POINTS = 0x0000, LINES = 0x0001, LINE_LOOP = 0x0002, LINE_STRIP = 0x0003, TRIANGLES = 0x0004, TRIANGLE_STRIP = 0x0005, TRIANGLE_FAN = 0x0006, QUADS = 0x0007, QUAD_STRIP = 0x0008, POLYGON = 0x0009 }; /** @brief Render OpenGL texture or primitives. @param tex Texture to draw. @param wndRect Region of window, where to draw a texture (normalized coordinates). @param texRect Region of texture to draw (normalized coordinates). */ CV_EXPORTS void render(const Texture2D& tex, Rect_ wndRect = Rect_(0.0, 0.0, 1.0, 1.0), Rect_ texRect = Rect_(0.0, 0.0, 1.0, 1.0)); /** @overload @param arr Array of privitives vertices. @param mode Render mode. One of cv::ogl::RenderModes @param color Color for all vertices. Will be used if arr doesn't contain color array. */ CV_EXPORTS void render(const Arrays& arr, int mode = POINTS, Scalar color = Scalar::all(255)); /** @overload @param arr Array of privitives vertices. @param indices Array of vertices indices (host or device memory). @param mode Render mode. One of cv::ogl::RenderModes @param color Color for all vertices. Will be used if arr doesn't contain color array. */ CV_EXPORTS void render(const Arrays& arr, InputArray indices, int mode = POINTS, Scalar color = Scalar::all(255)); /////////////////// CL-GL Interoperability Functions /////////////////// namespace ocl { using namespace cv::ocl; // TODO static functions in the Context class /** @brief Creates OpenCL context from GL. @return Returns reference to OpenCL Context */ CV_EXPORTS Context& initializeContextFromGL(); } // namespace cv::ogl::ocl /** @brief Converts InputArray to Texture2D object. @param src - source InputArray. @param texture - destination Texture2D object. */ CV_EXPORTS void convertToGLTexture2D(InputArray src, Texture2D& texture); /** @brief Converts Texture2D object to OutputArray. @param texture - source Texture2D object. @param dst - destination OutputArray. */ CV_EXPORTS void convertFromGLTexture2D(const Texture2D& texture, OutputArray dst); /** @brief Maps Buffer object to process on CL side (convert to UMat). Function creates CL buffer from GL one, and then constructs UMat that can be used to process buffer data with OpenCV functions. Note that in current implementation UMat constructed this way doesn't own corresponding GL buffer object, so it is the user responsibility to close down CL/GL buffers relationships by explicitly calling unmapGLBuffer() function. @param buffer - source Buffer object. @param accessFlags - data access flags (ACCESS_READ|ACCESS_WRITE). @return Returns UMat object */ CV_EXPORTS UMat mapGLBuffer(const Buffer& buffer, int accessFlags = ACCESS_READ|ACCESS_WRITE); /** @brief Unmaps Buffer object (releases UMat, previously mapped from Buffer). Function must be called explicitly by the user for each UMat previously constructed by the call to mapGLBuffer() function. @param u - source UMat, created by mapGLBuffer(). */ CV_EXPORTS void unmapGLBuffer(UMat& u); }} // namespace cv::ogl namespace cv { namespace cuda { //! @addtogroup cuda //! @{ /** @brief Sets a CUDA device and initializes it for the current thread with OpenGL interoperability. This function should be explicitly called after OpenGL context creation and before any CUDA calls. @param device System index of a CUDA device starting with 0. @ingroup core_opengl */ CV_EXPORTS void setGlDevice(int device = 0); //! @} }} //! @cond IGNORED //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// inline cv::ogl::Buffer::Buffer(int arows, int acols, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) { create(arows, acols, atype, target, autoRelease); } inline cv::ogl::Buffer::Buffer(Size asize, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) { create(asize, atype, target, autoRelease); } inline void cv::ogl::Buffer::create(Size asize, int atype, Target target, bool autoRelease) { create(asize.height, asize.width, atype, target, autoRelease); } inline int cv::ogl::Buffer::rows() const { return rows_; } inline int cv::ogl::Buffer::cols() const { return cols_; } inline cv::Size cv::ogl::Buffer::size() const { return Size(cols_, rows_); } inline bool cv::ogl::Buffer::empty() const { return rows_ == 0 || cols_ == 0; } inline int cv::ogl::Buffer::type() const { return type_; } inline int cv::ogl::Buffer::depth() const { return CV_MAT_DEPTH(type_); } inline int cv::ogl::Buffer::channels() const { return CV_MAT_CN(type_); } inline int cv::ogl::Buffer::elemSize() const { return CV_ELEM_SIZE(type_); } inline int cv::ogl::Buffer::elemSize1() const { return CV_ELEM_SIZE1(type_); } /////// inline cv::ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) { create(arows, acols, aformat, autoRelease); } inline cv::ogl::Texture2D::Texture2D(Size asize, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) { create(asize, aformat, autoRelease); } inline void cv::ogl::Texture2D::create(Size asize, Format aformat, bool autoRelease) { create(asize.height, asize.width, aformat, autoRelease); } inline int cv::ogl::Texture2D::rows() const { return rows_; } inline int cv::ogl::Texture2D::cols() const { return cols_; } inline cv::Size cv::ogl::Texture2D::size() const { return Size(cols_, rows_); } inline bool cv::ogl::Texture2D::empty() const { return rows_ == 0 || cols_ == 0; } inline cv::ogl::Texture2D::Format cv::ogl::Texture2D::format() const { return format_; } /////// inline cv::ogl::Arrays::Arrays() : size_(0) { } inline int cv::ogl::Arrays::size() const { return size_; } inline bool cv::ogl::Arrays::empty() const { return size_ == 0; } //! @endcond #endif /* __OPENCV_CORE_OPENGL_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/operations.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_OPERATIONS_HPP__ #define __OPENCV_CORE_OPERATIONS_HPP__ #ifndef __cplusplus # error operations.hpp header must be compiled as C++ #endif #include //! @cond IGNORED namespace cv { ////////////////////////////// Matx methods depending on core API ///////////////////////////// namespace internal { template struct Matx_FastInvOp { bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const { Matx<_Tp, m, m> temp = a; // assume that b is all 0's on input => make it a unity matrix for( int i = 0; i < m; i++ ) b(i, i) = (_Tp)1; if( method == DECOMP_CHOLESKY ) return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; } }; template struct Matx_FastInvOp<_Tp, 2> { bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int) const { _Tp d = determinant(a); if( d == 0 ) return false; d = 1/d; b(1,1) = a(0,0)*d; b(0,0) = a(1,1)*d; b(0,1) = -a(0,1)*d; b(1,0) = -a(1,0)*d; return true; } }; template struct Matx_FastInvOp<_Tp, 3> { bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int) const { _Tp d = (_Tp)determinant(a); if( d == 0 ) return false; d = 1/d; b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d; b(0,1) = (a(0,2) * a(2,1) - a(0,1) * a(2,2)) * d; b(0,2) = (a(0,1) * a(1,2) - a(0,2) * a(1,1)) * d; b(1,0) = (a(1,2) * a(2,0) - a(1,0) * a(2,2)) * d; b(1,1) = (a(0,0) * a(2,2) - a(0,2) * a(2,0)) * d; b(1,2) = (a(0,2) * a(1,0) - a(0,0) * a(1,2)) * d; b(2,0) = (a(1,0) * a(2,1) - a(1,1) * a(2,0)) * d; b(2,1) = (a(0,1) * a(2,0) - a(0,0) * a(2,1)) * d; b(2,2) = (a(0,0) * a(1,1) - a(0,1) * a(1,0)) * d; return true; } }; template struct Matx_FastSolveOp { bool operator()(const Matx<_Tp, m, m>& a, const Matx<_Tp, m, n>& b, Matx<_Tp, m, n>& x, int method) const { Matx<_Tp, m, m> temp = a; x = b; if( method == DECOMP_CHOLESKY ) return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; } }; template struct Matx_FastSolveOp<_Tp, 2, 1> { bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b, Matx<_Tp, 2, 1>& x, int) const { _Tp d = determinant(a); if( d == 0 ) return false; d = 1/d; x(0) = (b(0)*a(1,1) - b(1)*a(0,1))*d; x(1) = (b(1)*a(0,0) - b(0)*a(1,0))*d; return true; } }; template struct Matx_FastSolveOp<_Tp, 3, 1> { bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b, Matx<_Tp, 3, 1>& x, int) const { _Tp d = (_Tp)determinant(a); if( d == 0 ) return false; d = 1/d; x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) - a(0,1)*(b(1)*a(2,2) - a(1,2)*b(2)) + a(0,2)*(b(1)*a(2,1) - a(1,1)*b(2))); x(1) = d*(a(0,0)*(b(1)*a(2,2) - a(1,2)*b(2)) - b(0)*(a(1,0)*a(2,2) - a(1,2)*a(2,0)) + a(0,2)*(a(1,0)*b(2) - b(1)*a(2,0))); x(2) = d*(a(0,0)*(a(1,1)*b(2) - b(1)*a(2,1)) - a(0,1)*(a(1,0)*b(2) - b(1)*a(2,0)) + b(0)*(a(1,0)*a(2,1) - a(1,1)*a(2,0))); return true; } }; } // internal template inline Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) { Matx<_Tp,m,n> M; cv::randu(M, Scalar(a), Scalar(b)); return M; } template inline Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) { Matx<_Tp,m,n> M; cv::randn(M, Scalar(a), Scalar(b)); return M; } template inline Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method, bool *p_is_ok /*= NULL*/) const { Matx<_Tp, n, m> b; bool ok; if( method == DECOMP_LU || method == DECOMP_CHOLESKY ) ok = cv::internal::Matx_FastInvOp<_Tp, m>()(*this, b, method); else { Mat A(*this, false), B(b, false); ok = (invert(A, B, method) != 0); } if( NULL != p_is_ok ) { *p_is_ok = ok; } return ok ? b : Matx<_Tp, n, m>::zeros(); } template template inline Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const { Matx<_Tp, n, l> x; bool ok; if( method == DECOMP_LU || method == DECOMP_CHOLESKY ) ok = cv::internal::Matx_FastSolveOp<_Tp, m, l>()(*this, rhs, x, method); else { Mat A(*this, false), B(rhs, false), X(x, false); ok = cv::solve(A, B, X, method); } return ok ? x : Matx<_Tp, n, l>::zeros(); } ////////////////////////// Augmenting algebraic & logical operations ////////////////////////// #define CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ static inline A& operator op (A& a, const B& b) { cvop; return a; } #define CV_MAT_AUG_OPERATOR(op, cvop, A, B) \ CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) #define CV_MAT_AUG_OPERATOR_T(op, cvop, A, B) \ template CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ template CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Mat) CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Scalar) CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat) CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Scalar) CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat_<_Tp>) CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Mat) CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Scalar) CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat) CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Scalar) CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat_<_Tp>) CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat) CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat) CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat_<_Tp>) CV_MAT_AUG_OPERATOR (*=, a.convertTo(a, -1, b), Mat, double) CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double) CV_MAT_AUG_OPERATOR (/=, cv::divide(a,b,a), Mat, Mat) CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat) CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat_<_Tp>) CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double) CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double) CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Mat) CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Scalar) CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat) CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Scalar) CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat_<_Tp>) CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Mat) CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Scalar) CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat) CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Scalar) CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat_<_Tp>) CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Mat) CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Scalar) CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat) CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Scalar) CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat_<_Tp>) #undef CV_MAT_AUG_OPERATOR_T #undef CV_MAT_AUG_OPERATOR #undef CV_MAT_AUG_OPERATOR1 ///////////////////////////////////////////// SVD ///////////////////////////////////////////// inline SVD::SVD() {} inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } inline void SVD::solveZ( InputArray m, OutputArray _dst ) { Mat mtx = m.getMat(); SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); _dst.create(svd.vt.cols, 1, svd.vt.type()); Mat dst = _dst.getMat(); svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); } template inline void SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ) { CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false); SVD::compute(_a, _w, _u, _vt); CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); } template inline void SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) { CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); Mat _a(a, false), _w(w, false); SVD::compute(_a, _w); CV_Assert(_w.data == (uchar*)&w.val[0]); } template inline void SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ) { CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false); SVD::backSubst(_w, _u, _vt, _rhs, _dst); CV_Assert(_dst.data == (uchar*)&dst.val[0]); } /////////////////////////////////// Multiply-with-Carry RNG /////////////////////////////////// inline RNG::RNG() { state = 0xffffffff; } inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; } inline RNG::operator uchar() { return (uchar)next(); } inline RNG::operator schar() { return (schar)next(); } inline RNG::operator ushort() { return (ushort)next(); } inline RNG::operator short() { return (short)next(); } inline RNG::operator int() { return (int)next(); } inline RNG::operator unsigned() { return next(); } inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; } inline RNG::operator double() { unsigned t = next(); return (((uint64)t << 32) | next()) * 5.4210108624275221700372640043497e-20; } inline unsigned RNG::operator ()(unsigned N) { return (unsigned)uniform(0,N); } inline unsigned RNG::operator ()() { return next(); } inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next() % (b - a) + a); } inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } inline unsigned RNG::next() { state = (uint64)(unsigned)state* /*CV_RNG_COEFF*/ 4164903690U + (unsigned)(state >> 32); return (unsigned)state; } //! returns the next unifomly-distributed random number of the specified type template static inline _Tp randu() { return (_Tp)theRNG(); } ///////////////////////////////// Formatted string generation ///////////////////////////////// CV_EXPORTS String format( const char* fmt, ... ); ///////////////////////////////// Formatted output of cv::Mat ///////////////////////////////// static inline Ptr format(InputArray mtx, int fmt) { return Formatter::get(fmt)->format(mtx.getMat()); } static inline int print(Ptr fmtd, FILE* stream = stdout) { int written = 0; fmtd->reset(); for(const char* str = fmtd->next(); str; str = fmtd->next()) written += fputs(str, stream); return written; } static inline int print(const Mat& mtx, FILE* stream = stdout) { return print(Formatter::get()->format(mtx), stream); } static inline int print(const UMat& mtx, FILE* stream = stdout) { return print(Formatter::get()->format(mtx.getMat(ACCESS_READ)), stream); } template static inline int print(const std::vector >& vec, FILE* stream = stdout) { return print(Formatter::get()->format(Mat(vec)), stream); } template static inline int print(const std::vector >& vec, FILE* stream = stdout) { return print(Formatter::get()->format(Mat(vec)), stream); } template static inline int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout) { return print(Formatter::get()->format(cv::Mat(matx)), stream); } //! @endcond /****************************************************************************************\ * Auxiliary algorithms * \****************************************************************************************/ /** @brief Splits an element set into equivalency classes. The generic function partition implements an \f$O(N^2)\f$ algorithm for splitting a set of \f$N\f$ elements into one or more equivalency classes, as described in . The function returns the number of equivalency classes. @param _vec Set of elements stored as a vector. @param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is a 0-based cluster index of `vec[i]`. @param predicate Equivalence predicate (pointer to a boolean function of two arguments or an instance of the class that has the method bool operator()(const _Tp& a, const _Tp& b) ). The predicate returns true when the elements are certainly in the same class, and returns false if they may or may not be in the same class. @ingroup core_cluster */ template int partition( const std::vector<_Tp>& _vec, std::vector& labels, _EqPredicate predicate=_EqPredicate()) { int i, j, N = (int)_vec.size(); const _Tp* vec = &_vec[0]; const int PARENT=0; const int RANK=1; std::vector _nodes(N*2); int (*nodes)[2] = (int(*)[2])&_nodes[0]; // The first O(N) pass: create N single-vertex trees for(i = 0; i < N; i++) { nodes[i][PARENT]=-1; nodes[i][RANK] = 0; } // The main O(N^2) pass: merge connected components for( i = 0; i < N; i++ ) { int root = i; // find root while( nodes[root][PARENT] >= 0 ) root = nodes[root][PARENT]; for( j = 0; j < N; j++ ) { if( i == j || !predicate(vec[i], vec[j])) continue; int root2 = j; while( nodes[root2][PARENT] >= 0 ) root2 = nodes[root2][PARENT]; if( root2 != root ) { // unite both trees int rank = nodes[root][RANK], rank2 = nodes[root2][RANK]; if( rank > rank2 ) nodes[root2][PARENT] = root; else { nodes[root][PARENT] = root2; nodes[root2][RANK] += rank == rank2; root = root2; } CV_Assert( nodes[root][PARENT] < 0 ); int k = j, parent; // compress the path from node2 to root while( (parent = nodes[k][PARENT]) >= 0 ) { nodes[k][PARENT] = root; k = parent; } // compress the path from node to root k = i; while( (parent = nodes[k][PARENT]) >= 0 ) { nodes[k][PARENT] = root; k = parent; } } } } // Final O(N) pass: enumerate classes labels.resize(N); int nclasses = 0; for( i = 0; i < N; i++ ) { int root = i; while( nodes[root][PARENT] >= 0 ) root = nodes[root][PARENT]; // re-use the rank as the class label if( nodes[root][RANK] >= 0 ) nodes[root][RANK] = ~nclasses++; labels[i] = ~nodes[root][RANK]; } return nclasses; } } // cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/optim.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the OpenCV Foundation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OPTIM_HPP__ #define __OPENCV_OPTIM_HPP__ #include "opencv2/core.hpp" namespace cv { /** @addtogroup core_optim The algorithms in this section minimize or maximize function value within specified constraints or without any constraints. @{ */ /** @brief Basic interface for all solvers */ class CV_EXPORTS MinProblemSolver : public Algorithm { public: /** @brief Represents function being optimized */ class CV_EXPORTS Function { public: virtual ~Function() {} virtual int getDims() const = 0; virtual double getGradientEps() const; virtual double calc(const double* x) const = 0; virtual void getGradient(const double* x,double* grad); }; /** @brief Getter for the optimized function. The optimized function is represented by Function interface, which requires derivatives to implement the sole method calc(double*) to evaluate the function. @return Smart-pointer to an object that implements Function interface - it represents the function that is being optimized. It can be empty, if no function was given so far. */ virtual Ptr getFunction() const = 0; /** @brief Setter for the optimized function. *It should be called at least once before the call to* minimize(), as default value is not usable. @param f The new function to optimize. */ virtual void setFunction(const Ptr& f) = 0; /** @brief Getter for the previously set terminal criteria for this algorithm. @return Deep copy of the terminal criteria used at the moment. */ virtual TermCriteria getTermCriteria() const = 0; /** @brief Set terminal criteria for solver. This method *is not necessary* to be called before the first call to minimize(), as the default value is sensible. Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first. @param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure. */ virtual void setTermCriteria(const TermCriteria& termcrit) = 0; /** @brief actually runs the algorithm and performs the minimization. The sole input parameter determines the centroid of the starting simplex (roughly, it tells where to start), all the others (terminal criteria, initial step, function to be minimized) are supposed to be set via the setters before the call to this method or the default values (not always sensible) will be used. @param x The initial point, that will become a centroid of an initial simplex. After the algorithm will terminate, it will be setted to the point where the algorithm stops, the point of possible minimum. @return The value of a function at the point found. */ virtual double minimize(InputOutputArray x) = 0; }; /** @brief This class is used to perform the non-linear non-constrained minimization of a function, defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as **downhill simplex method**. The basic idea about the method can be obtained from . It should be noted, that this method, although deterministic, is rather a heuristic and therefore may converge to a local minima, not necessary a global one. It is iterative optimization technique, which at each step uses an information about the values of a function evaluated only at `n+1` points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At each step new point is chosen to evaluate function at, obtained value is compared with previous ones and based on this information simplex changes it's shape , slowly moving to the local minimum. Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear Conjugate Gradient method (which is also implemented in optim). Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon. @note DownhillSolver is a derivative of the abstract interface cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to encapsulate the functionality, common to all non-linear optimization algorithms in the optim module. @note term criteria should meet following condition: @code termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 @endcode */ class CV_EXPORTS DownhillSolver : public MinProblemSolver { public: /** @brief Returns the initial step that will be used in downhill simplex algorithm. @param step Initial step that will be used in algorithm. Note, that although corresponding setter accepts column-vectors as well as row-vectors, this method will return a row-vector. @see DownhillSolver::setInitStep */ virtual void getInitStep(OutputArray step) const=0; /** @brief Sets the initial step that will be used in downhill simplex algorithm. Step, together with initial point (givin in DownhillSolver::minimize) are two `n`-dimensional vectors that are used to determine the shape of initial simplex. Roughly said, initial point determines the position of a simplex (it will become simplex's centroid), while step determines the spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are the initial step and initial point respectively, the vertices of a simplex will be: \f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes projections of the initial step of *n*-th coordinate (the result of projection is treated to be vector given by \f$s_i:=e_i\cdot\left\f$, where \f$e_i\f$ form canonical basis) @param step Initial step that will be used in algorithm. Roughly said, it determines the spread (size in each dimension) of an initial simplex. */ virtual void setInitStep(InputArray step)=0; /** @brief This function returns the reference to the ready-to-use DownhillSolver object. All the parameters are optional, so this procedure can be called even without parameters at all. In this case, the default values will be used. As default value for terminal criteria are the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep() should be called upon the obtained object, if the respective parameters were not given to create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely equivalent (and will drop the same errors in the same way, should invalid input be detected). @param f Pointer to the function that will be minimized, similarly to the one you submit via MinProblemSolver::setFunction. @param initStep Initial step, that will be used to construct the initial simplex, similarly to the one you submit via MinProblemSolver::setInitStep. @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via MinProblemSolver::setTermCriteria. */ static Ptr create(const Ptr& f=Ptr(), InputArray initStep=Mat_(1,1,0.0), TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); }; /** @brief This class is used to perform the non-linear non-constrained minimization of a function with known gradient, defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**. The implementation was done based on the beautifully clear explanatory article [An Introduction to the Conjugate Gradient Method Without the Agonizing Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for example ) for numerically solving the systems of linear equations. It should be noted, that this method, although deterministic, is rather a heuristic method and therefore may converge to a local minima, not necessary a global one. What is even more disastrous, most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may converge to it. Another obvious restriction is that it should be possible to compute the gradient of a function at any point, thus it is preferable to have analytic expression for gradient and computational burden should be born by the user. The latter responsibility is accompilished via the getGradient method of a MinProblemSolver::Function interface (which represents function being optimized). This method takes point a point in *n*-dimensional space (first argument represents the array of coordinates of that point) and comput its gradient (it should be stored in the second argument as an array). @note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface. @note term criteria should meet following condition: @code termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 // or termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0 @endcode */ class CV_EXPORTS ConjGradSolver : public MinProblemSolver { public: /** @brief This function returns the reference to the ready-to-use ConjGradSolver object. All the parameters are optional, so this procedure can be called even without parameters at all. In this case, the default values will be used. As default value for terminal criteria are the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained object, if the function was not given to create(). Otherwise, the two ways (submit it to create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent (and will drop the same errors in the same way, should invalid input be detected). @param f Pointer to the function that will be minimized, similarly to the one you submit via MinProblemSolver::setFunction. @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via MinProblemSolver::setTermCriteria. */ static Ptr create(const Ptr& f=Ptr(), TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); }; //! return codes for cv::solveLP() function enum SolveLPResult { SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values) SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed) SOLVELP_SINGLE = 0, //!< there is only one maximum for target function SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned }; /** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method). What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as: \f[\mbox{Maximize } c\cdot x\\ \mbox{Subject to:}\\ Ax\leq b\\ x\geq 0\f] Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1` column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints. Simplex algorithm is one of many algorithms that are designed to handle this sort of problems efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve any problem written as above in polynomial time, while simplex method degenerates to exponential time for some special cases), it is well-studied, easy to implement and is shown to work well for real-life purposes. The particular implementation is taken almost verbatim from **Introduction to Algorithms, third edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the Bland's rule is used to prevent cycling. @param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted, in the latter case it is understood to correspond to \f$c^T\f$. @param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above and the remaining to \f$A\f$. It should containt 32- or 64-bit floating point numbers. @param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the formulation above. It will contain 64-bit floating point numbers. @return One of cv::SolveLPResult */ CV_EXPORTS_W int solveLP(const Mat& Func, const Mat& Constr, Mat& z); //! @} }// cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/persistence.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_PERSISTENCE_HPP__ #define __OPENCV_CORE_PERSISTENCE_HPP__ #ifndef __cplusplus # error persistence.hpp header must be compiled as C++ #endif //! @addtogroup core_c //! @{ /** @brief "black box" representation of the file storage associated with a file on disk. Several functions that are described below take CvFileStorage\* as inputs and allow the user to save or to load hierarchical collections that consist of scalar values, standard CXCore objects (such as matrices, sequences, graphs), and user-defined objects. OpenCV can read and write data in XML () or YAML () formats. Below is an example of 3x3 floating-point identity matrix A, stored in XML and YAML files using CXCore functions: XML: @code{.xml} 3 3
f
1. 0. 0. 0. 1. 0. 0. 0. 1.
@endcode YAML: @code{.yaml} %YAML:1.0 A: !!opencv-matrix rows: 3 cols: 3 dt: f data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.] @endcode As it can be seen from the examples, XML uses nested tags to represent hierarchy, while YAML uses indentation for that purpose (similar to the Python programming language). The same functions can read and write data in both formats; the particular format is determined by the extension of the opened file, ".xml" for XML files and ".yml" or ".yaml" for YAML. */ typedef struct CvFileStorage CvFileStorage; typedef struct CvFileNode CvFileNode; //! @} core_c #include "opencv2/core/types.hpp" #include "opencv2/core/mat.hpp" namespace cv { /** @addtogroup core_xml XML/YAML file storages. {#xml_storage} ======================= Writing to a file storage. -------------------------- You can store and then restore various OpenCV data structures to/from XML () or YAML () formats. Also, it is possible store and load arbitrarily complex data structures, which include OpenCV data structures, as well as primitive data types (integer and floating-point numbers and text strings) as their elements. Use the following procedure to write something to XML or YAML: -# Create new FileStorage and open it for writing. It can be done with a single call to FileStorage::FileStorage constructor that takes a filename, or you can use the default constructor and then call FileStorage::open. Format of the file (XML or YAML) is determined from the filename extension (".xml" and ".yml"/".yaml", respectively) -# Write all the data you want using the streaming operator `<<`, just like in the case of STL streams. -# Close the file using FileStorage::release. FileStorage destructor also closes the file. Here is an example: @code #include "opencv2/opencv.hpp" #include using namespace cv; int main(int, char** argv) { FileStorage fs("test.yml", FileStorage::WRITE); fs << "frameCount" << 5; time_t rawtime; time(&rawtime); fs << "calibrationDate" << asctime(localtime(&rawtime)); Mat cameraMatrix = (Mat_(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1); Mat distCoeffs = (Mat_(5,1) << 0.1, 0.01, -0.001, 0, 0); fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs; fs << "features" << "["; for( int i = 0; i < 3; i++ ) { int x = rand() % 640; int y = rand() % 480; uchar lbp = rand() % 256; fs << "{:" << "x" << x << "y" << y << "lbp" << "[:"; for( int j = 0; j < 8; j++ ) fs << ((lbp >> j) & 1); fs << "]" << "}"; } fs << "]"; fs.release(); return 0; } @endcode The sample above stores to XML and integer, text string (calibration date), 2 matrices, and a custom structure "feature", which includes feature coordinates and LBP (local binary pattern) value. Here is output of the sample: @code{.yaml} %YAML:1.0 frameCount: 5 calibrationDate: "Fri Jun 17 14:09:29 2011\n" cameraMatrix: !!opencv-matrix rows: 3 cols: 3 dt: d data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ] distCoeffs: !!opencv-matrix rows: 5 cols: 1 dt: d data: [ 1.0000000000000001e-01, 1.0000000000000000e-02, -1.0000000000000000e-03, 0., 0. ] features: - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] } - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] } - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] } @endcode As an exercise, you can replace ".yml" with ".xml" in the sample above and see, how the corresponding XML file will look like. Several things can be noted by looking at the sample code and the output: - The produced YAML (and XML) consists of heterogeneous collections that can be nested. There are 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings each element has a name and is accessed by name. This is similar to structures and std::map in C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by indices. This is similar to arrays and std::vector in C/C++ and lists, tuples in Python. "Heterogeneous" means that elements of each single collection can have different types. Top-level collection in YAML/XML is a mapping. Each matrix is stored as a mapping, and the matrix elements are stored as a sequence. Then, there is a sequence of features, where each feature is represented a mapping, and lbp value in a nested sequence. - When you write to a mapping (a structure), you write element name followed by its value. When you write to a sequence, you simply write the elements one by one. OpenCV data structures (such as cv::Mat) are written in absolutely the same way as simple C data structures - using `<<` operator. - To write a mapping, you first write the special string `{` to the storage, then write the elements as pairs (`fs << << `) and then write the closing `}`. - To write a sequence, you first write the special string `[`, then write the elements, then write the closing `]`. - In YAML (but not XML), mappings and sequences can be written in a compact Python-like inline form. In the sample above matrix elements, as well as each feature, including its lbp value, is stored in such inline form. To store a mapping/sequence in a compact form, put `:` after the opening character, e.g. use `{:` instead of `{` and `[:` instead of `[`. When the data is written to XML, those extra `:` are ignored. Reading data from a file storage. --------------------------------- To read the previously written XML or YAML file, do the following: -# Open the file storage using FileStorage::FileStorage constructor or FileStorage::open method. In the current implementation the whole file is parsed and the whole representation of file storage is built in memory as a hierarchy of file nodes (see FileNode) -# Read the data you are interested in. Use FileStorage::operator [], FileNode::operator [] and/or FileNodeIterator. -# Close the storage using FileStorage::release. Here is how to read the file created by the code sample above: @code FileStorage fs2("test.yml", FileStorage::READ); // first method: use (type) operator on FileNode. int frameCount = (int)fs2["frameCount"]; String date; // second method: use FileNode::operator >> fs2["calibrationDate"] >> date; Mat cameraMatrix2, distCoeffs2; fs2["cameraMatrix"] >> cameraMatrix2; fs2["distCoeffs"] >> distCoeffs2; cout << "frameCount: " << frameCount << endl << "calibration date: " << date << endl << "camera matrix: " << cameraMatrix2 << endl << "distortion coeffs: " << distCoeffs2 << endl; FileNode features = fs2["features"]; FileNodeIterator it = features.begin(), it_end = features.end(); int idx = 0; std::vector lbpval; // iterate through a sequence using FileNodeIterator for( ; it != it_end; ++it, idx++ ) { cout << "feature #" << idx << ": "; cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: ("; // you can also easily read numerical arrays using FileNode >> std::vector operator. (*it)["lbp"] >> lbpval; for( int i = 0; i < (int)lbpval.size(); i++ ) cout << " " << (int)lbpval[i]; cout << ")" << endl; } fs2.release(); @endcode Format specification {#format_spec} -------------------- `([count]{u|c|w|s|i|f|d})`... where the characters correspond to fundamental C++ types: - `u` 8-bit unsigned number - `c` 8-bit signed number - `w` 16-bit unsigned number - `s` 16-bit signed number - `i` 32-bit signed number - `f` single precision floating-point number - `d` double precision floating-point number - `r` pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements. `count` is the optional counter of values of a given type. For example, `2if` means that each array element is a structure of 2 integers, followed by a single-precision floating-point number. The equivalent notations of the above specification are `iif`, `2i1f` and so forth. Other examples: `u` means that the array consists of bytes, and `2d` means the array consists of pairs of doubles. @see @ref filestorage.cpp */ //! @{ /** @example filestorage.cpp A complete example using the FileStorage interface */ ////////////////////////// XML & YAML I/O ////////////////////////// class CV_EXPORTS FileNode; class CV_EXPORTS FileNodeIterator; /** @brief XML/YAML file storage class that encapsulates all the information necessary for writing or reading data to/from a file. */ class CV_EXPORTS_W FileStorage { public: //! file storage mode enum Mode { READ = 0, //!< value, open the file for reading WRITE = 1, //!< value, open the file for writing APPEND = 2, //!< value, open the file for appending MEMORY = 4, //!< flag, read data from source or write data to the internal buffer (which is //!< returned by FileStorage::release) FORMAT_MASK = (7<<3), //!< mask for format flags FORMAT_AUTO = 0, //!< flag, auto format FORMAT_XML = (1<<3), //!< flag, XML format FORMAT_YAML = (2<<3) //!< flag, YAML format }; enum { UNDEFINED = 0, VALUE_EXPECTED = 1, NAME_EXPECTED = 2, INSIDE_MAP = 4 }; /** @brief The constructors. The full constructor opens the file. Alternatively you can use the default constructor and then call FileStorage::open. */ CV_WRAP FileStorage(); /** @overload @param source Name of the file to open or the text string to read the data from. Extension of the file (.xml or .yml/.yaml) determines its format (XML or YAML respectively). Also you can append .gz to work with compressed files, for example myHugeMatrix.xml.gz. If both FileStorage::WRITE and FileStorage::MEMORY flags are specified, source is used just to specify the output file format (e.g. mydata.xml, .yml etc.). @param flags Mode of operation. See FileStorage::Mode @param encoding Encoding of the file. Note that UTF-16 XML encoding is not supported currently and you should use 8-bit encoding instead of it. */ CV_WRAP FileStorage(const String& source, int flags, const String& encoding=String()); /** @overload */ FileStorage(CvFileStorage* fs, bool owning=true); //! the destructor. calls release() virtual ~FileStorage(); /** @brief Opens a file. See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release before opening the file. @param filename Name of the file to open or the text string to read the data from. Extension of the file (.xml or .yml/.yaml) determines its format (XML or YAML respectively). Also you can append .gz to work with compressed files, for example myHugeMatrix.xml.gz. If both FileStorage::WRITE and FileStorage::MEMORY flags are specified, source is used just to specify the output file format (e.g. mydata.xml, .yml etc.). @param flags Mode of operation. One of FileStorage::Mode @param encoding Encoding of the file. Note that UTF-16 XML encoding is not supported currently and you should use 8-bit encoding instead of it. */ CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String()); /** @brief Checks whether the file is opened. @returns true if the object is associated with the current file and false otherwise. It is a good practice to call this method after you tried to open a file. */ CV_WRAP virtual bool isOpened() const; /** @brief Closes the file and releases all the memory buffers. Call this method after all I/O operations with the storage are finished. */ CV_WRAP virtual void release(); /** @brief Closes the file and releases all the memory buffers. Call this method after all I/O operations with the storage are finished. If the storage was opened for writing data and FileStorage::WRITE was specified */ CV_WRAP virtual String releaseAndGetString(); /** @brief Returns the first element of the top-level mapping. @returns The first element of the top-level mapping. */ CV_WRAP FileNode getFirstTopLevelNode() const; /** @brief Returns the top-level mapping @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file. However, YAML supports multiple streams and so there can be several. @returns The top-level mapping. */ CV_WRAP FileNode root(int streamidx=0) const; /** @brief Returns the specified element of the top-level mapping. @param nodename Name of the file node. @returns Node with the given name. */ FileNode operator[](const String& nodename) const; /** @overload */ CV_WRAP FileNode operator[](const char* nodename) const; /** @brief Returns the obsolete C FileStorage structure. @returns Pointer to the underlying C FileStorage structure */ CvFileStorage* operator *() { return fs.get(); } /** @overload */ const CvFileStorage* operator *() const { return fs.get(); } /** @brief Writes multiple numbers. Writes one or more numbers of the specified format to the currently written structure. Usually it is more convenient to use operator `<<` instead of this method. @param fmt Specification of each array element, see @ref format_spec "format specification" @param vec Pointer to the written array. @param len Number of the uchar elements to write. */ void writeRaw( const String& fmt, const uchar* vec, size_t len ); /** @brief Writes the registered C structure (CvMat, CvMatND, CvSeq). @param name Name of the written object. @param obj Pointer to the object. @see ocvWrite for details. */ void writeObj( const String& name, const void* obj ); /** @brief Returns the normalized object name for the specified name of a file. @param filename Name of a file @returns The normalized object name. */ static String getDefaultObjectName(const String& filename); Ptr fs; //!< the underlying C FileStorage structure String elname; //!< the currently written element std::vector structs; //!< the stack of written structures int state; //!< the writer state }; template<> CV_EXPORTS void DefaultDeleter::operator ()(CvFileStorage* obj) const; /** @brief File Storage Node class. The node is used to store each and every element of the file storage opened for reading. When XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of nodes. Each node can be a “leaf” that is contain a single number or a string, or be a collection of other nodes. There can be named collections (mappings) where each element has a name and it is accessed by a name, and ordered collections (sequences) where elements do not have names but rather accessed by index. Type of the file node can be determined using FileNode::type method. Note that file nodes are only used for navigating file storages opened for reading. When a file storage is opened for writing, no data is stored in memory after it is written. */ class CV_EXPORTS_W_SIMPLE FileNode { public: //! type of the file storage node enum Type { NONE = 0, //!< empty node INT = 1, //!< an integer REAL = 2, //!< floating-point number FLOAT = REAL, //!< synonym or REAL STR = 3, //!< text string in UTF-8 encoding STRING = STR, //!< synonym for STR REF = 4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others SEQ = 5, //!< sequence MAP = 6, //!< mapping TYPE_MASK = 7, FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer USER = 16, //!< a registered object (e.g. a matrix) EMPTY = 32, //!< empty structure (sequence or mapping) NAMED = 64 //!< the node has a name (i.e. it is element of a mapping) }; /** @brief The constructors. These constructors are used to create a default file node, construct it from obsolete structures or from the another file node. */ CV_WRAP FileNode(); /** @overload @param fs Pointer to the obsolete file storage structure. @param node File node to be used as initialization for the created file node. */ FileNode(const CvFileStorage* fs, const CvFileNode* node); /** @overload @param node File node to be used as initialization for the created file node. */ FileNode(const FileNode& node); /** @brief Returns element of a mapping node or a sequence node. @param nodename Name of an element in the mapping node. @returns Returns the element with the given identifier. */ FileNode operator[](const String& nodename) const; /** @overload @param nodename Name of an element in the mapping node. */ CV_WRAP FileNode operator[](const char* nodename) const; /** @overload @param i Index of an element in the sequence node. */ CV_WRAP FileNode operator[](int i) const; /** @brief Returns type of the node. @returns Type of the node. See FileNode::Type */ CV_WRAP int type() const; //! returns true if the node is empty CV_WRAP bool empty() const; //! returns true if the node is a "none" object CV_WRAP bool isNone() const; //! returns true if the node is a sequence CV_WRAP bool isSeq() const; //! returns true if the node is a mapping CV_WRAP bool isMap() const; //! returns true if the node is an integer CV_WRAP bool isInt() const; //! returns true if the node is a floating-point number CV_WRAP bool isReal() const; //! returns true if the node is a text string CV_WRAP bool isString() const; //! returns true if the node has a name CV_WRAP bool isNamed() const; //! returns the node name or an empty string if the node is nameless CV_WRAP String name() const; //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise. CV_WRAP size_t size() const; //! returns the node content as an integer. If the node stores floating-point number, it is rounded. operator int() const; //! returns the node content as float operator float() const; //! returns the node content as double operator double() const; //! returns the node content as text string operator String() const; #ifndef OPENCV_NOSTL operator std::string() const; #endif //! returns pointer to the underlying file node CvFileNode* operator *(); //! returns pointer to the underlying file node const CvFileNode* operator* () const; //! returns iterator pointing to the first node element FileNodeIterator begin() const; //! returns iterator pointing to the element following the last node element FileNodeIterator end() const; /** @brief Reads node elements to the buffer with the specified format. Usually it is more convenient to use operator `>>` instead of this method. @param fmt Specification of each array element. See @ref format_spec "format specification" @param vec Pointer to the destination array. @param len Number of elements to read. If it is greater than number of remaining elements then all of them will be read. */ void readRaw( const String& fmt, uchar* vec, size_t len ) const; //! reads the registered object and returns pointer to it void* readObj() const; // do not use wrapper pointer classes for better efficiency const CvFileStorage* fs; const CvFileNode* node; }; /** @brief used to iterate through sequences and mappings. A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a sequence, stored in node. See the data reading sample in the beginning of the section. */ class CV_EXPORTS FileNodeIterator { public: /** @brief The constructors. These constructors are used to create a default iterator, set it to specific element in a file node or construct it from another iterator. */ FileNodeIterator(); /** @overload @param fs File storage for the iterator. @param node File node for the iterator. @param ofs Index of the element in the node. The created iterator will point to this element. */ FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0); /** @overload @param it Iterator to be used as initialization for the created iterator. */ FileNodeIterator(const FileNodeIterator& it); //! returns the currently observed element FileNode operator *() const; //! accesses the currently observed element methods FileNode operator ->() const; //! moves iterator to the next node FileNodeIterator& operator ++ (); //! moves iterator to the next node FileNodeIterator operator ++ (int); //! moves iterator to the previous node FileNodeIterator& operator -- (); //! moves iterator to the previous node FileNodeIterator operator -- (int); //! moves iterator forward by the specified offset (possibly negative) FileNodeIterator& operator += (int ofs); //! moves iterator backward by the specified offset (possibly negative) FileNodeIterator& operator -= (int ofs); /** @brief Reads node elements to the buffer with the specified format. Usually it is more convenient to use operator `>>` instead of this method. @param fmt Specification of each array element. See @ref format_spec "format specification" @param vec Pointer to the destination array. @param maxCount Number of elements to read. If it is greater than number of remaining elements then all of them will be read. */ FileNodeIterator& readRaw( const String& fmt, uchar* vec, size_t maxCount=(size_t)INT_MAX ); struct SeqReader { int header_size; void* seq; /* sequence, beign read; CvSeq */ void* block; /* current block; CvSeqBlock */ schar* ptr; /* pointer to element be read next */ schar* block_min; /* pointer to the beginning of block */ schar* block_max; /* pointer to the end of block */ int delta_index;/* = seq->first->start_index */ schar* prev_elem; /* pointer to previous element */ }; const CvFileStorage* fs; const CvFileNode* container; SeqReader reader; size_t remaining; }; //! @} core_xml /////////////////// XML & YAML I/O implementation ////////////////// //! @relates cv::FileStorage //! @{ CV_EXPORTS void write( FileStorage& fs, const String& name, int value ); CV_EXPORTS void write( FileStorage& fs, const String& name, float value ); CV_EXPORTS void write( FileStorage& fs, const String& name, double value ); CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value ); CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value ); CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value ); CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); CV_EXPORTS void writeScalar( FileStorage& fs, int value ); CV_EXPORTS void writeScalar( FileStorage& fs, float value ); CV_EXPORTS void writeScalar( FileStorage& fs, double value ); CV_EXPORTS void writeScalar( FileStorage& fs, const String& value ); //! @} //! @relates cv::FileNode //! @{ CV_EXPORTS void read(const FileNode& node, int& value, int default_value); CV_EXPORTS void read(const FileNode& node, float& value, float default_value); CV_EXPORTS void read(const FileNode& node, double& value, double default_value); CV_EXPORTS void read(const FileNode& node, String& value, const String& default_value); CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() ); CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() ); CV_EXPORTS void read(const FileNode& node, std::vector& keypoints); CV_EXPORTS void read(const FileNode& node, std::vector& matches); template static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value) { std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); } template static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value) { std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), saturate_cast<_Tp>(temp[2])); } template static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value) { std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); } template static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value) { std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); } template static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value) { std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); } template static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value) { std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]); } template static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value) { std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); } static inline void read(const FileNode& node, Range& value, const Range& default_value) { Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end); read(node, temp, default_temp); value.start = temp.x; value.end = temp.y; } //! @} /** @brief Writes string to a file storage. @relates cv::FileStorage */ CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str); //! @cond IGNORED namespace internal { class CV_EXPORTS WriteStructContext { public: WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String()); ~WriteStructContext(); private: FileStorage* fs; }; template class VecWriterProxy { public: VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} void operator()(const std::vector<_Tp>& vec) const { size_t count = vec.size(); for (size_t i = 0; i < count; i++) write(*fs, vec[i]); } private: FileStorage* fs; }; template class VecWriterProxy<_Tp, 1> { public: VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} void operator()(const std::vector<_Tp>& vec) const { int _fmt = DataType<_Tp>::fmt; char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' }; fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp)); } private: FileStorage* fs; }; template class VecReaderProxy { public: VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} void operator()(std::vector<_Tp>& vec, size_t count) const { count = std::min(count, it->remaining); vec.resize(count); for (size_t i = 0; i < count; i++, ++(*it)) read(**it, vec[i], _Tp()); } private: FileNodeIterator* it; }; template class VecReaderProxy<_Tp, 1> { public: VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} void operator()(std::vector<_Tp>& vec, size_t count) const { size_t remaining = it->remaining; size_t cn = DataType<_Tp>::channels; int _fmt = DataType<_Tp>::fmt; char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' }; size_t remaining1 = remaining / cn; count = count < remaining1 ? count : remaining1; vec.resize(count); it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp)); } private: FileNodeIterator* it; }; } // internal //! @endcond //! @relates cv::FileStorage //! @{ template static inline void write(FileStorage& fs, const _Tp& value) { write(fs, String(), value); } template<> inline void write( FileStorage& fs, const int& value ) { writeScalar(fs, value); } template<> inline void write( FileStorage& fs, const float& value ) { writeScalar(fs, value); } template<> inline void write( FileStorage& fs, const double& value ) { writeScalar(fs, value); } template<> inline void write( FileStorage& fs, const String& value ) { writeScalar(fs, value); } template static inline void write(FileStorage& fs, const Point_<_Tp>& pt ) { write(fs, pt.x); write(fs, pt.y); } template static inline void write(FileStorage& fs, const Point3_<_Tp>& pt ) { write(fs, pt.x); write(fs, pt.y); write(fs, pt.z); } template static inline void write(FileStorage& fs, const Size_<_Tp>& sz ) { write(fs, sz.width); write(fs, sz.height); } template static inline void write(FileStorage& fs, const Complex<_Tp>& c ) { write(fs, c.re); write(fs, c.im); } template static inline void write(FileStorage& fs, const Rect_<_Tp>& r ) { write(fs, r.x); write(fs, r.y); write(fs, r.width); write(fs, r.height); } template static inline void write(FileStorage& fs, const Vec<_Tp, cn>& v ) { for(int i = 0; i < cn; i++) write(fs, v.val[i]); } template static inline void write(FileStorage& fs, const Scalar_<_Tp>& s ) { write(fs, s.val[0]); write(fs, s.val[1]); write(fs, s.val[2]); write(fs, s.val[3]); } static inline void write(FileStorage& fs, const Range& r ) { write(fs, r.start); write(fs, r.end); } template static inline void write( FileStorage& fs, const std::vector<_Tp>& vec ) { cv::internal::VecWriterProxy<_Tp, DataType<_Tp>::fmt != 0> w(&fs); w(vec); } template static inline void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, pt); } template static inline void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, pt); } template static inline void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, sz); } template static inline void write(FileStorage& fs, const String& name, const Complex<_Tp>& c ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, c); } template static inline void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, r); } template static inline void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, v); } template static inline void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, s); } static inline void write(FileStorage& fs, const String& name, const Range& r ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); write(fs, r); } template static inline void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec ) { cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+(DataType<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); write(fs, vec); } //! @} FileStorage //! @relates cv::FileNode //! @{ static inline void read(const FileNode& node, bool& value, bool default_value) { int temp; read(node, temp, (int)default_value); value = temp != 0; } static inline void read(const FileNode& node, uchar& value, uchar default_value) { int temp; read(node, temp, (int)default_value); value = saturate_cast(temp); } static inline void read(const FileNode& node, schar& value, schar default_value) { int temp; read(node, temp, (int)default_value); value = saturate_cast(temp); } static inline void read(const FileNode& node, ushort& value, ushort default_value) { int temp; read(node, temp, (int)default_value); value = saturate_cast(temp); } static inline void read(const FileNode& node, short& value, short default_value) { int temp; read(node, temp, (int)default_value); value = saturate_cast(temp); } template static inline void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX ) { cv::internal::VecReaderProxy<_Tp, DataType<_Tp>::fmt != 0> r(&it); r(vec, maxCount); } template static inline void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() ) { if(!node.node) vec = default_value; else { FileNodeIterator it = node.begin(); read( it, vec ); } } //! @} FileNode //! @relates cv::FileStorage //! @{ /** @brief Writes data to a file storage. */ template static inline FileStorage& operator << (FileStorage& fs, const _Tp& value) { if( !fs.isOpened() ) return fs; if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP ) CV_Error( Error::StsError, "No element name has been given" ); write( fs, fs.elname, value ); if( fs.state & FileStorage::INSIDE_MAP ) fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP; return fs; } /** @brief Writes data to a file storage. */ static inline FileStorage& operator << (FileStorage& fs, const char* str) { return (fs << String(str)); } /** @brief Writes data to a file storage. */ static inline FileStorage& operator << (FileStorage& fs, char* value) { return (fs << String(value)); } //! @} FileStorage //! @relates cv::FileNodeIterator //! @{ /** @brief Reads data from a file storage. */ template static inline FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value) { read( *it, value, _Tp()); return ++it; } /** @brief Reads data from a file storage. */ template static inline FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec) { cv::internal::VecReaderProxy<_Tp, DataType<_Tp>::fmt != 0> r(&it); r(vec, (size_t)INT_MAX); return it; } //! @} FileNodeIterator //! @relates cv::FileNode //! @{ /** @brief Reads data from a file storage. */ template static inline void operator >> (const FileNode& n, _Tp& value) { read( n, value, _Tp()); } /** @brief Reads data from a file storage. */ template static inline void operator >> (const FileNode& n, std::vector<_Tp>& vec) { FileNodeIterator it = n.begin(); it >> vec; } //! @} FileNode //! @relates cv::FileNodeIterator //! @{ static inline bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2) { return it1.fs == it2.fs && it1.container == it2.container && it1.reader.ptr == it2.reader.ptr && it1.remaining == it2.remaining; } static inline bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2) { return !(it1 == it2); } static inline ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2) { return it2.remaining - it1.remaining; } static inline bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2) { return it1.remaining > it2.remaining; } //! @} FileNodeIterator //! @cond IGNORED inline FileNode FileStorage::getFirstTopLevelNode() const { FileNode r = root(); FileNodeIterator it = r.begin(); return it != r.end() ? *it : FileNode(); } inline FileNode::FileNode() : fs(0), node(0) {} inline FileNode::FileNode(const CvFileStorage* _fs, const CvFileNode* _node) : fs(_fs), node(_node) {} inline FileNode::FileNode(const FileNode& _node) : fs(_node.fs), node(_node.node) {} inline bool FileNode::empty() const { return node == 0; } inline bool FileNode::isNone() const { return type() == NONE; } inline bool FileNode::isSeq() const { return type() == SEQ; } inline bool FileNode::isMap() const { return type() == MAP; } inline bool FileNode::isInt() const { return type() == INT; } inline bool FileNode::isReal() const { return type() == REAL; } inline bool FileNode::isString() const { return type() == STR; } inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; } inline const CvFileNode* FileNode::operator* () const { return node; } inline FileNode::operator int() const { int value; read(*this, value, 0); return value; } inline FileNode::operator float() const { float value; read(*this, value, 0.f); return value; } inline FileNode::operator double() const { double value; read(*this, value, 0.); return value; } inline FileNode::operator String() const { String value; read(*this, value, value); return value; } inline FileNodeIterator FileNode::begin() const { return FileNodeIterator(fs, node); } inline FileNodeIterator FileNode::end() const { return FileNodeIterator(fs, node, size()); } inline void FileNode::readRaw( const String& fmt, uchar* vec, size_t len ) const { begin().readRaw( fmt, vec, len ); } inline FileNode FileNodeIterator::operator *() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); } inline FileNode FileNodeIterator::operator ->() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); } inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, *this); } //! @endcond } // cv #endif // __OPENCV_CORE_PERSISTENCE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/private.cuda.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_PRIVATE_CUDA_HPP__ #define __OPENCV_CORE_PRIVATE_CUDA_HPP__ #ifndef __OPENCV_BUILD # error this is a private header which should not be used from outside of the OpenCV library #endif #include "cvconfig.h" #include "opencv2/core/cvdef.h" #include "opencv2/core/base.hpp" #include "opencv2/core/cuda.hpp" #ifdef HAVE_CUDA # include # include # include # include "opencv2/core/cuda_stream_accessor.hpp" # include "opencv2/core/cuda/common.hpp" # define NPP_VERSION (NPP_VERSION_MAJOR * 1000 + NPP_VERSION_MINOR * 100 + NPP_VERSION_BUILD) # define CUDART_MINIMUM_REQUIRED_VERSION 4020 # if (CUDART_VERSION < CUDART_MINIMUM_REQUIRED_VERSION) # error "Insufficient Cuda Runtime library version, please update it." # endif # if defined(CUDA_ARCH_BIN_OR_PTX_10) # error "OpenCV CUDA module doesn't support NVIDIA compute capability 1.0" # endif #endif //! @cond IGNORED namespace cv { namespace cuda { CV_EXPORTS cv::String getNppErrorMessage(int code); CV_EXPORTS cv::String getCudaDriverApiErrorMessage(int code); CV_EXPORTS GpuMat getInputMat(InputArray _src, Stream& stream); CV_EXPORTS GpuMat getOutputMat(OutputArray _dst, int rows, int cols, int type, Stream& stream); static inline GpuMat getOutputMat(OutputArray _dst, Size size, int type, Stream& stream) { return getOutputMat(_dst, size.height, size.width, type, stream); } CV_EXPORTS void syncOutput(const GpuMat& dst, OutputArray _dst, Stream& stream); }} #ifndef HAVE_CUDA static inline void throw_no_cuda() { CV_Error(cv::Error::GpuNotSupported, "The library is compiled without CUDA support"); } #else // HAVE_CUDA static inline void throw_no_cuda() { CV_Error(cv::Error::StsNotImplemented, "The called functionality is disabled for current build or platform"); } namespace cv { namespace cuda { class CV_EXPORTS BufferPool { public: explicit BufferPool(Stream& stream); GpuMat getBuffer(int rows, int cols, int type); GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); } GpuMat::Allocator* getAllocator() const { return allocator_; } private: GpuMat::Allocator* allocator_; }; static inline void checkNppError(int code, const char* file, const int line, const char* func) { if (code < 0) cv::error(cv::Error::GpuApiCallError, getNppErrorMessage(code), func, file, line); } static inline void checkCudaDriverApiError(int code, const char* file, const int line, const char* func) { if (code != CUDA_SUCCESS) cv::error(cv::Error::GpuApiCallError, getCudaDriverApiErrorMessage(code), func, file, line); } template struct NPPTypeTraits; template<> struct NPPTypeTraits { typedef Npp8u npp_type; }; template<> struct NPPTypeTraits { typedef Npp8s npp_type; }; template<> struct NPPTypeTraits { typedef Npp16u npp_type; }; template<> struct NPPTypeTraits { typedef Npp16s npp_type; }; template<> struct NPPTypeTraits { typedef Npp32s npp_type; }; template<> struct NPPTypeTraits { typedef Npp32f npp_type; }; template<> struct NPPTypeTraits { typedef Npp64f npp_type; }; class NppStreamHandler { public: inline explicit NppStreamHandler(Stream& newStream) { oldStream = nppGetStream(); nppSetStream(StreamAccessor::getStream(newStream)); } inline explicit NppStreamHandler(cudaStream_t newStream) { oldStream = nppGetStream(); nppSetStream(newStream); } inline ~NppStreamHandler() { nppSetStream(oldStream); } private: cudaStream_t oldStream; }; }} #define nppSafeCall(expr) cv::cuda::checkNppError(expr, __FILE__, __LINE__, CV_Func) #define cuSafeCall(expr) cv::cuda::checkCudaDriverApiError(expr, __FILE__, __LINE__, CV_Func) #endif // HAVE_CUDA //! @endcond #endif // __OPENCV_CORE_CUDA_PRIVATE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/private.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_PRIVATE_HPP__ #define __OPENCV_CORE_PRIVATE_HPP__ #ifndef __OPENCV_BUILD # error this is a private header which should not be used from outside of the OpenCV library #endif #include "opencv2/core.hpp" #include "cvconfig.h" #ifdef HAVE_EIGEN # if defined __GNUC__ && defined __APPLE__ # pragma GCC diagnostic ignored "-Wshadow" # endif # include # include "opencv2/core/eigen.hpp" #endif #ifdef HAVE_TBB # include "tbb/tbb_stddef.h" # if TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202 # include "tbb/tbb.h" # include "tbb/task.h" # undef min # undef max # else # undef HAVE_TBB # endif #endif //! @cond IGNORED namespace cv { #ifdef HAVE_TBB typedef tbb::blocked_range BlockedRange; template static inline void parallel_for( const BlockedRange& range, const Body& body ) { tbb::parallel_for(range, body); } typedef tbb::split Split; template static inline void parallel_reduce( const BlockedRange& range, Body& body ) { tbb::parallel_reduce(range, body); } typedef tbb::concurrent_vector ConcurrentRectVector; #else class BlockedRange { public: BlockedRange() : _begin(0), _end(0), _grainsize(0) {} BlockedRange(int b, int e, int g=1) : _begin(b), _end(e), _grainsize(g) {} int begin() const { return _begin; } int end() const { return _end; } int grainsize() const { return _grainsize; } protected: int _begin, _end, _grainsize; }; template static inline void parallel_for( const BlockedRange& range, const Body& body ) { body(range); } typedef std::vector ConcurrentRectVector; class Split {}; template static inline void parallel_reduce( const BlockedRange& range, Body& body ) { body(range); } #endif // Returns a static string if there is a parallel framework, // NULL otherwise. CV_EXPORTS const char* currentParallelFramework(); } //namespace cv /****************************************************************************************\ * Common declarations * \****************************************************************************************/ /* the alignment of all the allocated buffers */ #define CV_MALLOC_ALIGN 16 /* IEEE754 constants and macros */ #define CV_TOGGLE_FLT(x) ((x)^((int)(x) < 0 ? 0x7fffffff : 0)) #define CV_TOGGLE_DBL(x) ((x)^((int64)(x) < 0 ? CV_BIG_INT(0x7fffffffffffffff) : 0)) static inline void* cvAlignPtr( const void* ptr, int align = 32 ) { CV_DbgAssert ( (align & (align-1)) == 0 ); return (void*)( ((size_t)ptr + align - 1) & ~(size_t)(align-1) ); } static inline int cvAlign( int size, int align ) { CV_DbgAssert( (align & (align-1)) == 0 && size < INT_MAX ); return (size + align - 1) & -align; } #ifdef IPL_DEPTH_8U static inline cv::Size cvGetMatSize( const CvMat* mat ) { return cv::Size(mat->cols, mat->rows); } #endif namespace cv { CV_EXPORTS void scalarToRawData(const cv::Scalar& s, void* buf, int type, int unroll_to = 0); } // property implementation macros #define CV_IMPL_PROPERTY_RO(type, name, member) \ inline type get##name() const { return member; } #define CV_HELP_IMPL_PROPERTY(r_type, w_type, name, member) \ CV_IMPL_PROPERTY_RO(r_type, name, member) \ inline void set##name(w_type val) { member = val; } #define CV_HELP_WRAP_PROPERTY(r_type, w_type, name, internal_name, internal_obj) \ r_type get##name() const { return internal_obj.get##internal_name(); } \ void set##name(w_type val) { internal_obj.set##internal_name(val); } #define CV_IMPL_PROPERTY(type, name, member) CV_HELP_IMPL_PROPERTY(type, type, name, member) #define CV_IMPL_PROPERTY_S(type, name, member) CV_HELP_IMPL_PROPERTY(type, const type &, name, member) #define CV_WRAP_PROPERTY(type, name, internal_name, internal_obj) CV_HELP_WRAP_PROPERTY(type, type, name, internal_name, internal_obj) #define CV_WRAP_PROPERTY_S(type, name, internal_name, internal_obj) CV_HELP_WRAP_PROPERTY(type, const type &, name, internal_name, internal_obj) #define CV_WRAP_SAME_PROPERTY(type, name, internal_obj) CV_WRAP_PROPERTY(type, name, name, internal_obj) #define CV_WRAP_SAME_PROPERTY_S(type, name, internal_obj) CV_WRAP_PROPERTY_S(type, name, name, internal_obj) /****************************************************************************************\ * Structures and macros for integration with IPP * \****************************************************************************************/ #ifdef HAVE_IPP #include "ipp.h" #ifndef IPP_VERSION_UPDATE // prior to 7.1 #define IPP_VERSION_UPDATE 0 #endif #define IPP_VERSION_X100 (IPP_VERSION_MAJOR * 100 + IPP_VERSION_MINOR*10 + IPP_VERSION_UPDATE) // General define for ipp function disabling #define IPP_DISABLE_BLOCK 0 #ifdef CV_MALLOC_ALIGN #undef CV_MALLOC_ALIGN #endif #define CV_MALLOC_ALIGN 32 // required for AVX optimization #define setIppErrorStatus() cv::ipp::setIppStatus(-1, CV_Func, __FILE__, __LINE__) static inline IppiSize ippiSize(int width, int height) { IppiSize size = { width, height }; return size; } static inline IppiSize ippiSize(const cv::Size & _size) { IppiSize size = { _size.width, _size.height }; return size; } static inline IppiBorderType ippiGetBorderType(int borderTypeNI) { return borderTypeNI == cv::BORDER_CONSTANT ? ippBorderConst : borderTypeNI == cv::BORDER_WRAP ? ippBorderWrap : borderTypeNI == cv::BORDER_REPLICATE ? ippBorderRepl : borderTypeNI == cv::BORDER_REFLECT_101 ? ippBorderMirror : borderTypeNI == cv::BORDER_REFLECT ? ippBorderMirrorR : (IppiBorderType)-1; } static inline IppDataType ippiGetDataType(int depth) { return depth == CV_8U ? ipp8u : depth == CV_8S ? ipp8s : depth == CV_16U ? ipp16u : depth == CV_16S ? ipp16s : depth == CV_32S ? ipp32s : depth == CV_32F ? ipp32f : depth == CV_64F ? ipp64f : (IppDataType)-1; } // IPP temporary buffer hepler template class IppAutoBuffer { public: IppAutoBuffer() { m_pBuffer = NULL; } IppAutoBuffer(int size) { Alloc(size); } ~IppAutoBuffer() { Release(); } T* Alloc(int size) { m_pBuffer = (T*)ippMalloc(size); return m_pBuffer; } void Release() { if(m_pBuffer) ippFree(m_pBuffer); } inline operator T* () { return (T*)m_pBuffer;} inline operator const T* () const { return (const T*)m_pBuffer;} private: // Disable copy operations IppAutoBuffer(IppAutoBuffer &) {}; IppAutoBuffer& operator =(const IppAutoBuffer &) {return *this;}; T* m_pBuffer; }; #else #define IPP_VERSION_X100 0 #endif // There shoud be no API difference in OpenCV between ICV and IPP since 9.0 #if (defined HAVE_IPP_ICV_ONLY) && IPP_VERSION_X100 >= 900 #undef HAVE_IPP_ICV_ONLY #endif #ifdef HAVE_IPP_ICV_ONLY #define HAVE_ICV 1 #else #define HAVE_ICV 0 #endif #if defined HAVE_IPP #if IPP_VERSION_X100 >= 900 #define IPP_INITIALIZER(FEAT) \ { \ if(FEAT) \ ippSetCpuFeatures(FEAT); \ else \ ippInit(); \ } #elif IPP_VERSION_X100 >= 800 #define IPP_INITIALIZER(FEAT) \ { \ ippInit(); \ } #else #define IPP_INITIALIZER(FEAT) \ { \ ippStaticInit(); \ } #endif #ifdef CVAPI_EXPORTS #define IPP_INITIALIZER_AUTO \ struct __IppInitializer__ \ { \ __IppInitializer__() \ {IPP_INITIALIZER(cv::ipp::getIppFeatures())} \ }; \ static struct __IppInitializer__ __ipp_initializer__; #else #define IPP_INITIALIZER_AUTO #endif #else #define IPP_INITIALIZER #define IPP_INITIALIZER_AUTO #endif #define CV_IPP_CHECK_COND (cv::ipp::useIPP()) #define CV_IPP_CHECK() if(CV_IPP_CHECK_COND) #ifdef HAVE_IPP #ifdef CV_IPP_RUN_VERBOSE #define CV_IPP_RUN_(condition, func, ...) \ { \ if (cv::ipp::useIPP() && (condition) && func) \ { \ printf("%s: IPP implementation is running\n", CV_Func); \ fflush(stdout); \ CV_IMPL_ADD(CV_IMPL_IPP); \ return __VA_ARGS__; \ } \ else \ { \ printf("%s: Plain implementation is running\n", CV_Func); \ fflush(stdout); \ } \ } #elif defined CV_IPP_RUN_ASSERT #define CV_IPP_RUN_(condition, func, ...) \ { \ if (cv::ipp::useIPP() && (condition)) \ { \ if(func) \ { \ CV_IMPL_ADD(CV_IMPL_IPP); \ } \ else \ { \ setIppErrorStatus(); \ CV_Error(cv::Error::StsAssert, #func); \ } \ return __VA_ARGS__; \ } \ } #else #define CV_IPP_RUN_(condition, func, ...) \ if (cv::ipp::useIPP() && (condition) && func) \ { \ CV_IMPL_ADD(CV_IMPL_IPP); \ return __VA_ARGS__; \ } #endif #else #define CV_IPP_RUN_(condition, func, ...) #endif #define CV_IPP_RUN(condition, func, ...) CV_IPP_RUN_(condition, func, __VA_ARGS__) #ifndef IPPI_CALL # define IPPI_CALL(func) CV_Assert((func) >= 0) #endif /* IPP-compatible return codes */ typedef enum CvStatus { CV_BADMEMBLOCK_ERR = -113, CV_INPLACE_NOT_SUPPORTED_ERR= -112, CV_UNMATCHED_ROI_ERR = -111, CV_NOTFOUND_ERR = -110, CV_BADCONVERGENCE_ERR = -109, CV_BADDEPTH_ERR = -107, CV_BADROI_ERR = -106, CV_BADHEADER_ERR = -105, CV_UNMATCHED_FORMATS_ERR = -104, CV_UNSUPPORTED_COI_ERR = -103, CV_UNSUPPORTED_CHANNELS_ERR = -102, CV_UNSUPPORTED_DEPTH_ERR = -101, CV_UNSUPPORTED_FORMAT_ERR = -100, CV_BADARG_ERR = -49, //ipp comp CV_NOTDEFINED_ERR = -48, //ipp comp CV_BADCHANNELS_ERR = -47, //ipp comp CV_BADRANGE_ERR = -44, //ipp comp CV_BADSTEP_ERR = -29, //ipp comp CV_BADFLAG_ERR = -12, CV_DIV_BY_ZERO_ERR = -11, //ipp comp CV_BADCOEF_ERR = -10, CV_BADFACTOR_ERR = -7, CV_BADPOINT_ERR = -6, CV_BADSCALE_ERR = -4, CV_OUTOFMEM_ERR = -3, CV_NULLPTR_ERR = -2, CV_BADSIZE_ERR = -1, CV_NO_ERR = 0, CV_OK = CV_NO_ERR } CvStatus; #ifdef HAVE_TEGRA_OPTIMIZATION namespace tegra { CV_EXPORTS bool useTegra(); CV_EXPORTS void setUseTegra(bool flag); } #endif //! @endcond #endif // __OPENCV_CORE_PRIVATE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/ptr.inl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, NVIDIA Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the copyright holders or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_PTR_INL_HPP__ #define __OPENCV_CORE_PTR_INL_HPP__ #include //! @cond IGNORED namespace cv { template void DefaultDeleter::operator () (Y* p) const { delete p; } namespace detail { struct PtrOwner { PtrOwner() : refCount(1) {} void incRef() { CV_XADD(&refCount, 1); } void decRef() { if (CV_XADD(&refCount, -1) == 1) deleteSelf(); } protected: /* This doesn't really need to be virtual, since PtrOwner is never deleted directly, but it doesn't hurt and it helps avoid warnings. */ virtual ~PtrOwner() {} virtual void deleteSelf() = 0; private: unsigned int refCount; // noncopyable PtrOwner(const PtrOwner&); PtrOwner& operator = (const PtrOwner&); }; template struct PtrOwnerImpl : PtrOwner { PtrOwnerImpl(Y* p, D d) : owned(p), deleter(d) {} void deleteSelf() { deleter(owned); delete this; } private: Y* owned; D deleter; }; } template Ptr::Ptr() : owner(NULL), stored(NULL) {} template template Ptr::Ptr(Y* p) : owner(p ? new detail::PtrOwnerImpl >(p, DefaultDeleter()) : NULL), stored(p) {} template template Ptr::Ptr(Y* p, D d) : owner(p ? new detail::PtrOwnerImpl(p, d) : NULL), stored(p) {} template Ptr::Ptr(const Ptr& o) : owner(o.owner), stored(o.stored) { if (owner) owner->incRef(); } template template Ptr::Ptr(const Ptr& o) : owner(o.owner), stored(o.stored) { if (owner) owner->incRef(); } template template Ptr::Ptr(const Ptr& o, T* p) : owner(o.owner), stored(p) { if (owner) owner->incRef(); } template Ptr::~Ptr() { release(); } template Ptr& Ptr::operator = (const Ptr& o) { Ptr(o).swap(*this); return *this; } template template Ptr& Ptr::operator = (const Ptr& o) { Ptr(o).swap(*this); return *this; } template void Ptr::release() { if (owner) owner->decRef(); owner = NULL; stored = NULL; } template template void Ptr::reset(Y* p) { Ptr(p).swap(*this); } template template void Ptr::reset(Y* p, D d) { Ptr(p, d).swap(*this); } template void Ptr::swap(Ptr& o) { std::swap(owner, o.owner); std::swap(stored, o.stored); } template T* Ptr::get() const { return stored; } template typename detail::RefOrVoid::type Ptr::operator * () const { return *stored; } template T* Ptr::operator -> () const { return stored; } template Ptr::operator T* () const { return stored; } template bool Ptr::empty() const { return !stored; } template template Ptr Ptr::staticCast() const { return Ptr(*this, static_cast(stored)); } template template Ptr Ptr::constCast() const { return Ptr(*this, const_cast(stored)); } template template Ptr Ptr::dynamicCast() const { return Ptr(*this, dynamic_cast(stored)); } #ifdef CV_CXX_MOVE_SEMANTICS template Ptr::Ptr(Ptr&& o) : owner(o.owner), stored(o.stored) { o.owner = NULL; o.stored = NULL; } template Ptr& Ptr::operator = (Ptr&& o) { release(); owner = o.owner; stored = o.stored; o.owner = NULL; o.stored = NULL; return *this; } #endif template void swap(Ptr& ptr1, Ptr& ptr2){ ptr1.swap(ptr2); } template bool operator == (const Ptr& ptr1, const Ptr& ptr2) { return ptr1.get() == ptr2.get(); } template bool operator != (const Ptr& ptr1, const Ptr& ptr2) { return ptr1.get() != ptr2.get(); } template Ptr makePtr() { return Ptr(new T()); } template Ptr makePtr(const A1& a1) { return Ptr(new T(a1)); } template Ptr makePtr(const A1& a1, const A2& a2) { return Ptr(new T(a1, a2)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3) { return Ptr(new T(a1, a2, a3)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4) { return Ptr(new T(a1, a2, a3, a4)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) { return Ptr(new T(a1, a2, a3, a4, a5)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) { return Ptr(new T(a1, a2, a3, a4, a5, a6)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) { return Ptr(new T(a1, a2, a3, a4, a5, a6, a7)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8) { return Ptr(new T(a1, a2, a3, a4, a5, a6, a7, a8)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9) { return Ptr(new T(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } template Ptr makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10) { return Ptr(new T(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } } // namespace cv //! @endcond #endif // __OPENCV_CORE_PTR_INL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/saturate.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2014, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_SATURATE_HPP__ #define __OPENCV_CORE_SATURATE_HPP__ #include "opencv2/core/cvdef.h" #include "opencv2/core/fast_math.hpp" namespace cv { //! @addtogroup core_utils //! @{ /////////////// saturate_cast (used in image & signal processing) /////////////////// /** @brief Template function for accurate conversion from one primitive type to another. The functions saturate_cast resemble the standard C++ cast operations, such as static_cast\() and others. They perform an efficient and accurate conversion from one primitive type to another (see the introduction chapter). saturate in the name means that when the input value v is out of the range of the target type, the result is not formed just by taking low bits of the input, but instead the value is clipped. For example: @code uchar a = saturate_cast(-100); // a = 0 (UCHAR_MIN) short b = saturate_cast(33333.33333); // b = 32767 (SHRT_MAX) @endcode Such clipping is done when the target type is unsigned char , signed char , unsigned short or signed short . For 32-bit integers, no clipping is done. When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), the floating-point value is first rounded to the nearest integer and then clipped if needed (when the target type is 8- or 16-bit). This operation is used in the simplest or most complex image processing functions in OpenCV. @param v Function parameter. @sa add, subtract, multiply, divide, Mat::convertTo */ template static inline _Tp saturate_cast(uchar v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(schar v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(ushort v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(short v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(unsigned v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(int v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(float v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(double v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(int64 v) { return _Tp(v); } /** @overload */ template static inline _Tp saturate_cast(uint64 v) { return _Tp(v); } template<> inline uchar saturate_cast(schar v) { return (uchar)std::max((int)v, 0); } template<> inline uchar saturate_cast(ushort v) { return (uchar)std::min((unsigned)v, (unsigned)UCHAR_MAX); } template<> inline uchar saturate_cast(int v) { return (uchar)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } template<> inline uchar saturate_cast(short v) { return saturate_cast((int)v); } template<> inline uchar saturate_cast(unsigned v) { return (uchar)std::min(v, (unsigned)UCHAR_MAX); } template<> inline uchar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline uchar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline uchar saturate_cast(int64 v) { return (uchar)((uint64)v <= (uint64)UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } template<> inline uchar saturate_cast(uint64 v) { return (uchar)std::min(v, (uint64)UCHAR_MAX); } template<> inline schar saturate_cast(uchar v) { return (schar)std::min((int)v, SCHAR_MAX); } template<> inline schar saturate_cast(ushort v) { return (schar)std::min((unsigned)v, (unsigned)SCHAR_MAX); } template<> inline schar saturate_cast(int v) { return (schar)((unsigned)(v-SCHAR_MIN) <= (unsigned)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } template<> inline schar saturate_cast(short v) { return saturate_cast((int)v); } template<> inline schar saturate_cast(unsigned v) { return (schar)std::min(v, (unsigned)SCHAR_MAX); } template<> inline schar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline schar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline schar saturate_cast(int64 v) { return (schar)((uint64)((int64)v-SCHAR_MIN) <= (uint64)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } template<> inline schar saturate_cast(uint64 v) { return (schar)std::min(v, (uint64)SCHAR_MAX); } template<> inline ushort saturate_cast(schar v) { return (ushort)std::max((int)v, 0); } template<> inline ushort saturate_cast(short v) { return (ushort)std::max((int)v, 0); } template<> inline ushort saturate_cast(int v) { return (ushort)((unsigned)v <= (unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } template<> inline ushort saturate_cast(unsigned v) { return (ushort)std::min(v, (unsigned)USHRT_MAX); } template<> inline ushort saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline ushort saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline ushort saturate_cast(int64 v) { return (ushort)((uint64)v <= (uint64)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } template<> inline ushort saturate_cast(uint64 v) { return (ushort)std::min(v, (uint64)USHRT_MAX); } template<> inline short saturate_cast(ushort v) { return (short)std::min((int)v, SHRT_MAX); } template<> inline short saturate_cast(int v) { return (short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } template<> inline short saturate_cast(unsigned v) { return (short)std::min(v, (unsigned)SHRT_MAX); } template<> inline short saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline short saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } template<> inline short saturate_cast(int64 v) { return (short)((uint64)((int64)v - SHRT_MIN) <= (uint64)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } template<> inline short saturate_cast(uint64 v) { return (short)std::min(v, (uint64)SHRT_MAX); } template<> inline int saturate_cast(float v) { return cvRound(v); } template<> inline int saturate_cast(double v) { return cvRound(v); } // we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. template<> inline unsigned saturate_cast(float v) { return cvRound(v); } template<> inline unsigned saturate_cast(double v) { return cvRound(v); } //! @} } // cv #endif // __OPENCV_CORE_SATURATE_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/sse_utils.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_SSE_UTILS_HPP__ #define __OPENCV_CORE_SSE_UTILS_HPP__ #ifndef __cplusplus # error sse_utils.hpp header must be compiled as C++ #endif #include "opencv2/core/cvdef.h" //! @addtogroup core_utils_sse //! @{ #if CV_SSE2 inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) { __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g0); __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g0); __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_g1); __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_g1); __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk2); __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk2); __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk3); __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk3); __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk2); __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk2); __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk3); __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk3); __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk2); __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk2); __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk3); __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk3); v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk2); v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk2); v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk3); v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk3); } inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) { __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g1); __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g1); __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b0); __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b0); __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_b1); __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_b1); __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk3); __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk3); __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk4); __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk4); __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk5); __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk5); __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk3); __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk3); __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk4); __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk4); __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk5); __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk5); __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk3); __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk3); __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk4); __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk4); __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk5); __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk5); v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk3); v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk3); v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk4); v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk4); v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk5); v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk5); } inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) { __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_b0); __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_b0); __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b1); __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b1); __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_a0); __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_a0); __m128i layer1_chunk6 = _mm_unpacklo_epi8(v_g1, v_a1); __m128i layer1_chunk7 = _mm_unpackhi_epi8(v_g1, v_a1); __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk4); __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk4); __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk5); __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk5); __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk6); __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk6); __m128i layer2_chunk6 = _mm_unpacklo_epi8(layer1_chunk3, layer1_chunk7); __m128i layer2_chunk7 = _mm_unpackhi_epi8(layer1_chunk3, layer1_chunk7); __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk4); __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk4); __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk5); __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk5); __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk6); __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk6); __m128i layer3_chunk6 = _mm_unpacklo_epi8(layer2_chunk3, layer2_chunk7); __m128i layer3_chunk7 = _mm_unpackhi_epi8(layer2_chunk3, layer2_chunk7); __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk4); __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk4); __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk5); __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk5); __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk6); __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk6); __m128i layer4_chunk6 = _mm_unpacklo_epi8(layer3_chunk3, layer3_chunk7); __m128i layer4_chunk7 = _mm_unpackhi_epi8(layer3_chunk3, layer3_chunk7); v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk4); v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk4); v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk5); v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk5); v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk6); v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk6); v_a0 = _mm_unpacklo_epi8(layer4_chunk3, layer4_chunk7); v_a1 = _mm_unpackhi_epi8(layer4_chunk3, layer4_chunk7); } inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) { __m128i v_mask = _mm_set1_epi16(0x00ff); __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); __m128i layer4_chunk2 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); __m128i layer3_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); __m128i layer2_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); __m128i layer1_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); v_g0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); } inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) { __m128i v_mask = _mm_set1_epi16(0x00ff); __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); } inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) { __m128i v_mask = _mm_set1_epi16(0x00ff); __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); __m128i layer4_chunk6 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); __m128i layer4_chunk3 = _mm_packus_epi16(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); __m128i layer4_chunk7 = _mm_packus_epi16(_mm_srli_epi16(v_a0, 8), _mm_srli_epi16(v_a1, 8)); __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); __m128i layer3_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); __m128i layer3_chunk3 = _mm_packus_epi16(_mm_and_si128(layer4_chunk6, v_mask), _mm_and_si128(layer4_chunk7, v_mask)); __m128i layer3_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk6, 8), _mm_srli_epi16(layer4_chunk7, 8)); __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); __m128i layer2_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); __m128i layer2_chunk3 = _mm_packus_epi16(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); __m128i layer2_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk6, 8), _mm_srli_epi16(layer3_chunk7, 8)); __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); __m128i layer1_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); __m128i layer1_chunk3 = _mm_packus_epi16(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); __m128i layer1_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk6, 8), _mm_srli_epi16(layer2_chunk7, 8)); v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); v_a0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); v_g1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); v_a1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk6, 8), _mm_srli_epi16(layer1_chunk7, 8)); } inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) { __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g0); __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g0); __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_g1); __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_g1); __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk2); __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk2); __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk3); __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk3); __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk2); __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk2); __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk3); __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk3); v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk2); v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk2); v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk3); v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk3); } inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) { __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g1); __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g1); __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b0); __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b0); __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_b1); __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_b1); __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk3); __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk3); __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk4); __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk4); __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk5); __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk5); __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk3); __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk3); __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk4); __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk4); __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk5); __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk5); v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk3); v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk3); v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk4); v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk4); v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk5); v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk5); } inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) { __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_b0); __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_b0); __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b1); __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b1); __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_a0); __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_a0); __m128i layer1_chunk6 = _mm_unpacklo_epi16(v_g1, v_a1); __m128i layer1_chunk7 = _mm_unpackhi_epi16(v_g1, v_a1); __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk4); __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk4); __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk5); __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk5); __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk6); __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk6); __m128i layer2_chunk6 = _mm_unpacklo_epi16(layer1_chunk3, layer1_chunk7); __m128i layer2_chunk7 = _mm_unpackhi_epi16(layer1_chunk3, layer1_chunk7); __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk4); __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk4); __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk5); __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk5); __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk6); __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk6); __m128i layer3_chunk6 = _mm_unpacklo_epi16(layer2_chunk3, layer2_chunk7); __m128i layer3_chunk7 = _mm_unpackhi_epi16(layer2_chunk3, layer2_chunk7); v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk4); v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk4); v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk5); v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk5); v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk6); v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk6); v_a0 = _mm_unpacklo_epi16(layer3_chunk3, layer3_chunk7); v_a1 = _mm_unpackhi_epi16(layer3_chunk3, layer3_chunk7); } #if CV_SSE4_1 inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) { __m128i v_mask = _mm_set1_epi32(0x0000ffff); __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); __m128i layer3_chunk2 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); __m128i layer2_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); __m128i layer1_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); v_g0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); } inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) { __m128i v_mask = _mm_set1_epi32(0x0000ffff); __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); } inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) { __m128i v_mask = _mm_set1_epi32(0x0000ffff); __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); __m128i layer3_chunk6 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); __m128i layer3_chunk3 = _mm_packus_epi32(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); __m128i layer3_chunk7 = _mm_packus_epi32(_mm_srli_epi32(v_a0, 16), _mm_srli_epi32(v_a1, 16)); __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); __m128i layer2_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); __m128i layer2_chunk3 = _mm_packus_epi32(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); __m128i layer2_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk6, 16), _mm_srli_epi32(layer3_chunk7, 16)); __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); __m128i layer1_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); __m128i layer1_chunk3 = _mm_packus_epi32(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); __m128i layer1_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk6, 16), _mm_srli_epi32(layer2_chunk7, 16)); v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); v_a0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); v_g1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); v_a1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk6, 16), _mm_srli_epi32(layer1_chunk7, 16)); } #endif // CV_SSE4_1 inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) { __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g0); __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g0); __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_g1); __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_g1); __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk2); __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk2); __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk3); __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk3); v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk2); v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk2); v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk3); v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk3); } inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) { __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g1); __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g1); __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b0); __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b0); __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_b1); __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_b1); __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk3); __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk3); __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk4); __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk4); __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk5); __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk5); v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk3); v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk3); v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk4); v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk4); v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk5); v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk5); } inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) { __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_b0); __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_b0); __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b1); __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b1); __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_a0); __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_a0); __m128 layer1_chunk6 = _mm_unpacklo_ps(v_g1, v_a1); __m128 layer1_chunk7 = _mm_unpackhi_ps(v_g1, v_a1); __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk4); __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk4); __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk5); __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk5); __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk6); __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk6); __m128 layer2_chunk6 = _mm_unpacklo_ps(layer1_chunk3, layer1_chunk7); __m128 layer2_chunk7 = _mm_unpackhi_ps(layer1_chunk3, layer1_chunk7); v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk4); v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk4); v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk5); v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk5); v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk6); v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk6); v_a0 = _mm_unpacklo_ps(layer2_chunk3, layer2_chunk7); v_a1 = _mm_unpackhi_ps(layer2_chunk3, layer2_chunk7); } inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) { const int mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1); __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); __m128 layer2_chunk2 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); __m128 layer2_chunk3 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); v_g0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); v_g1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); } inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) { const int mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1); __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); __m128 layer2_chunk3 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); __m128 layer2_chunk4 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); __m128 layer2_chunk5 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); v_g1 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); v_b0 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); v_b1 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); } inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) { const int mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1); __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); __m128 layer2_chunk4 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); __m128 layer2_chunk5 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); __m128 layer2_chunk6 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); __m128 layer2_chunk3 = _mm_shuffle_ps(v_a0, v_a1, mask_lo); __m128 layer2_chunk7 = _mm_shuffle_ps(v_a0, v_a1, mask_hi); __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); __m128 layer1_chunk6 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_lo); __m128 layer1_chunk7 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_hi); v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); v_b0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); v_b1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); v_a0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); v_g1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_lo); v_a1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_hi); } #endif // CV_SSE2 //! @} #endif //__OPENCV_CORE_SSE_UTILS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/traits.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_TRAITS_HPP__ #define __OPENCV_CORE_TRAITS_HPP__ #include "opencv2/core/cvdef.h" namespace cv { //! @addtogroup core_basic //! @{ /** @brief Template "trait" class for OpenCV primitive data types. A primitive OpenCV data type is one of unsigned char, bool, signed char, unsigned short, signed short, int, float, double, or a tuple of values of one of these types, where all the values in the tuple have the same type. Any primitive type from the list can be defined by an identifier in the form CV_\{U|S|F}C(\), for example: uchar \~ CV_8UC1, 3-element floating-point tuple \~ CV_32FC3, and so on. A universal OpenCV structure that is able to store a single instance of such a primitive data type is Vec. Multiple instances of such a type can be stored in a std::vector, Mat, Mat_, SparseMat, SparseMat_, or any other container that is able to store Vec instances. The DataType class is basically used to provide a description of such primitive data types without adding any fields or methods to the corresponding classes (and it is actually impossible to add anything to primitive C/C++ data types). This technique is known in C++ as class traits. It is not DataType itself that is used but its specialized versions, such as: @code template<> class DataType { typedef uchar value_type; typedef int work_type; typedef uchar channel_type; enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U }; }; ... template DataType > { typedef std::complex<_Tp> value_type; typedef std::complex<_Tp> work_type; typedef _Tp channel_type; // DataDepth is another helper trait class enum { depth = DataDepth<_Tp>::value, channels=2, fmt=(channels-1)*256+DataDepth<_Tp>::fmt, type=CV_MAKETYPE(depth, channels) }; }; ... @endcode The main purpose of this class is to convert compilation-time type information to an OpenCV-compatible data type identifier, for example: @code // allocates a 30x40 floating-point matrix Mat A(30, 40, DataType::type); Mat B = Mat_ >(3, 3); // the statement below will print 6, 2 , that is depth == CV_64F, channels == 2 cout << B.depth() << ", " << B.channels() << endl; @endcode So, such traits are used to tell OpenCV which data type you are working with, even if such a type is not native to OpenCV. For example, the matrix B initialization above is compiled because OpenCV defines the proper specialized template class DataType\ \> . This mechanism is also useful (and used in OpenCV this way) for generic algorithms implementations. */ template class DataType { public: typedef _Tp value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 1, depth = -1, channels = 1, fmt = 0, type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef bool value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8U, channels = 1, fmt = (int)'u', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef uchar value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8U, channels = 1, fmt = (int)'u', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef schar value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8S, channels = 1, fmt = (int)'c', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef schar value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8S, channels = 1, fmt = (int)'c', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef ushort value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_16U, channels = 1, fmt = (int)'w', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef short value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_16S, channels = 1, fmt = (int)'s', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef int value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_32S, channels = 1, fmt = (int)'i', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef float value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_32F, channels = 1, fmt = (int)'f', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType { public: typedef double value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_64F, channels = 1, fmt = (int)'d', type = CV_MAKETYPE(depth, channels) }; }; /** @brief A helper class for cv::DataType The class is specialized for each fundamental numerical data type supported by OpenCV. It provides DataDepth::value constant. */ template class DataDepth { public: enum { value = DataType<_Tp>::depth, fmt = DataType<_Tp>::fmt }; }; template class TypeDepth { enum { depth = CV_USRTYPE1 }; typedef void value_type; }; template<> class TypeDepth { enum { depth = CV_8U }; typedef uchar value_type; }; template<> class TypeDepth { enum { depth = CV_8S }; typedef schar value_type; }; template<> class TypeDepth { enum { depth = CV_16U }; typedef ushort value_type; }; template<> class TypeDepth { enum { depth = CV_16S }; typedef short value_type; }; template<> class TypeDepth { enum { depth = CV_32S }; typedef int value_type; }; template<> class TypeDepth { enum { depth = CV_32F }; typedef float value_type; }; template<> class TypeDepth { enum { depth = CV_64F }; typedef double value_type; }; //! @} } // cv #endif // __OPENCV_CORE_TRAITS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/types.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_TYPES_HPP__ #define __OPENCV_CORE_TYPES_HPP__ #ifndef __cplusplus # error types.hpp header must be compiled as C++ #endif #include #include #include #include "opencv2/core/cvdef.h" #include "opencv2/core/cvstd.hpp" #include "opencv2/core/matx.hpp" namespace cv { //! @addtogroup core_basic //! @{ //////////////////////////////// Complex ////////////////////////////// /** @brief A complex number class. The template class is similar and compatible with std::complex, however it provides slightly more convenient access to the real and imaginary parts using through the simple field access, as opposite to std::complex::real() and std::complex::imag(). */ template class Complex { public: //! constructors Complex(); Complex( _Tp _re, _Tp _im = 0 ); //! conversion to another data type template operator Complex() const; //! conjugation Complex conj() const; _Tp re, im; //< the real and the imaginary parts }; typedef Complex Complexf; typedef Complex Complexd; template class DataType< Complex<_Tp> > { public: typedef Complex<_Tp> value_type; typedef value_type work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 2, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //////////////////////////////// Point_ //////////////////////////////// /** @brief Template class for 2D points specified by its coordinates `x` and `y`. An instance of the class is interchangeable with C structures, CvPoint and CvPoint2D32f . There is also a cast operator to convert point coordinates to the specified type. The conversion from floating-point coordinates to integer coordinates is done by rounding. Commonly, the conversion uses this operation for each of the coordinates. Besides the class members listed in the declaration above, the following operations on points are implemented: @code pt1 = pt2 + pt3; pt1 = pt2 - pt3; pt1 = pt2 * a; pt1 = a * pt2; pt1 = pt2 / a; pt1 += pt2; pt1 -= pt2; pt1 *= a; pt1 /= a; double value = norm(pt); // L2 norm pt1 == pt2; pt1 != pt2; @endcode For your convenience, the following type aliases are defined: @code typedef Point_ Point2i; typedef Point2i Point; typedef Point_ Point2f; typedef Point_ Point2d; @endcode Example: @code Point2f a(0.3f, 0.f), b(0.f, 0.4f); Point pt = (a + b)*10.f; cout << pt.x << ", " << pt.y << endl; @endcode */ template class Point_ { public: typedef _Tp value_type; // various constructors Point_(); Point_(_Tp _x, _Tp _y); Point_(const Point_& pt); Point_(const Size_<_Tp>& sz); Point_(const Vec<_Tp, 2>& v); Point_& operator = (const Point_& pt); //! conversion to another data type template operator Point_<_Tp2>() const; //! conversion to the old-style C structures operator Vec<_Tp, 2>() const; //! dot product _Tp dot(const Point_& pt) const; //! dot product computed in double-precision arithmetics double ddot(const Point_& pt) const; //! cross-product double cross(const Point_& pt) const; //! checks whether the point is inside the specified rectangle bool inside(const Rect_<_Tp>& r) const; _Tp x, y; //< the point coordinates }; typedef Point_ Point2i; typedef Point_ Point2f; typedef Point_ Point2d; typedef Point2i Point; template class DataType< Point_<_Tp> > { public: typedef Point_<_Tp> value_type; typedef Point_::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 2, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //////////////////////////////// Point3_ //////////////////////////////// /** @brief Template class for 3D points specified by its coordinates `x`, `y` and `z`. An instance of the class is interchangeable with the C structure CvPoint2D32f . Similarly to Point_ , the coordinates of 3D points can be converted to another type. The vector arithmetic and comparison operations are also supported. The following Point3_\<\> aliases are available: @code typedef Point3_ Point3i; typedef Point3_ Point3f; typedef Point3_ Point3d; @endcode @see cv::Point3i, cv::Point3f and cv::Point3d */ template class Point3_ { public: typedef _Tp value_type; // various constructors Point3_(); Point3_(_Tp _x, _Tp _y, _Tp _z); Point3_(const Point3_& pt); explicit Point3_(const Point_<_Tp>& pt); Point3_(const Vec<_Tp, 3>& v); Point3_& operator = (const Point3_& pt); //! conversion to another data type template operator Point3_<_Tp2>() const; //! conversion to cv::Vec<> operator Vec<_Tp, 3>() const; //! dot product _Tp dot(const Point3_& pt) const; //! dot product computed in double-precision arithmetics double ddot(const Point3_& pt) const; //! cross product of the 2 3D points Point3_ cross(const Point3_& pt) const; _Tp x, y, z; //< the point coordinates }; typedef Point3_ Point3i; typedef Point3_ Point3f; typedef Point3_ Point3d; template class DataType< Point3_<_Tp> > { public: typedef Point3_<_Tp> value_type; typedef Point3_::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 3, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //////////////////////////////// Size_ //////////////////////////////// /** @brief Template class for specifying the size of an image or rectangle. The class includes two members called width and height. The structure can be converted to and from the old OpenCV structures CvSize and CvSize2D32f . The same set of arithmetic and comparison operations as for Point_ is available. OpenCV defines the following Size_\<\> aliases: @code typedef Size_ Size2i; typedef Size2i Size; typedef Size_ Size2f; @endcode */ template class Size_ { public: typedef _Tp value_type; //! various constructors Size_(); Size_(_Tp _width, _Tp _height); Size_(const Size_& sz); Size_(const Point_<_Tp>& pt); Size_& operator = (const Size_& sz); //! the area (width*height) _Tp area() const; //! conversion of another data type. template operator Size_<_Tp2>() const; _Tp width, height; // the width and the height }; typedef Size_ Size2i; typedef Size_ Size2f; typedef Size_ Size2d; typedef Size2i Size; template class DataType< Size_<_Tp> > { public: typedef Size_<_Tp> value_type; typedef Size_::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 2, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //////////////////////////////// Rect_ //////////////////////////////// /** @brief Template class for 2D rectangles described by the following parameters: - Coordinates of the top-left corner. This is a default interpretation of Rect_::x and Rect_::y in OpenCV. Though, in your algorithms you may count x and y from the bottom-left corner. - Rectangle width and height. OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the right and bottom boundaries are not. For example, the method Rect_::contains returns true if \f[x \leq pt.x < x+width, y \leq pt.y < y+height\f] Virtually every loop over an image ROI in OpenCV (where ROI is specified by Rect_\ ) is implemented as: @code for(int y = roi.y; y < roi.y + roi.height; y++) for(int x = roi.x; x < roi.x + roi.width; x++) { // ... } @endcode In addition to the class members, the following operations on rectangles are implemented: - \f$\texttt{rect} = \texttt{rect} \pm \texttt{point}\f$ (shifting a rectangle by a certain offset) - \f$\texttt{rect} = \texttt{rect} \pm \texttt{size}\f$ (expanding or shrinking a rectangle by a certain amount) - rect += point, rect -= point, rect += size, rect -= size (augmenting operations) - rect = rect1 & rect2 (rectangle intersection) - rect = rect1 | rect2 (minimum area rectangle containing rect1 and rect2 ) - rect &= rect1, rect |= rect1 (and the corresponding augmenting operations) - rect == rect1, rect != rect1 (rectangle comparison) This is an example how the partial ordering on rectangles can be established (rect1 \f$\subseteq\f$ rect2): @code template inline bool operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2) { return (r1 & r2) == r1; } @endcode For your convenience, the Rect_\<\> alias is available: cv::Rect */ template class Rect_ { public: typedef _Tp value_type; //! various constructors Rect_(); Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); Rect_(const Rect_& r); Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); Rect_& operator = ( const Rect_& r ); //! the top-left corner Point_<_Tp> tl() const; //! the bottom-right corner Point_<_Tp> br() const; //! size (width, height) of the rectangle Size_<_Tp> size() const; //! area (width*height) of the rectangle _Tp area() const; //! conversion to another data type template operator Rect_<_Tp2>() const; //! checks whether the rectangle contains the point bool contains(const Point_<_Tp>& pt) const; _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle }; typedef Rect_ Rect2i; typedef Rect_ Rect2f; typedef Rect_ Rect2d; typedef Rect2i Rect; template class DataType< Rect_<_Tp> > { public: typedef Rect_<_Tp> value_type; typedef Rect_::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 4, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; ///////////////////////////// RotatedRect ///////////////////////////// /** @brief The class represents rotated (i.e. not up-right) rectangles on a plane. Each rectangle is specified by the center point (mass center), length of each side (represented by cv::Size2f structure) and the rotation angle in degrees. The sample below demonstrates how to use RotatedRect: @code Mat image(200, 200, CV_8UC3, Scalar(0)); RotatedRect rRect = RotatedRect(Point2f(100,100), Size2f(100,50), 30); Point2f vertices[4]; rRect.points(vertices); for (int i = 0; i < 4; i++) line(image, vertices[i], vertices[(i+1)%4], Scalar(0,255,0)); Rect brect = rRect.boundingRect(); rectangle(image, brect, Scalar(255,0,0)); imshow("rectangles", image); waitKey(0); @endcode ![image](pics/rotatedrect.png) @sa CamShift, fitEllipse, minAreaRect, CvBox2D */ class CV_EXPORTS RotatedRect { public: //! various constructors RotatedRect(); /** @param center The rectangle mass center. @param size Width and height of the rectangle. @param angle The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. */ RotatedRect(const Point2f& center, const Size2f& size, float angle); /** Any 3 end points of the RotatedRect. They must be given in order (either clockwise or anticlockwise). */ RotatedRect(const Point2f& point1, const Point2f& point2, const Point2f& point3); /** returns 4 vertices of the rectangle @param pts The points array for storing rectangle vertices. */ void points(Point2f pts[]) const; //! returns the minimal up-right rectangle containing the rotated rectangle Rect boundingRect() const; Point2f center; //< the rectangle mass center Size2f size; //< width and height of the rectangle float angle; //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. }; template<> class DataType< RotatedRect > { public: typedef RotatedRect value_type; typedef value_type work_type; typedef float channel_type; enum { generic_type = 0, depth = DataType::depth, channels = (int)sizeof(value_type)/sizeof(channel_type), // 5 fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //////////////////////////////// Range ///////////////////////////////// /** @brief Template class specifying a continuous subsequence (slice) of a sequence. The class is used to specify a row or a column span in a matrix ( Mat ) and for many other purposes. Range(a,b) is basically the same as a:b in Matlab or a..b in Python. As in Python, start is an inclusive left boundary of the range and end is an exclusive right boundary of the range. Such a half-opened interval is usually denoted as \f$[start,end)\f$ . The static method Range::all() returns a special variable that means "the whole sequence" or "the whole range", just like " : " in Matlab or " ... " in Python. All the methods and functions in OpenCV that take Range support this special Range::all() value. But, of course, in case of your own custom processing, you will probably have to check and handle it explicitly: @code void my_function(..., const Range& r, ....) { if(r == Range::all()) { // process all the data } else { // process [r.start, r.end) } } @endcode */ class CV_EXPORTS Range { public: Range(); Range(int _start, int _end); int size() const; bool empty() const; static Range all(); int start, end; }; template<> class DataType { public: typedef Range value_type; typedef value_type work_type; typedef int channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 2, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //////////////////////////////// Scalar_ /////////////////////////////// /** @brief Template class for a 4-element vector derived from Vec. Being derived from Vec\<_Tp, 4\> , Scalar_ and Scalar can be used just as typical 4-element vectors. In addition, they can be converted to/from CvScalar . The type Scalar is widely used in OpenCV to pass pixel values. */ template class Scalar_ : public Vec<_Tp, 4> { public: //! various constructors Scalar_(); Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); Scalar_(_Tp v0); template Scalar_(const Vec<_Tp2, cn>& v); //! returns a scalar with all elements set to v0 static Scalar_<_Tp> all(_Tp v0); //! conversion to another data type template operator Scalar_() const; //! per-element product Scalar_<_Tp> mul(const Scalar_<_Tp>& a, double scale=1 ) const; // returns (v0, -v1, -v2, -v3) Scalar_<_Tp> conj() const; // returns true iff v1 == v2 == v3 == 0 bool isReal() const; }; typedef Scalar_ Scalar; template class DataType< Scalar_<_Tp> > { public: typedef Scalar_<_Tp> value_type; typedef Scalar_::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, depth = DataType::depth, channels = 4, fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; /////////////////////////////// KeyPoint //////////////////////////////// /** @brief Data structure for salient point detectors. The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint detectors, such as Harris corner detector, cv::FAST, cv::StarDetector, cv::SURF, cv::SIFT, cv::LDetector etc. The keypoint is characterized by the 2D position, scale (proportional to the diameter of the neighborhood that needs to be taken into account), orientation and some other parameters. The keypoint neighborhood is then analyzed by another algorithm that builds a descriptor (usually represented as a feature vector). The keypoints representing the same object in different images can then be matched using cv::KDTree or another method. */ class CV_EXPORTS_W_SIMPLE KeyPoint { public: //! the default constructor CV_WRAP KeyPoint(); /** @param _pt x & y coordinates of the keypoint @param _size keypoint diameter @param _angle keypoint orientation @param _response keypoint detector response on the keypoint (that is, strength of the keypoint) @param _octave pyramid octave in which the keypoint has been detected @param _class_id object id */ KeyPoint(Point2f _pt, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1); /** @param x x-coordinate of the keypoint @param y y-coordinate of the keypoint @param _size keypoint diameter @param _angle keypoint orientation @param _response keypoint detector response on the keypoint (that is, strength of the keypoint) @param _octave pyramid octave in which the keypoint has been detected @param _class_id object id */ CV_WRAP KeyPoint(float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1); size_t hash() const; /** This method converts vector of keypoints to vector of points or the reverse, where each keypoint is assigned the same size and the same orientation. @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB @param points2f Array of (x,y) coordinates of each keypoint @param keypointIndexes Array of indexes of keypoints to be converted to points. (Acts like a mask to convert only specified keypoints) */ CV_WRAP static void convert(const std::vector& keypoints, CV_OUT std::vector& points2f, const std::vector& keypointIndexes=std::vector()); /** @overload @param points2f Array of (x,y) coordinates of each keypoint @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB @param size keypoint diameter @param response keypoint detector response on the keypoint (that is, strength of the keypoint) @param octave pyramid octave in which the keypoint has been detected @param class_id object id */ CV_WRAP static void convert(const std::vector& points2f, CV_OUT std::vector& keypoints, float size=1, float response=1, int octave=0, int class_id=-1); /** This method computes overlap for pair of keypoints. Overlap is the ratio between area of keypoint regions' intersection and area of keypoint regions' union (considering keypoint region as circle). If they don't overlap, we get zero. If they coincide at same location with same size, we get 1. @param kp1 First keypoint @param kp2 Second keypoint */ CV_WRAP static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); CV_PROP_RW Point2f pt; //!< coordinates of the keypoints CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable); //!< it's in [0,360) degrees and measured relative to //!< image coordinate system, ie in clockwise. CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) }; template<> class DataType { public: typedef KeyPoint value_type; typedef float work_type; typedef float channel_type; enum { generic_type = 0, depth = DataType::depth, channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 7 fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //////////////////////////////// DMatch ///////////////////////////////// /** @brief Class for matching keypoint descriptors query descriptor index, train descriptor index, train image index, and distance between descriptors. */ class CV_EXPORTS_W_SIMPLE DMatch { public: CV_WRAP DMatch(); CV_WRAP DMatch(int _queryIdx, int _trainIdx, float _distance); CV_WRAP DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance); CV_PROP_RW int queryIdx; // query descriptor index CV_PROP_RW int trainIdx; // train descriptor index CV_PROP_RW int imgIdx; // train image index CV_PROP_RW float distance; // less is better bool operator<(const DMatch &m) const; }; template<> class DataType { public: typedef DMatch value_type; typedef int work_type; typedef int channel_type; enum { generic_type = 0, depth = DataType::depth, channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 4 fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; ///////////////////////////// TermCriteria ////////////////////////////// /** @brief The class defining termination criteria for iterative algorithms. You can initialize it by default constructor and then override any parameters, or the structure may be fully initialized using the advanced variant of the constructor. */ class CV_EXPORTS TermCriteria { public: /** Criteria type, can be one of: COUNT, EPS or COUNT + EPS */ enum Type { COUNT=1, //!< the maximum number of iterations or elements to compute MAX_ITER=COUNT, //!< ditto EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops }; //! default constructor TermCriteria(); /** @param type The type of termination criteria, one of TermCriteria::Type @param maxCount The maximum number of iterations or elements to compute. @param epsilon The desired accuracy or change in parameters at which the iterative algorithm stops. */ TermCriteria(int type, int maxCount, double epsilon); int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS int maxCount; // the maximum number of iterations/elements double epsilon; // the desired accuracy }; //! @} core_basic ///////////////////////// raster image moments ////////////////////////// //! @addtogroup imgproc_shape //! @{ /** @brief struct returned by cv::moments The spatial moments \f$\texttt{Moments::m}_{ji}\f$ are computed as: \f[\texttt{m} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot x^j \cdot y^i \right )\f] The central moments \f$\texttt{Moments::mu}_{ji}\f$ are computed as: \f[\texttt{mu} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot (x - \bar{x} )^j \cdot (y - \bar{y} )^i \right )\f] where \f$(\bar{x}, \bar{y})\f$ is the mass center: \f[\bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}\f] The normalized central moments \f$\texttt{Moments::nu}_{ij}\f$ are computed as: \f[\texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .\f] @note \f$\texttt{mu}_{00}=\texttt{m}_{00}\f$, \f$\texttt{nu}_{00}=1\f$ \f$\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0\f$ , hence the values are not stored. The moments of a contour are defined in the same way but computed using the Green's formula (see ). So, due to a limited raster resolution, the moments computed for a contour are slightly different from the moments computed for the same rasterized contour. @note Since the contour moments are computed using Green formula, you may get seemingly odd results for contours with self-intersections, e.g. a zero area (m00) for butterfly-shaped contours. */ class CV_EXPORTS_W_MAP Moments { public: //! the default constructor Moments(); //! the full constructor Moments(double m00, double m10, double m01, double m20, double m11, double m02, double m30, double m21, double m12, double m03 ); ////! the conversion from CvMoments //Moments( const CvMoments& moments ); ////! the conversion to CvMoments //operator CvMoments() const; //! @name spatial moments //! @{ CV_PROP_RW double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; //! @} //! @name central moments //! @{ CV_PROP_RW double mu20, mu11, mu02, mu30, mu21, mu12, mu03; //! @} //! @name central normalized moments //! @{ CV_PROP_RW double nu20, nu11, nu02, nu30, nu21, nu12, nu03; //! @} }; template<> class DataType { public: typedef Moments value_type; typedef double work_type; typedef double channel_type; enum { generic_type = 0, depth = DataType::depth, channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 24 fmt = DataType::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec vec_type; }; //! @} imgproc_shape //! @cond IGNORED ///////////////////////////////////////////////////////////////////////// ///////////////////////////// Implementation //////////////////////////// ///////////////////////////////////////////////////////////////////////// //////////////////////////////// Complex //////////////////////////////// template inline Complex<_Tp>::Complex() : re(0), im(0) {} template inline Complex<_Tp>::Complex( _Tp _re, _Tp _im ) : re(_re), im(_im) {} template template inline Complex<_Tp>::operator Complex() const { return Complex(saturate_cast(re), saturate_cast(im)); } template inline Complex<_Tp> Complex<_Tp>::conj() const { return Complex<_Tp>(re, -im); } template static inline bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) { return a.re == b.re && a.im == b.im; } template static inline bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) { return a.re != b.re || a.im != b.im; } template static inline Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) { return Complex<_Tp>( a.re + b.re, a.im + b.im ); } template static inline Complex<_Tp>& operator += (Complex<_Tp>& a, const Complex<_Tp>& b) { a.re += b.re; a.im += b.im; return a; } template static inline Complex<_Tp> operator - (const Complex<_Tp>& a, const Complex<_Tp>& b) { return Complex<_Tp>( a.re - b.re, a.im - b.im ); } template static inline Complex<_Tp>& operator -= (Complex<_Tp>& a, const Complex<_Tp>& b) { a.re -= b.re; a.im -= b.im; return a; } template static inline Complex<_Tp> operator - (const Complex<_Tp>& a) { return Complex<_Tp>(-a.re, -a.im); } template static inline Complex<_Tp> operator * (const Complex<_Tp>& a, const Complex<_Tp>& b) { return Complex<_Tp>( a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re ); } template static inline Complex<_Tp> operator * (const Complex<_Tp>& a, _Tp b) { return Complex<_Tp>( a.re*b, a.im*b ); } template static inline Complex<_Tp> operator * (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>( a.re*b, a.im*b ); } template static inline Complex<_Tp> operator + (const Complex<_Tp>& a, _Tp b) { return Complex<_Tp>( a.re + b, a.im ); } template static inline Complex<_Tp> operator - (const Complex<_Tp>& a, _Tp b) { return Complex<_Tp>( a.re - b, a.im ); } template static inline Complex<_Tp> operator + (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>( a.re + b, a.im ); } template static inline Complex<_Tp> operator - (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>( b - a.re, -a.im ); } template static inline Complex<_Tp>& operator += (Complex<_Tp>& a, _Tp b) { a.re += b; return a; } template static inline Complex<_Tp>& operator -= (Complex<_Tp>& a, _Tp b) { a.re -= b; return a; } template static inline Complex<_Tp>& operator *= (Complex<_Tp>& a, _Tp b) { a.re *= b; a.im *= b; return a; } template static inline double abs(const Complex<_Tp>& a) { return std::sqrt( (double)a.re*a.re + (double)a.im*a.im); } template static inline Complex<_Tp> operator / (const Complex<_Tp>& a, const Complex<_Tp>& b) { double t = 1./((double)b.re*b.re + (double)b.im*b.im); return Complex<_Tp>( (_Tp)((a.re*b.re + a.im*b.im)*t), (_Tp)((-a.re*b.im + a.im*b.re)*t) ); } template static inline Complex<_Tp>& operator /= (Complex<_Tp>& a, const Complex<_Tp>& b) { return (a = a / b); } template static inline Complex<_Tp> operator / (const Complex<_Tp>& a, _Tp b) { _Tp t = (_Tp)1/b; return Complex<_Tp>( a.re*t, a.im*t ); } template static inline Complex<_Tp> operator / (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>(b)/a; } template static inline Complex<_Tp> operator /= (const Complex<_Tp>& a, _Tp b) { _Tp t = (_Tp)1/b; a.re *= t; a.im *= t; return a; } //////////////////////////////// 2D Point /////////////////////////////// template inline Point_<_Tp>::Point_() : x(0), y(0) {} template inline Point_<_Tp>::Point_(_Tp _x, _Tp _y) : x(_x), y(_y) {} template inline Point_<_Tp>::Point_(const Point_& pt) : x(pt.x), y(pt.y) {} template inline Point_<_Tp>::Point_(const Size_<_Tp>& sz) : x(sz.width), y(sz.height) {} template inline Point_<_Tp>::Point_(const Vec<_Tp,2>& v) : x(v[0]), y(v[1]) {} template inline Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt) { x = pt.x; y = pt.y; return *this; } template template inline Point_<_Tp>::operator Point_<_Tp2>() const { return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); } template inline Point_<_Tp>::operator Vec<_Tp, 2>() const { return Vec<_Tp, 2>(x, y); } template inline _Tp Point_<_Tp>::dot(const Point_& pt) const { return saturate_cast<_Tp>(x*pt.x + y*pt.y); } template inline double Point_<_Tp>::ddot(const Point_& pt) const { return (double)x*pt.x + (double)y*pt.y; } template inline double Point_<_Tp>::cross(const Point_& pt) const { return (double)x*pt.y - (double)y*pt.x; } template inline bool Point_<_Tp>::inside( const Rect_<_Tp>& r ) const { return r.contains(*this); } template static inline Point_<_Tp>& operator += (Point_<_Tp>& a, const Point_<_Tp>& b) { a.x += b.x; a.y += b.y; return a; } template static inline Point_<_Tp>& operator -= (Point_<_Tp>& a, const Point_<_Tp>& b) { a.x -= b.x; a.y -= b.y; return a; } template static inline Point_<_Tp>& operator *= (Point_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); return a; } template static inline Point_<_Tp>& operator *= (Point_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); return a; } template static inline Point_<_Tp>& operator *= (Point_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); return a; } template static inline Point_<_Tp>& operator /= (Point_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); return a; } template static inline Point_<_Tp>& operator /= (Point_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); return a; } template static inline Point_<_Tp>& operator /= (Point_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); return a; } template static inline double norm(const Point_<_Tp>& pt) { return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); } template static inline bool operator == (const Point_<_Tp>& a, const Point_<_Tp>& b) { return a.x == b.x && a.y == b.y; } template static inline bool operator != (const Point_<_Tp>& a, const Point_<_Tp>& b) { return a.x != b.x || a.y != b.y; } template static inline Point_<_Tp> operator + (const Point_<_Tp>& a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y) ); } template static inline Point_<_Tp> operator - (const Point_<_Tp>& a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y) ); } template static inline Point_<_Tp> operator - (const Point_<_Tp>& a) { return Point_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y) ); } template static inline Point_<_Tp> operator * (const Point_<_Tp>& a, int b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } template static inline Point_<_Tp> operator * (int a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } template static inline Point_<_Tp> operator * (const Point_<_Tp>& a, float b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } template static inline Point_<_Tp> operator * (float a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } template static inline Point_<_Tp> operator * (const Point_<_Tp>& a, double b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } template static inline Point_<_Tp> operator * (double a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } template static inline Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) { Matx<_Tp, 2, 1> tmp = a * Vec<_Tp,2>(b.x, b.y); return Point_<_Tp>(tmp.val[0], tmp.val[1]); } template static inline Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) { Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, 1); return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); } template static inline Point_<_Tp> operator / (const Point_<_Tp>& a, int b) { Point_<_Tp> tmp(a); tmp /= b; return tmp; } template static inline Point_<_Tp> operator / (const Point_<_Tp>& a, float b) { Point_<_Tp> tmp(a); tmp /= b; return tmp; } template static inline Point_<_Tp> operator / (const Point_<_Tp>& a, double b) { Point_<_Tp> tmp(a); tmp /= b; return tmp; } //////////////////////////////// 3D Point /////////////////////////////// template inline Point3_<_Tp>::Point3_() : x(0), y(0), z(0) {} template inline Point3_<_Tp>::Point3_(_Tp _x, _Tp _y, _Tp _z) : x(_x), y(_y), z(_z) {} template inline Point3_<_Tp>::Point3_(const Point3_& pt) : x(pt.x), y(pt.y), z(pt.z) {} template inline Point3_<_Tp>::Point3_(const Point_<_Tp>& pt) : x(pt.x), y(pt.y), z(_Tp()) {} template inline Point3_<_Tp>::Point3_(const Vec<_Tp, 3>& v) : x(v[0]), y(v[1]), z(v[2]) {} template template inline Point3_<_Tp>::operator Point3_<_Tp2>() const { return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z)); } template inline Point3_<_Tp>::operator Vec<_Tp, 3>() const { return Vec<_Tp, 3>(x, y, z); } template inline Point3_<_Tp>& Point3_<_Tp>::operator = (const Point3_& pt) { x = pt.x; y = pt.y; z = pt.z; return *this; } template inline _Tp Point3_<_Tp>::dot(const Point3_& pt) const { return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); } template inline double Point3_<_Tp>::ddot(const Point3_& pt) const { return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; } template inline Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const { return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); } template static inline Point3_<_Tp>& operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) { a.x += b.x; a.y += b.y; a.z += b.z; return a; } template static inline Point3_<_Tp>& operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; return a; } template static inline Point3_<_Tp>& operator *= (Point3_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); a.z = saturate_cast<_Tp>(a.z * b); return a; } template static inline Point3_<_Tp>& operator *= (Point3_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); a.z = saturate_cast<_Tp>(a.z * b); return a; } template static inline Point3_<_Tp>& operator *= (Point3_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); a.z = saturate_cast<_Tp>(a.z * b); return a; } template static inline Point3_<_Tp>& operator /= (Point3_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); a.z = saturate_cast<_Tp>(a.z / b); return a; } template static inline Point3_<_Tp>& operator /= (Point3_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); a.z = saturate_cast<_Tp>(a.z / b); return a; } template static inline Point3_<_Tp>& operator /= (Point3_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); a.z = saturate_cast<_Tp>(a.z / b); return a; } template static inline double norm(const Point3_<_Tp>& pt) { return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); } template static inline bool operator == (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return a.x == b.x && a.y == b.y && a.z == b.z; } template static inline bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return a.x != b.x || a.y != b.y || a.z != b.z; } template static inline Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y), saturate_cast<_Tp>(a.z + b.z)); } template static inline Point3_<_Tp> operator - (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y), saturate_cast<_Tp>(a.z - b.z)); } template static inline Point3_<_Tp> operator - (const Point3_<_Tp>& a) { return Point3_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y), saturate_cast<_Tp>(-a.z) ); } template static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, int b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b), saturate_cast<_Tp>(a.z*b) ); } template static inline Point3_<_Tp> operator * (int a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); } template static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, float b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); } template static inline Point3_<_Tp> operator * (float a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); } template static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, double b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); } template static inline Point3_<_Tp> operator * (double a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); } template static inline Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) { Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, b.z); return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); } template static inline Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) { return a * Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); } template static inline Point3_<_Tp> operator / (const Point3_<_Tp>& a, int b) { Point3_<_Tp> tmp(a); tmp /= b; return tmp; } template static inline Point3_<_Tp> operator / (const Point3_<_Tp>& a, float b) { Point3_<_Tp> tmp(a); tmp /= b; return tmp; } template static inline Point3_<_Tp> operator / (const Point3_<_Tp>& a, double b) { Point3_<_Tp> tmp(a); tmp /= b; return tmp; } ////////////////////////////////// Size ///////////////////////////////// template inline Size_<_Tp>::Size_() : width(0), height(0) {} template inline Size_<_Tp>::Size_(_Tp _width, _Tp _height) : width(_width), height(_height) {} template inline Size_<_Tp>::Size_(const Size_& sz) : width(sz.width), height(sz.height) {} template inline Size_<_Tp>::Size_(const Point_<_Tp>& pt) : width(pt.x), height(pt.y) {} template template inline Size_<_Tp>::operator Size_<_Tp2>() const { return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); } template inline Size_<_Tp>& Size_<_Tp>::operator = (const Size_<_Tp>& sz) { width = sz.width; height = sz.height; return *this; } template inline _Tp Size_<_Tp>::area() const { return width * height; } template static inline Size_<_Tp>& operator *= (Size_<_Tp>& a, _Tp b) { a.width *= b; a.height *= b; return a; } template static inline Size_<_Tp> operator * (const Size_<_Tp>& a, _Tp b) { Size_<_Tp> tmp(a); tmp *= b; return tmp; } template static inline Size_<_Tp>& operator /= (Size_<_Tp>& a, _Tp b) { a.width /= b; a.height /= b; return a; } template static inline Size_<_Tp> operator / (const Size_<_Tp>& a, _Tp b) { Size_<_Tp> tmp(a); tmp /= b; return tmp; } template static inline Size_<_Tp>& operator += (Size_<_Tp>& a, const Size_<_Tp>& b) { a.width += b.width; a.height += b.height; return a; } template static inline Size_<_Tp> operator + (const Size_<_Tp>& a, const Size_<_Tp>& b) { Size_<_Tp> tmp(a); tmp += b; return tmp; } template static inline Size_<_Tp>& operator -= (Size_<_Tp>& a, const Size_<_Tp>& b) { a.width -= b.width; a.height -= b.height; return a; } template static inline Size_<_Tp> operator - (const Size_<_Tp>& a, const Size_<_Tp>& b) { Size_<_Tp> tmp(a); tmp -= b; return tmp; } template static inline bool operator == (const Size_<_Tp>& a, const Size_<_Tp>& b) { return a.width == b.width && a.height == b.height; } template static inline bool operator != (const Size_<_Tp>& a, const Size_<_Tp>& b) { return !(a == b); } ////////////////////////////////// Rect ///////////////////////////////// template inline Rect_<_Tp>::Rect_() : x(0), y(0), width(0), height(0) {} template inline Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height) : x(_x), y(_y), width(_width), height(_height) {} template inline Rect_<_Tp>::Rect_(const Rect_<_Tp>& r) : x(r.x), y(r.y), width(r.width), height(r.height) {} template inline Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz) : x(org.x), y(org.y), width(sz.width), height(sz.height) {} template inline Rect_<_Tp>::Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2) { x = std::min(pt1.x, pt2.x); y = std::min(pt1.y, pt2.y); width = std::max(pt1.x, pt2.x) - x; height = std::max(pt1.y, pt2.y) - y; } template inline Rect_<_Tp>& Rect_<_Tp>::operator = ( const Rect_<_Tp>& r ) { x = r.x; y = r.y; width = r.width; height = r.height; return *this; } template inline Point_<_Tp> Rect_<_Tp>::tl() const { return Point_<_Tp>(x,y); } template inline Point_<_Tp> Rect_<_Tp>::br() const { return Point_<_Tp>(x + width, y + height); } template inline Size_<_Tp> Rect_<_Tp>::size() const { return Size_<_Tp>(width, height); } template inline _Tp Rect_<_Tp>::area() const { return width * height; } template template inline Rect_<_Tp>::operator Rect_<_Tp2>() const { return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); } template inline bool Rect_<_Tp>::contains(const Point_<_Tp>& pt) const { return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height; } template static inline Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Point_<_Tp>& b ) { a.x += b.x; a.y += b.y; return a; } template static inline Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Point_<_Tp>& b ) { a.x -= b.x; a.y -= b.y; return a; } template static inline Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Size_<_Tp>& b ) { a.width += b.width; a.height += b.height; return a; } template static inline Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Size_<_Tp>& b ) { a.width -= b.width; a.height -= b.height; return a; } template static inline Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) { _Tp x1 = std::max(a.x, b.x); _Tp y1 = std::max(a.y, b.y); a.width = std::min(a.x + a.width, b.x + b.width) - x1; a.height = std::min(a.y + a.height, b.y + b.height) - y1; a.x = x1; a.y = y1; if( a.width <= 0 || a.height <= 0 ) a = Rect(); return a; } template static inline Rect_<_Tp>& operator |= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) { _Tp x1 = std::min(a.x, b.x); _Tp y1 = std::min(a.y, b.y); a.width = std::max(a.x + a.width, b.x + b.width) - x1; a.height = std::max(a.y + a.height, b.y + b.height) - y1; a.x = x1; a.y = y1; return a; } template static inline bool operator == (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; } template static inline bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; } template static inline Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) { return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); } template static inline Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Point_<_Tp>& b) { return Rect_<_Tp>( a.x - b.x, a.y - b.y, a.width, a.height ); } template static inline Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Size_<_Tp>& b) { return Rect_<_Tp>( a.x, a.y, a.width + b.width, a.height + b.height ); } template static inline Rect_<_Tp> operator & (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { Rect_<_Tp> c = a; return c &= b; } template static inline Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { Rect_<_Tp> c = a; return c |= b; } ////////////////////////////// RotatedRect ////////////////////////////// inline RotatedRect::RotatedRect() : center(), size(), angle(0) {} inline RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle) : center(_center), size(_size), angle(_angle) {} ///////////////////////////////// Range ///////////////////////////////// inline Range::Range() : start(0), end(0) {} inline Range::Range(int _start, int _end) : start(_start), end(_end) {} inline int Range::size() const { return end - start; } inline bool Range::empty() const { return start == end; } inline Range Range::all() { return Range(INT_MIN, INT_MAX); } static inline bool operator == (const Range& r1, const Range& r2) { return r1.start == r2.start && r1.end == r2.end; } static inline bool operator != (const Range& r1, const Range& r2) { return !(r1 == r2); } static inline bool operator !(const Range& r) { return r.start == r.end; } static inline Range operator & (const Range& r1, const Range& r2) { Range r(std::max(r1.start, r2.start), std::min(r1.end, r2.end)); r.end = std::max(r.end, r.start); return r; } static inline Range& operator &= (Range& r1, const Range& r2) { r1 = r1 & r2; return r1; } static inline Range operator + (const Range& r1, int delta) { return Range(r1.start + delta, r1.end + delta); } static inline Range operator + (int delta, const Range& r1) { return Range(r1.start + delta, r1.end + delta); } static inline Range operator - (const Range& r1, int delta) { return r1 + (-delta); } ///////////////////////////////// Scalar //////////////////////////////// template inline Scalar_<_Tp>::Scalar_() { this->val[0] = this->val[1] = this->val[2] = this->val[3] = 0; } template inline Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3) { this->val[0] = v0; this->val[1] = v1; this->val[2] = v2; this->val[3] = v3; } template template inline Scalar_<_Tp>::Scalar_(const Vec<_Tp2, cn>& v) { int i; for( i = 0; i < (cn < 4 ? cn : 4); i++ ) this->val[i] = cv::saturate_cast<_Tp>(v.val[i]); for( ; i < 4; i++ ) this->val[i] = 0; } template inline Scalar_<_Tp>::Scalar_(_Tp v0) { this->val[0] = v0; this->val[1] = this->val[2] = this->val[3] = 0; } template inline Scalar_<_Tp> Scalar_<_Tp>::all(_Tp v0) { return Scalar_<_Tp>(v0, v0, v0, v0); } template inline Scalar_<_Tp> Scalar_<_Tp>::mul(const Scalar_<_Tp>& a, double scale ) const { return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0] * a.val[0] * scale), saturate_cast<_Tp>(this->val[1] * a.val[1] * scale), saturate_cast<_Tp>(this->val[2] * a.val[2] * scale), saturate_cast<_Tp>(this->val[3] * a.val[3] * scale)); } template inline Scalar_<_Tp> Scalar_<_Tp>::conj() const { return Scalar_<_Tp>(saturate_cast<_Tp>( this->val[0]), saturate_cast<_Tp>(-this->val[1]), saturate_cast<_Tp>(-this->val[2]), saturate_cast<_Tp>(-this->val[3])); } template inline bool Scalar_<_Tp>::isReal() const { return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; } template template inline Scalar_<_Tp>::operator Scalar_() const { return Scalar_(saturate_cast(this->val[0]), saturate_cast(this->val[1]), saturate_cast(this->val[2]), saturate_cast(this->val[3])); } template static inline Scalar_<_Tp>& operator += (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a.val[0] += b.val[0]; a.val[1] += b.val[1]; a.val[2] += b.val[2]; a.val[3] += b.val[3]; return a; } template static inline Scalar_<_Tp>& operator -= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a.val[0] -= b.val[0]; a.val[1] -= b.val[1]; a.val[2] -= b.val[2]; a.val[3] -= b.val[3]; return a; } template static inline Scalar_<_Tp>& operator *= ( Scalar_<_Tp>& a, _Tp v ) { a.val[0] *= v; a.val[1] *= v; a.val[2] *= v; a.val[3] *= v; return a; } template static inline bool operator == ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) { return a.val[0] == b.val[0] && a.val[1] == b.val[1] && a.val[2] == b.val[2] && a.val[3] == b.val[3]; } template static inline bool operator != ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) { return a.val[0] != b.val[0] || a.val[1] != b.val[1] || a.val[2] != b.val[2] || a.val[3] != b.val[3]; } template static inline Scalar_<_Tp> operator + (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return Scalar_<_Tp>(a.val[0] + b.val[0], a.val[1] + b.val[1], a.val[2] + b.val[2], a.val[3] + b.val[3]); } template static inline Scalar_<_Tp> operator - (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] - b.val[0]), saturate_cast<_Tp>(a.val[1] - b.val[1]), saturate_cast<_Tp>(a.val[2] - b.val[2]), saturate_cast<_Tp>(a.val[3] - b.val[3])); } template static inline Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, _Tp alpha) { return Scalar_<_Tp>(a.val[0] * alpha, a.val[1] * alpha, a.val[2] * alpha, a.val[3] * alpha); } template static inline Scalar_<_Tp> operator * (_Tp alpha, const Scalar_<_Tp>& a) { return a*alpha; } template static inline Scalar_<_Tp> operator - (const Scalar_<_Tp>& a) { return Scalar_<_Tp>(saturate_cast<_Tp>(-a.val[0]), saturate_cast<_Tp>(-a.val[1]), saturate_cast<_Tp>(-a.val[2]), saturate_cast<_Tp>(-a.val[3])); } template static inline Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return Scalar_<_Tp>(saturate_cast<_Tp>(a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3]), saturate_cast<_Tp>(a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2]), saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); } template static inline Scalar_<_Tp>& operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a = a * b; return a; } template static inline Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) { return Scalar_<_Tp>(a.val[0] / alpha, a.val[1] / alpha, a.val[2] / alpha, a.val[3] / alpha); } template static inline Scalar_ operator / (const Scalar_& a, float alpha) { float s = 1 / alpha; return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); } template static inline Scalar_ operator / (const Scalar_& a, double alpha) { double s = 1 / alpha; return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); } template static inline Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) { a = a / alpha; return a; } template static inline Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) { _Tp s = a / (b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); return b.conj() * s; } template static inline Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return a * ((_Tp)1 / b); } template static inline Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a = a / b; return a; } template static inline Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) { Matx c((Matx)a, b, Matx_MatMulOp()); return reinterpret_cast(c); } template<> inline Scalar operator * (const Matx& a, const Scalar& b) { Matx c(a, b, Matx_MatMulOp()); return reinterpret_cast(c); } //////////////////////////////// KeyPoint /////////////////////////////// inline KeyPoint::KeyPoint() : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} inline KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle, float _response, int _octave, int _class_id) : pt(_pt), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} inline KeyPoint::KeyPoint(float x, float y, float _size, float _angle, float _response, int _octave, int _class_id) : pt(x, y), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} ///////////////////////////////// DMatch //////////////////////////////// inline DMatch::DMatch() : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(FLT_MAX) {} inline DMatch::DMatch(int _queryIdx, int _trainIdx, float _distance) : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} inline DMatch::DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance) : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} inline bool DMatch::operator < (const DMatch &m) const { return distance < m.distance; } ////////////////////////////// TermCriteria ///////////////////////////// inline TermCriteria::TermCriteria() : type(0), maxCount(0), epsilon(0) {} inline TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon) : type(_type), maxCount(_maxCount), epsilon(_epsilon) {} //! @endcond } // cv #endif //__OPENCV_CORE_TYPES_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/types_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_TYPES_H__ #define __OPENCV_CORE_TYPES_H__ #ifdef HAVE_IPL # ifndef __IPL_H__ # if defined WIN32 || defined _WIN32 # include # else # include # endif # endif #elif defined __IPL_H__ # define HAVE_IPL #endif #include "opencv2/core/cvdef.h" #ifndef SKIP_INCLUDES #include #include #include #include #endif // SKIP_INCLUDES #if defined WIN32 || defined _WIN32 # define CV_CDECL __cdecl # define CV_STDCALL __stdcall #else # define CV_CDECL # define CV_STDCALL #endif #ifndef CV_DEFAULT # ifdef __cplusplus # define CV_DEFAULT(val) = val # else # define CV_DEFAULT(val) # endif #endif #ifndef CV_EXTERN_C_FUNCPTR # ifdef __cplusplus # define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } # else # define CV_EXTERN_C_FUNCPTR(x) typedef x # endif #endif #ifndef CVAPI # define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL #endif #ifndef CV_IMPL # define CV_IMPL CV_EXTERN_C #endif #ifdef __cplusplus # include "opencv2/core.hpp" #endif /** @addtogroup core_c @{ */ /** @brief This is the "metatype" used *only* as a function parameter. It denotes that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 bytes of the header. In C++ interface the role of CvArr is played by InputArray and OutputArray. */ typedef void CvArr; typedef int CVStatus; /** @see cv::Error::Code */ enum { CV_StsOk= 0, /**< everything is ok */ CV_StsBackTrace= -1, /**< pseudo error for back trace */ CV_StsError= -2, /**< unknown /unspecified error */ CV_StsInternal= -3, /**< internal error (bad state) */ CV_StsNoMem= -4, /**< insufficient memory */ CV_StsBadArg= -5, /**< function arg/param is bad */ CV_StsBadFunc= -6, /**< unsupported function */ CV_StsNoConv= -7, /**< iter. didn't converge */ CV_StsAutoTrace= -8, /**< tracing */ CV_HeaderIsNull= -9, /**< image header is NULL */ CV_BadImageSize= -10, /**< image size is invalid */ CV_BadOffset= -11, /**< offset is invalid */ CV_BadDataPtr= -12, /**/ CV_BadStep= -13, /**/ CV_BadModelOrChSeq= -14, /**/ CV_BadNumChannels= -15, /**/ CV_BadNumChannel1U= -16, /**/ CV_BadDepth= -17, /**/ CV_BadAlphaChannel= -18, /**/ CV_BadOrder= -19, /**/ CV_BadOrigin= -20, /**/ CV_BadAlign= -21, /**/ CV_BadCallBack= -22, /**/ CV_BadTileSize= -23, /**/ CV_BadCOI= -24, /**/ CV_BadROISize= -25, /**/ CV_MaskIsTiled= -26, /**/ CV_StsNullPtr= -27, /**< null pointer */ CV_StsVecLengthErr= -28, /**< incorrect vector length */ CV_StsFilterStructContentErr= -29, /**< incorr. filter structure content */ CV_StsKernelStructContentErr= -30, /**< incorr. transform kernel content */ CV_StsFilterOffsetErr= -31, /**< incorrect filter offset value */ CV_StsBadSize= -201, /**< the input/output structure size is incorrect */ CV_StsDivByZero= -202, /**< division by zero */ CV_StsInplaceNotSupported= -203, /**< in-place operation is not supported */ CV_StsObjectNotFound= -204, /**< request can't be completed */ CV_StsUnmatchedFormats= -205, /**< formats of input/output arrays differ */ CV_StsBadFlag= -206, /**< flag is wrong or not supported */ CV_StsBadPoint= -207, /**< bad CvPoint */ CV_StsBadMask= -208, /**< bad format of mask (neither 8uC1 nor 8sC1)*/ CV_StsUnmatchedSizes= -209, /**< sizes of input/output structures do not match */ CV_StsUnsupportedFormat= -210, /**< the data format/type is not supported by the function*/ CV_StsOutOfRange= -211, /**< some of parameters are out of range */ CV_StsParseError= -212, /**< invalid syntax/structure of the parsed file */ CV_StsNotImplemented= -213, /**< the requested function/feature is not implemented */ CV_StsBadMemBlock= -214, /**< an allocated block has been corrupted */ CV_StsAssert= -215, /**< assertion failed */ CV_GpuNotSupported= -216, CV_GpuApiCallError= -217, CV_OpenGlNotSupported= -218, CV_OpenGlApiCallError= -219, CV_OpenCLApiCallError= -220, CV_OpenCLDoubleNotSupported= -221, CV_OpenCLInitError= -222, CV_OpenCLNoAMDBlasFft= -223 }; /****************************************************************************************\ * Common macros and inline functions * \****************************************************************************************/ #define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t)) /** min & max without jumps */ #define CV_IMIN(a, b) ((a) ^ (((a)^(b)) & (((a) < (b)) - 1))) #define CV_IMAX(a, b) ((a) ^ (((a)^(b)) & (((a) > (b)) - 1))) /** absolute value without jumps */ #ifndef __cplusplus # define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) #else # define CV_IABS(a) abs(a) #endif #define CV_CMP(a,b) (((a) > (b)) - ((a) < (b))) #define CV_SIGN(a) CV_CMP((a),0) #define cvInvSqrt(value) ((float)(1./sqrt(value))) #define cvSqrt(value) ((float)sqrt(value)) /*************** Random number generation *******************/ typedef uint64 CvRNG; #define CV_RNG_COEFF 4164903690U /** @brief Initializes a random number generator state. The function initializes a random number generator and returns the state. The pointer to the state can be then passed to the cvRandInt, cvRandReal and cvRandArr functions. In the current implementation a multiply-with-carry generator is used. @param seed 64-bit value used to initiate a random sequence @sa the C++ class RNG replaced CvRNG. */ CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1)) { CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1; return rng; } /** @brief Returns a 32-bit unsigned integer and updates RNG. The function returns a uniformly-distributed random 32-bit unsigned integer and updates the RNG state. It is similar to the rand() function from the C runtime library, except that OpenCV functions always generates a 32-bit random number, regardless of the platform. @param rng CvRNG state initialized by cvRNG. */ CV_INLINE unsigned cvRandInt( CvRNG* rng ) { uint64 temp = *rng; temp = (uint64)(unsigned)temp*CV_RNG_COEFF + (temp >> 32); *rng = temp; return (unsigned)temp; } /** @brief Returns a floating-point random number and updates RNG. The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not included). @param rng RNG state initialized by cvRNG */ CV_INLINE double cvRandReal( CvRNG* rng ) { return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */; } /****************************************************************************************\ * Image type (IplImage) * \****************************************************************************************/ #ifndef HAVE_IPL /* * The following definitions (until #endif) * is an extract from IPL headers. * Copyright (c) 1995 Intel Corporation. */ #define IPL_DEPTH_SIGN 0x80000000 #define IPL_DEPTH_1U 1 #define IPL_DEPTH_8U 8 #define IPL_DEPTH_16U 16 #define IPL_DEPTH_32F 32 #define IPL_DEPTH_8S (IPL_DEPTH_SIGN| 8) #define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16) #define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32) #define IPL_DATA_ORDER_PIXEL 0 #define IPL_DATA_ORDER_PLANE 1 #define IPL_ORIGIN_TL 0 #define IPL_ORIGIN_BL 1 #define IPL_ALIGN_4BYTES 4 #define IPL_ALIGN_8BYTES 8 #define IPL_ALIGN_16BYTES 16 #define IPL_ALIGN_32BYTES 32 #define IPL_ALIGN_DWORD IPL_ALIGN_4BYTES #define IPL_ALIGN_QWORD IPL_ALIGN_8BYTES #define IPL_BORDER_CONSTANT 0 #define IPL_BORDER_REPLICATE 1 #define IPL_BORDER_REFLECT 2 #define IPL_BORDER_WRAP 3 /** The IplImage is taken from the Intel Image Processing Library, in which the format is native. OpenCV only supports a subset of possible IplImage formats, as outlined in the parameter list above. In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require that the image size or ROI size of all source and destination images match exactly. On the other hand, the Intel Image Processing Library processes the area of intersection between the source and destination images (or ROIs), allowing them to vary independently. */ typedef struct #ifdef __cplusplus CV_EXPORTS #endif _IplImage { int nSize; /**< sizeof(IplImage) */ int ID; /**< version (=0)*/ int nChannels; /**< Most of OpenCV functions support 1,2,3 or 4 channels */ int alphaChannel; /**< Ignored by OpenCV */ int depth; /**< Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported. */ char colorModel[4]; /**< Ignored by OpenCV */ char channelSeq[4]; /**< ditto */ int dataOrder; /**< 0 - interleaved color channels, 1 - separate color channels. cvCreateImage can only create interleaved images */ int origin; /**< 0 - top-left origin, 1 - bottom-left origin (Windows bitmaps style). */ int align; /**< Alignment of image rows (4 or 8). OpenCV ignores it and uses widthStep instead. */ int width; /**< Image width in pixels. */ int height; /**< Image height in pixels. */ struct _IplROI *roi; /**< Image ROI. If NULL, the whole image is selected. */ struct _IplImage *maskROI; /**< Must be NULL. */ void *imageId; /**< " " */ struct _IplTileInfo *tileInfo; /**< " " */ int imageSize; /**< Image data size in bytes (==image->height*image->widthStep in case of interleaved data)*/ char *imageData; /**< Pointer to aligned image data. */ int widthStep; /**< Size of aligned image row in bytes. */ int BorderMode[4]; /**< Ignored by OpenCV. */ int BorderConst[4]; /**< Ditto. */ char *imageDataOrigin; /**< Pointer to very origin of image data (not necessarily aligned) - needed for correct deallocation */ #ifdef __cplusplus _IplImage() {} _IplImage(const cv::Mat& m); #endif } IplImage; typedef struct _IplTileInfo IplTileInfo; typedef struct _IplROI { int coi; /**< 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/ int xOffset; int yOffset; int width; int height; } IplROI; typedef struct _IplConvKernel { int nCols; int nRows; int anchorX; int anchorY; int *values; int nShiftR; } IplConvKernel; typedef struct _IplConvKernelFP { int nCols; int nRows; int anchorX; int anchorY; float *values; } IplConvKernelFP; #define IPL_IMAGE_HEADER 1 #define IPL_IMAGE_DATA 2 #define IPL_IMAGE_ROI 4 #endif/*HAVE_IPL*/ /** extra border mode */ #define IPL_BORDER_REFLECT_101 4 #define IPL_BORDER_TRANSPARENT 5 #define IPL_IMAGE_MAGIC_VAL ((int)sizeof(IplImage)) #define CV_TYPE_NAME_IMAGE "opencv-image" #define CV_IS_IMAGE_HDR(img) \ ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage)) #define CV_IS_IMAGE(img) \ (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL) /** for storing double-precision floating point data in IplImage's */ #define IPL_DEPTH_64F 64 /** get reference to pixel at (col,row), for multi-channel images (col) should be multiplied by number of channels */ #define CV_IMAGE_ELEM( image, elemtype, row, col ) \ (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) /****************************************************************************************\ * Matrix type (CvMat) * \****************************************************************************************/ #define CV_AUTO_STEP 0x7fffffff #define CV_WHOLE_ARR cvSlice( 0, 0x3fffffff ) #define CV_MAGIC_MASK 0xFFFF0000 #define CV_MAT_MAGIC_VAL 0x42420000 #define CV_TYPE_NAME_MAT "opencv-matrix" /** Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column index) of a matrix can be retrieved or modified using CV_MAT_ELEM macro: uchar pixval = CV_MAT_ELEM(grayimg, uchar, i, j) CV_MAT_ELEM(cameraMatrix, float, 0, 2) = image.width*0.5f; To access multiple-channel matrices, you can use CV_MAT_ELEM(matrix, type, i, j\*nchannels + channel_idx). @deprecated CvMat is now obsolete; consider using Mat instead. */ typedef struct CvMat { int type; int step; /* for internal use only */ int* refcount; int hdr_refcount; union { uchar* ptr; short* s; int* i; float* fl; double* db; } data; #ifdef __cplusplus union { int rows; int height; }; union { int cols; int width; }; #else int rows; int cols; #endif #ifdef __cplusplus CvMat() {} CvMat(const CvMat& m) { memcpy(this, &m, sizeof(CvMat));} CvMat(const cv::Mat& m); #endif } CvMat; #define CV_IS_MAT_HDR(mat) \ ((mat) != NULL && \ (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0) #define CV_IS_MAT_HDR_Z(mat) \ ((mat) != NULL && \ (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ ((const CvMat*)(mat))->cols >= 0 && ((const CvMat*)(mat))->rows >= 0) #define CV_IS_MAT(mat) \ (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL) #define CV_IS_MASK_ARR(mat) \ (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0) #define CV_ARE_TYPES_EQ(mat1, mat2) \ ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0) #define CV_ARE_CNS_EQ(mat1, mat2) \ ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0) #define CV_ARE_DEPTHS_EQ(mat1, mat2) \ ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0) #define CV_ARE_SIZES_EQ(mat1, mat2) \ ((mat1)->rows == (mat2)->rows && (mat1)->cols == (mat2)->cols) #define CV_IS_MAT_CONST(mat) \ (((mat)->rows|(mat)->cols) == 1) #define IPL2CV_DEPTH(depth) \ ((((CV_8U)+(CV_16U<<4)+(CV_32F<<8)+(CV_64F<<16)+(CV_8S<<20)+ \ (CV_16S<<24)+(CV_32S<<28)) >> ((((depth) & 0xF0) >> 2) + \ (((depth) & IPL_DEPTH_SIGN) ? 20 : 0))) & 15) /** Inline constructor. No data is allocated internally!!! * (Use together with cvCreateData, or use cvCreateMat instead to * get a matrix with allocated data): */ CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL)) { CvMat m; assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F ); type = CV_MAT_TYPE(type); m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type; m.cols = cols; m.rows = rows; m.step = m.cols*CV_ELEM_SIZE(type); m.data.ptr = (uchar*)data; m.refcount = NULL; m.hdr_refcount = 0; return m; } #ifdef __cplusplus inline CvMat::CvMat(const cv::Mat& m) { CV_DbgAssert(m.dims <= 2); *this = cvMat(m.rows, m.dims == 1 ? 1 : m.cols, m.type(), m.data); step = (int)m.step[0]; type = (type & ~cv::Mat::CONTINUOUS_FLAG) | (m.flags & cv::Mat::CONTINUOUS_FLAG); } #endif #define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size ) \ (assert( (unsigned)(row) < (unsigned)(mat).rows && \ (unsigned)(col) < (unsigned)(mat).cols ), \ (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col)) #define CV_MAT_ELEM_PTR( mat, row, col ) \ CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) ) #define CV_MAT_ELEM( mat, elemtype, row, col ) \ (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype))) /** @brief Returns the particular element of single-channel floating-point matrix. The function is a fast replacement for cvGetReal2D in the case of single-channel floating-point matrices. It is faster because it is inline, it does fewer checks for array type and array element type, and it checks for the row and column ranges only in debug mode. @param mat Input matrix @param row The zero-based index of row @param col The zero-based index of column */ CV_INLINE double cvmGet( const CvMat* mat, int row, int col ) { int type; type = CV_MAT_TYPE(mat->type); assert( (unsigned)row < (unsigned)mat->rows && (unsigned)col < (unsigned)mat->cols ); if( type == CV_32FC1 ) return ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; else { assert( type == CV_64FC1 ); return ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; } } /** @brief Sets a specific element of a single-channel floating-point matrix. The function is a fast replacement for cvSetReal2D in the case of single-channel floating-point matrices. It is faster because it is inline, it does fewer checks for array type and array element type, and it checks for the row and column ranges only in debug mode. @param mat The matrix @param row The zero-based index of row @param col The zero-based index of column @param value The new value of the matrix element */ CV_INLINE void cvmSet( CvMat* mat, int row, int col, double value ) { int type; type = CV_MAT_TYPE(mat->type); assert( (unsigned)row < (unsigned)mat->rows && (unsigned)col < (unsigned)mat->cols ); if( type == CV_32FC1 ) ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value; else { assert( type == CV_64FC1 ); ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = value; } } CV_INLINE int cvIplDepth( int type ) { int depth = CV_MAT_DEPTH(type); return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S || depth == CV_32S ? IPL_DEPTH_SIGN : 0); } /****************************************************************************************\ * Multi-dimensional dense array (CvMatND) * \****************************************************************************************/ #define CV_MATND_MAGIC_VAL 0x42430000 #define CV_TYPE_NAME_MATND "opencv-nd-matrix" #define CV_MAX_DIM 32 #define CV_MAX_DIM_HEAP 1024 /** @deprecated consider using cv::Mat instead */ typedef struct #ifdef __cplusplus CV_EXPORTS #endif CvMatND { int type; int dims; int* refcount; int hdr_refcount; union { uchar* ptr; float* fl; double* db; int* i; short* s; } data; struct { int size; int step; } dim[CV_MAX_DIM]; #ifdef __cplusplus CvMatND() {} CvMatND(const cv::Mat& m); #endif } CvMatND; #define CV_IS_MATND_HDR(mat) \ ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL) #define CV_IS_MATND(mat) \ (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL) /****************************************************************************************\ * Multi-dimensional sparse array (CvSparseMat) * \****************************************************************************************/ #define CV_SPARSE_MAT_MAGIC_VAL 0x42440000 #define CV_TYPE_NAME_SPARSE_MAT "opencv-sparse-matrix" struct CvSet; typedef struct #ifdef __cplusplus CV_EXPORTS #endif CvSparseMat { int type; int dims; int* refcount; int hdr_refcount; struct CvSet* heap; void** hashtable; int hashsize; int valoffset; int idxoffset; int size[CV_MAX_DIM]; #ifdef __cplusplus void copyToSparseMat(cv::SparseMat& m) const; #endif } CvSparseMat; #ifdef __cplusplus CV_EXPORTS CvSparseMat* cvCreateSparseMat(const cv::SparseMat& m); #endif #define CV_IS_SPARSE_MAT_HDR(mat) \ ((mat) != NULL && \ (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL) #define CV_IS_SPARSE_MAT(mat) \ CV_IS_SPARSE_MAT_HDR(mat) /**************** iteration through a sparse array *****************/ typedef struct CvSparseNode { unsigned hashval; struct CvSparseNode* next; } CvSparseNode; typedef struct CvSparseMatIterator { CvSparseMat* mat; CvSparseNode* node; int curidx; } CvSparseMatIterator; #define CV_NODE_VAL(mat,node) ((void*)((uchar*)(node) + (mat)->valoffset)) #define CV_NODE_IDX(mat,node) ((int*)((uchar*)(node) + (mat)->idxoffset)) /****************************************************************************************\ * Histogram * \****************************************************************************************/ typedef int CvHistType; #define CV_HIST_MAGIC_VAL 0x42450000 #define CV_HIST_UNIFORM_FLAG (1 << 10) /** indicates whether bin ranges are set already or not */ #define CV_HIST_RANGES_FLAG (1 << 11) #define CV_HIST_ARRAY 0 #define CV_HIST_SPARSE 1 #define CV_HIST_TREE CV_HIST_SPARSE /** should be used as a parameter only, it turns to CV_HIST_UNIFORM_FLAG of hist->type */ #define CV_HIST_UNIFORM 1 typedef struct CvHistogram { int type; CvArr* bins; float thresh[CV_MAX_DIM][2]; /**< For uniform histograms. */ float** thresh2; /**< For non-uniform histograms. */ CvMatND mat; /**< Embedded matrix header for array histograms. */ } CvHistogram; #define CV_IS_HIST( hist ) \ ((hist) != NULL && \ (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \ (hist)->bins != NULL) #define CV_IS_UNIFORM_HIST( hist ) \ (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0) #define CV_IS_SPARSE_HIST( hist ) \ CV_IS_SPARSE_MAT((hist)->bins) #define CV_HIST_HAS_RANGES( hist ) \ (((hist)->type & CV_HIST_RANGES_FLAG) != 0) /****************************************************************************************\ * Other supplementary data type definitions * \****************************************************************************************/ /*************************************** CvRect *****************************************/ /** @sa Rect_ */ typedef struct CvRect { int x; int y; int width; int height; #ifdef __cplusplus CvRect(int _x = 0, int _y = 0, int w = 0, int h = 0): x(_x), y(_y), width(w), height(h) {} template CvRect(const cv::Rect_<_Tp>& r): x(cv::saturate_cast(r.x)), y(cv::saturate_cast(r.y)), width(cv::saturate_cast(r.width)), height(cv::saturate_cast(r.height)) {} template operator cv::Rect_<_Tp>() const { return cv::Rect_<_Tp>((_Tp)x, (_Tp)y, (_Tp)width, (_Tp)height); } #endif } CvRect; /** constructs CvRect structure. */ CV_INLINE CvRect cvRect( int x, int y, int width, int height ) { CvRect r; r.x = x; r.y = y; r.width = width; r.height = height; return r; } CV_INLINE IplROI cvRectToROI( CvRect rect, int coi ) { IplROI roi; roi.xOffset = rect.x; roi.yOffset = rect.y; roi.width = rect.width; roi.height = rect.height; roi.coi = coi; return roi; } CV_INLINE CvRect cvROIToRect( IplROI roi ) { return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height ); } /*********************************** CvTermCriteria *************************************/ #define CV_TERMCRIT_ITER 1 #define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER #define CV_TERMCRIT_EPS 2 /** @sa TermCriteria */ typedef struct CvTermCriteria { int type; /**< may be combination of CV_TERMCRIT_ITER CV_TERMCRIT_EPS */ int max_iter; double epsilon; #ifdef __cplusplus CvTermCriteria(int _type = 0, int _iter = 0, double _eps = 0) : type(_type), max_iter(_iter), epsilon(_eps) {} CvTermCriteria(const cv::TermCriteria& t) : type(t.type), max_iter(t.maxCount), epsilon(t.epsilon) {} operator cv::TermCriteria() const { return cv::TermCriteria(type, max_iter, epsilon); } #endif } CvTermCriteria; CV_INLINE CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon ) { CvTermCriteria t; t.type = type; t.max_iter = max_iter; t.epsilon = (float)epsilon; return t; } /******************************* CvPoint and variants ***********************************/ typedef struct CvPoint { int x; int y; #ifdef __cplusplus CvPoint(int _x = 0, int _y = 0): x(_x), y(_y) {} template CvPoint(const cv::Point_<_Tp>& pt): x((int)pt.x), y((int)pt.y) {} template operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } #endif } CvPoint; /** constructs CvPoint structure. */ CV_INLINE CvPoint cvPoint( int x, int y ) { CvPoint p; p.x = x; p.y = y; return p; } typedef struct CvPoint2D32f { float x; float y; #ifdef __cplusplus CvPoint2D32f(float _x = 0, float _y = 0): x(_x), y(_y) {} template CvPoint2D32f(const cv::Point_<_Tp>& pt): x((float)pt.x), y((float)pt.y) {} template operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } #endif } CvPoint2D32f; /** constructs CvPoint2D32f structure. */ CV_INLINE CvPoint2D32f cvPoint2D32f( double x, double y ) { CvPoint2D32f p; p.x = (float)x; p.y = (float)y; return p; } /** converts CvPoint to CvPoint2D32f. */ CV_INLINE CvPoint2D32f cvPointTo32f( CvPoint point ) { return cvPoint2D32f( (float)point.x, (float)point.y ); } /** converts CvPoint2D32f to CvPoint. */ CV_INLINE CvPoint cvPointFrom32f( CvPoint2D32f point ) { CvPoint ipt; ipt.x = cvRound(point.x); ipt.y = cvRound(point.y); return ipt; } typedef struct CvPoint3D32f { float x; float y; float z; #ifdef __cplusplus CvPoint3D32f(float _x = 0, float _y = 0, float _z = 0): x(_x), y(_y), z(_z) {} template CvPoint3D32f(const cv::Point3_<_Tp>& pt): x((float)pt.x), y((float)pt.y), z((float)pt.z) {} template operator cv::Point3_<_Tp>() const { return cv::Point3_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y), cv::saturate_cast<_Tp>(z)); } #endif } CvPoint3D32f; /** constructs CvPoint3D32f structure. */ CV_INLINE CvPoint3D32f cvPoint3D32f( double x, double y, double z ) { CvPoint3D32f p; p.x = (float)x; p.y = (float)y; p.z = (float)z; return p; } typedef struct CvPoint2D64f { double x; double y; } CvPoint2D64f; /** constructs CvPoint2D64f structure.*/ CV_INLINE CvPoint2D64f cvPoint2D64f( double x, double y ) { CvPoint2D64f p; p.x = x; p.y = y; return p; } typedef struct CvPoint3D64f { double x; double y; double z; } CvPoint3D64f; /** constructs CvPoint3D64f structure. */ CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z ) { CvPoint3D64f p; p.x = x; p.y = y; p.z = z; return p; } /******************************** CvSize's & CvBox **************************************/ typedef struct CvSize { int width; int height; #ifdef __cplusplus CvSize(int w = 0, int h = 0): width(w), height(h) {} template CvSize(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} template operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } #endif } CvSize; /** constructs CvSize structure. */ CV_INLINE CvSize cvSize( int width, int height ) { CvSize s; s.width = width; s.height = height; return s; } typedef struct CvSize2D32f { float width; float height; #ifdef __cplusplus CvSize2D32f(float w = 0, float h = 0): width(w), height(h) {} template CvSize2D32f(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} template operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } #endif } CvSize2D32f; /** constructs CvSize2D32f structure. */ CV_INLINE CvSize2D32f cvSize2D32f( double width, double height ) { CvSize2D32f s; s.width = (float)width; s.height = (float)height; return s; } /** @sa RotatedRect */ typedef struct CvBox2D { CvPoint2D32f center; /**< Center of the box. */ CvSize2D32f size; /**< Box width and length. */ float angle; /**< Angle between the horizontal axis */ /**< and the first side (i.e. length) in degrees */ #ifdef __cplusplus CvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) : center(c), size(s), angle(a) {} CvBox2D(const cv::RotatedRect& rr) : center(rr.center), size(rr.size), angle(rr.angle) {} operator cv::RotatedRect() const { return cv::RotatedRect(center, size, angle); } #endif } CvBox2D; /** Line iterator state: */ typedef struct CvLineIterator { /** Pointer to the current point: */ uchar* ptr; /* Bresenham algorithm state: */ int err; int plus_delta; int minus_delta; int plus_step; int minus_step; } CvLineIterator; /************************************* CvSlice ******************************************/ #define CV_WHOLE_SEQ_END_INDEX 0x3fffffff #define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX) typedef struct CvSlice { int start_index, end_index; #if defined(__cplusplus) && !defined(__CUDACC__) CvSlice(int start = 0, int end = 0) : start_index(start), end_index(end) {} CvSlice(const cv::Range& r) { *this = (r.start != INT_MIN && r.end != INT_MAX) ? CvSlice(r.start, r.end) : CvSlice(0, CV_WHOLE_SEQ_END_INDEX); } operator cv::Range() const { return (start_index == 0 && end_index == CV_WHOLE_SEQ_END_INDEX ) ? cv::Range::all() : cv::Range(start_index, end_index); } #endif } CvSlice; CV_INLINE CvSlice cvSlice( int start, int end ) { CvSlice slice; slice.start_index = start; slice.end_index = end; return slice; } /************************************* CvScalar *****************************************/ /** @sa Scalar_ */ typedef struct CvScalar { double val[4]; #ifdef __cplusplus CvScalar() {} CvScalar(double d0, double d1 = 0, double d2 = 0, double d3 = 0) { val[0] = d0; val[1] = d1; val[2] = d2; val[3] = d3; } template CvScalar(const cv::Scalar_<_Tp>& s) { val[0] = s.val[0]; val[1] = s.val[1]; val[2] = s.val[2]; val[3] = s.val[3]; } template operator cv::Scalar_<_Tp>() const { return cv::Scalar_<_Tp>(cv::saturate_cast<_Tp>(val[0]), cv::saturate_cast<_Tp>(val[1]), cv::saturate_cast<_Tp>(val[2]), cv::saturate_cast<_Tp>(val[3])); } template CvScalar(const cv::Vec<_Tp, cn>& v) { int i; for( i = 0; i < (cn < 4 ? cn : 4); i++ ) val[i] = v.val[i]; for( ; i < 4; i++ ) val[i] = 0; } #endif } CvScalar; CV_INLINE CvScalar cvScalar( double val0, double val1 CV_DEFAULT(0), double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0)) { CvScalar scalar; scalar.val[0] = val0; scalar.val[1] = val1; scalar.val[2] = val2; scalar.val[3] = val3; return scalar; } CV_INLINE CvScalar cvRealScalar( double val0 ) { CvScalar scalar; scalar.val[0] = val0; scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; return scalar; } CV_INLINE CvScalar cvScalarAll( double val0123 ) { CvScalar scalar; scalar.val[0] = val0123; scalar.val[1] = val0123; scalar.val[2] = val0123; scalar.val[3] = val0123; return scalar; } /****************************************************************************************\ * Dynamic Data structures * \****************************************************************************************/ /******************************** Memory storage ****************************************/ typedef struct CvMemBlock { struct CvMemBlock* prev; struct CvMemBlock* next; } CvMemBlock; #define CV_STORAGE_MAGIC_VAL 0x42890000 typedef struct CvMemStorage { int signature; CvMemBlock* bottom; /**< First allocated block. */ CvMemBlock* top; /**< Current memory block - top of the stack. */ struct CvMemStorage* parent; /**< We get new blocks from parent as needed. */ int block_size; /**< Block size. */ int free_space; /**< Remaining free space in current block. */ } CvMemStorage; #define CV_IS_STORAGE(storage) \ ((storage) != NULL && \ (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL) typedef struct CvMemStoragePos { CvMemBlock* top; int free_space; } CvMemStoragePos; /*********************************** Sequence *******************************************/ typedef struct CvSeqBlock { struct CvSeqBlock* prev; /**< Previous sequence block. */ struct CvSeqBlock* next; /**< Next sequence block. */ int start_index; /**< Index of the first element in the block + */ /**< sequence->first->start_index. */ int count; /**< Number of elements in the block. */ schar* data; /**< Pointer to the first element of the block. */ } CvSeqBlock; #define CV_TREE_NODE_FIELDS(node_type) \ int flags; /**< Miscellaneous flags. */ \ int header_size; /**< Size of sequence header. */ \ struct node_type* h_prev; /**< Previous sequence. */ \ struct node_type* h_next; /**< Next sequence. */ \ struct node_type* v_prev; /**< 2nd previous sequence. */ \ struct node_type* v_next /**< 2nd next sequence. */ /** Read/Write sequence. Elements can be dynamically inserted to or deleted from the sequence. */ #define CV_SEQUENCE_FIELDS() \ CV_TREE_NODE_FIELDS(CvSeq); \ int total; /**< Total number of elements. */ \ int elem_size; /**< Size of sequence element in bytes. */ \ schar* block_max; /**< Maximal bound of the last block. */ \ schar* ptr; /**< Current write pointer. */ \ int delta_elems; /**< Grow seq this many at a time. */ \ CvMemStorage* storage; /**< Where the seq is stored. */ \ CvSeqBlock* free_blocks; /**< Free blocks list. */ \ CvSeqBlock* first; /**< Pointer to the first sequence block. */ typedef struct CvSeq { CV_SEQUENCE_FIELDS() } CvSeq; #define CV_TYPE_NAME_SEQ "opencv-sequence" #define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree" /*************************************** Set ********************************************/ /** @brief Set Order is not preserved. There can be gaps between sequence elements. After the element has been inserted it stays in the same place all the time. The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists. */ #define CV_SET_ELEM_FIELDS(elem_type) \ int flags; \ struct elem_type* next_free; typedef struct CvSetElem { CV_SET_ELEM_FIELDS(CvSetElem) } CvSetElem; #define CV_SET_FIELDS() \ CV_SEQUENCE_FIELDS() \ CvSetElem* free_elems; \ int active_count; typedef struct CvSet { CV_SET_FIELDS() } CvSet; #define CV_SET_ELEM_IDX_MASK ((1 << 26) - 1) #define CV_SET_ELEM_FREE_FLAG (1 << (sizeof(int)*8-1)) /** Checks whether the element pointed by ptr belongs to a set or not */ #define CV_IS_SET_ELEM( ptr ) (((CvSetElem*)(ptr))->flags >= 0) /************************************* Graph ********************************************/ /** @name Graph We represent a graph as a set of vertices. Vertices contain their adjacency lists (more exactly, pointers to first incoming or outcoming edge (or 0 if isolated vertex)). Edges are stored in another set. There is a singly-linked list of incoming/outcoming edges for each vertex. Each edge consists of: - Two pointers to the starting and ending vertices (vtx[0] and vtx[1] respectively). A graph may be oriented or not. In the latter case, edges between vertex i to vertex j are not distinguished during search operations. - Two pointers to next edges for the starting and ending vertices, where next[0] points to the next edge in the vtx[0] adjacency list and next[1] points to the next edge in the vtx[1] adjacency list. @see CvGraphEdge, CvGraphVtx, CvGraphVtx2D, CvGraph @{ */ #define CV_GRAPH_EDGE_FIELDS() \ int flags; \ float weight; \ struct CvGraphEdge* next[2]; \ struct CvGraphVtx* vtx[2]; #define CV_GRAPH_VERTEX_FIELDS() \ int flags; \ struct CvGraphEdge* first; typedef struct CvGraphEdge { CV_GRAPH_EDGE_FIELDS() } CvGraphEdge; typedef struct CvGraphVtx { CV_GRAPH_VERTEX_FIELDS() } CvGraphVtx; typedef struct CvGraphVtx2D { CV_GRAPH_VERTEX_FIELDS() CvPoint2D32f* ptr; } CvGraphVtx2D; /** Graph is "derived" from the set (this is set a of vertices) and includes another set (edges) */ #define CV_GRAPH_FIELDS() \ CV_SET_FIELDS() \ CvSet* edges; typedef struct CvGraph { CV_GRAPH_FIELDS() } CvGraph; #define CV_TYPE_NAME_GRAPH "opencv-graph" /** @} */ /*********************************** Chain/Countour *************************************/ typedef struct CvChain { CV_SEQUENCE_FIELDS() CvPoint origin; } CvChain; #define CV_CONTOUR_FIELDS() \ CV_SEQUENCE_FIELDS() \ CvRect rect; \ int color; \ int reserved[3]; typedef struct CvContour { CV_CONTOUR_FIELDS() } CvContour; typedef CvContour CvPoint2DSeq; /****************************************************************************************\ * Sequence types * \****************************************************************************************/ #define CV_SEQ_MAGIC_VAL 0x42990000 #define CV_IS_SEQ(seq) \ ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL) #define CV_SET_MAGIC_VAL 0x42980000 #define CV_IS_SET(set) \ ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL) #define CV_SEQ_ELTYPE_BITS 12 #define CV_SEQ_ELTYPE_MASK ((1 << CV_SEQ_ELTYPE_BITS) - 1) #define CV_SEQ_ELTYPE_POINT CV_32SC2 /**< (x,y) */ #define CV_SEQ_ELTYPE_CODE CV_8UC1 /**< freeman code: 0..7 */ #define CV_SEQ_ELTYPE_GENERIC 0 #define CV_SEQ_ELTYPE_PTR CV_USRTYPE1 #define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /**< &(x,y) */ #define CV_SEQ_ELTYPE_INDEX CV_32SC1 /**< #(x,y) */ #define CV_SEQ_ELTYPE_GRAPH_EDGE 0 /**< &next_o, &next_d, &vtx_o, &vtx_d */ #define CV_SEQ_ELTYPE_GRAPH_VERTEX 0 /**< first_edge, &(x,y) */ #define CV_SEQ_ELTYPE_TRIAN_ATR 0 /**< vertex of the binary tree */ #define CV_SEQ_ELTYPE_CONNECTED_COMP 0 /**< connected component */ #define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /**< (x,y,z) */ #define CV_SEQ_KIND_BITS 2 #define CV_SEQ_KIND_MASK (((1 << CV_SEQ_KIND_BITS) - 1)<flags & CV_SEQ_ELTYPE_MASK) #define CV_SEQ_KIND( seq ) ((seq)->flags & CV_SEQ_KIND_MASK ) /** flag checking */ #define CV_IS_SEQ_INDEX( seq ) ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \ (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC)) #define CV_IS_SEQ_CURVE( seq ) (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE) #define CV_IS_SEQ_CLOSED( seq ) (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0) #define CV_IS_SEQ_CONVEX( seq ) 0 #define CV_IS_SEQ_HOLE( seq ) (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0) #define CV_IS_SEQ_SIMPLE( seq ) 1 /** type checking macros */ #define CV_IS_SEQ_POINT_SET( seq ) \ ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2)) #define CV_IS_SEQ_POINT_SUBSET( seq ) \ (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT) #define CV_IS_SEQ_POLYLINE( seq ) \ (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq)) #define CV_IS_SEQ_POLYGON( seq ) \ (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq)) #define CV_IS_SEQ_CHAIN( seq ) \ (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1) #define CV_IS_SEQ_CONTOUR( seq ) \ (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq))) #define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \ (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq )) #define CV_IS_SEQ_POLYGON_TREE( seq ) \ (CV_SEQ_ELTYPE (seq) == CV_SEQ_ELTYPE_TRIAN_ATR && \ CV_SEQ_KIND( seq ) == CV_SEQ_KIND_BIN_TREE ) #define CV_IS_GRAPH( seq ) \ (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH) #define CV_IS_GRAPH_ORIENTED( seq ) \ (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0) #define CV_IS_SUBDIV2D( seq ) \ (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D) /****************************************************************************************/ /* Sequence writer & reader */ /****************************************************************************************/ #define CV_SEQ_WRITER_FIELDS() \ int header_size; \ CvSeq* seq; /**< the sequence written */ \ CvSeqBlock* block; /**< current block */ \ schar* ptr; /**< pointer to free space */ \ schar* block_min; /**< pointer to the beginning of block*/\ schar* block_max; /**< pointer to the end of block */ typedef struct CvSeqWriter { CV_SEQ_WRITER_FIELDS() } CvSeqWriter; #define CV_SEQ_READER_FIELDS() \ int header_size; \ CvSeq* seq; /**< sequence, beign read */ \ CvSeqBlock* block; /**< current block */ \ schar* ptr; /**< pointer to element be read next */ \ schar* block_min; /**< pointer to the beginning of block */\ schar* block_max; /**< pointer to the end of block */ \ int delta_index;/**< = seq->first->start_index */ \ schar* prev_elem; /**< pointer to previous element */ typedef struct CvSeqReader { CV_SEQ_READER_FIELDS() } CvSeqReader; /****************************************************************************************/ /* Operations on sequences */ /****************************************************************************************/ #define CV_SEQ_ELEM( seq, elem_type, index ) \ /** assert gives some guarantee that parameter is valid */ \ ( assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) && \ (seq)->elem_size == sizeof(elem_type)), \ (elem_type*)((seq)->first && (unsigned)index < \ (unsigned)((seq)->first->count) ? \ (seq)->first->data + (index) * sizeof(elem_type) : \ cvGetSeqElem( (CvSeq*)(seq), (index) ))) #define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) ) /** Add element to sequence: */ #define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ { \ if( (writer).ptr >= (writer).block_max ) \ { \ cvCreateSeqBlock( &writer); \ } \ memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\ (writer).ptr += (writer).seq->elem_size; \ } #define CV_WRITE_SEQ_ELEM( elem, writer ) \ { \ assert( (writer).seq->elem_size == sizeof(elem)); \ if( (writer).ptr >= (writer).block_max ) \ { \ cvCreateSeqBlock( &writer); \ } \ assert( (writer).ptr <= (writer).block_max - sizeof(elem));\ memcpy((writer).ptr, &(elem), sizeof(elem)); \ (writer).ptr += sizeof(elem); \ } /** Move reader position forward: */ #define CV_NEXT_SEQ_ELEM( elem_size, reader ) \ { \ if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ { \ cvChangeSeqBlock( &(reader), 1 ); \ } \ } /** Move reader position backward: */ #define CV_PREV_SEQ_ELEM( elem_size, reader ) \ { \ if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ { \ cvChangeSeqBlock( &(reader), -1 ); \ } \ } /** Read element and move read position forward: */ #define CV_READ_SEQ_ELEM( elem, reader ) \ { \ assert( (reader).seq->elem_size == sizeof(elem)); \ memcpy( &(elem), (reader).ptr, sizeof((elem))); \ CV_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ } /** Read element and move read position backward: */ #define CV_REV_READ_SEQ_ELEM( elem, reader ) \ { \ assert( (reader).seq->elem_size == sizeof(elem)); \ memcpy(&(elem), (reader).ptr, sizeof((elem))); \ CV_PREV_SEQ_ELEM( sizeof(elem), reader ) \ } #define CV_READ_CHAIN_POINT( _pt, reader ) \ { \ (_pt) = (reader).pt; \ if( (reader).ptr ) \ { \ CV_READ_SEQ_ELEM( (reader).code, (reader)); \ assert( ((reader).code & ~7) == 0 ); \ (reader).pt.x += (reader).deltas[(int)(reader).code][0]; \ (reader).pt.y += (reader).deltas[(int)(reader).code][1]; \ } \ } #define CV_CURRENT_POINT( reader ) (*((CvPoint*)((reader).ptr))) #define CV_PREV_POINT( reader ) (*((CvPoint*)((reader).prev_elem))) #define CV_READ_EDGE( pt1, pt2, reader ) \ { \ assert( sizeof(pt1) == sizeof(CvPoint) && \ sizeof(pt2) == sizeof(CvPoint) && \ reader.seq->elem_size == sizeof(CvPoint)); \ (pt1) = CV_PREV_POINT( reader ); \ (pt2) = CV_CURRENT_POINT( reader ); \ (reader).prev_elem = (reader).ptr; \ CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader)); \ } /************ Graph macros ************/ /** Return next graph edge for given vertex: */ #define CV_NEXT_GRAPH_EDGE( edge, vertex ) \ (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)), \ (edge)->next[(edge)->vtx[1] == (vertex)]) /****************************************************************************************\ * Data structures for persistence (a.k.a serialization) functionality * \****************************************************************************************/ /** "black box" file storage */ typedef struct CvFileStorage CvFileStorage; /** Storage flags: */ #define CV_STORAGE_READ 0 #define CV_STORAGE_WRITE 1 #define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE #define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE #define CV_STORAGE_APPEND 2 #define CV_STORAGE_MEMORY 4 #define CV_STORAGE_FORMAT_MASK (7<<3) #define CV_STORAGE_FORMAT_AUTO 0 #define CV_STORAGE_FORMAT_XML 8 #define CV_STORAGE_FORMAT_YAML 16 /** @brief List of attributes. : In the current implementation, attributes are used to pass extra parameters when writing user objects (see cvWrite). XML attributes inside tags are not supported, aside from the object type specification (type_id attribute). @see cvAttrList, cvAttrValue */ typedef struct CvAttrList { const char** attr; /**< NULL-terminated array of (attribute_name,attribute_value) pairs. */ struct CvAttrList* next; /**< Pointer to next chunk of the attributes list. */ } CvAttrList; /** initializes CvAttrList structure */ CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL), CvAttrList* next CV_DEFAULT(NULL) ) { CvAttrList l; l.attr = attr; l.next = next; return l; } struct CvTypeInfo; #define CV_NODE_NONE 0 #define CV_NODE_INT 1 #define CV_NODE_INTEGER CV_NODE_INT #define CV_NODE_REAL 2 #define CV_NODE_FLOAT CV_NODE_REAL #define CV_NODE_STR 3 #define CV_NODE_STRING CV_NODE_STR #define CV_NODE_REF 4 /**< not used */ #define CV_NODE_SEQ 5 #define CV_NODE_MAP 6 #define CV_NODE_TYPE_MASK 7 #define CV_NODE_TYPE(flags) ((flags) & CV_NODE_TYPE_MASK) /** file node flags */ #define CV_NODE_FLOW 8 /**= CV_NODE_SEQ) #define CV_NODE_IS_FLOW(flags) (((flags) & CV_NODE_FLOW) != 0) #define CV_NODE_IS_EMPTY(flags) (((flags) & CV_NODE_EMPTY) != 0) #define CV_NODE_IS_USER(flags) (((flags) & CV_NODE_USER) != 0) #define CV_NODE_HAS_NAME(flags) (((flags) & CV_NODE_NAMED) != 0) #define CV_NODE_SEQ_SIMPLE 256 #define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0) typedef struct CvString { int len; char* ptr; } CvString; /** All the keys (names) of elements in the readed file storage are stored in the hash to speed up the lookup operations: */ typedef struct CvStringHashNode { unsigned hashval; CvString str; struct CvStringHashNode* next; } CvStringHashNode; typedef struct CvGenericHash CvFileNodeHash; /** Basic element of the file storage - scalar or collection: */ typedef struct CvFileNode { int tag; struct CvTypeInfo* info; /**< type information (only for user-defined object, for others it is 0) */ union { double f; /**< scalar floating-point number */ int i; /**< scalar integer number */ CvString str; /**< text string */ CvSeq* seq; /**< sequence (ordered collection of file nodes) */ CvFileNodeHash* map; /**< map (collection of named file nodes) */ } data; } CvFileNode; #ifdef __cplusplus extern "C" { #endif typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr ); typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr ); typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node ); typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage, const char* name, const void* struct_ptr, CvAttrList attributes ); typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr ); #ifdef __cplusplus } #endif /** @brief Type information The structure contains information about one of the standard or user-defined types. Instances of the type may or may not contain a pointer to the corresponding CvTypeInfo structure. In any case, there is a way to find the type info structure for a given object using the cvTypeOf function. Alternatively, type info can be found by type name using cvFindType, which is used when an object is read from file storage. The user can register a new type with cvRegisterType that adds the type information structure into the beginning of the type list. Thus, it is possible to create specialized types from generic standard types and override the basic methods. */ typedef struct CvTypeInfo { int flags; /**< not used */ int header_size; /**< sizeof(CvTypeInfo) */ struct CvTypeInfo* prev; /**< previous registered type in the list */ struct CvTypeInfo* next; /**< next registered type in the list */ const char* type_name; /**< type name, written to file storage */ CvIsInstanceFunc is_instance; /**< checks if the passed object belongs to the type */ CvReleaseFunc release; /**< releases object (memory etc.) */ CvReadFunc read; /**< reads object from file storage */ CvWriteFunc write; /**< writes object to file storage */ CvCloneFunc clone; /**< creates a copy of the object */ } CvTypeInfo; /**** System data types ******/ typedef struct CvPluginFuncInfo { void** func_addr; void* default_func_addr; const char* func_names; int search_modules; int loaded_from; } CvPluginFuncInfo; typedef struct CvModuleInfo { struct CvModuleInfo* next; const char* name; const char* version; CvPluginFuncInfo* func_tab; } CvModuleInfo; /** @} */ #endif /*__OPENCV_CORE_TYPES_H__*/ /* End of file. */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/utility.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_UTILITY_H__ #define __OPENCV_CORE_UTILITY_H__ #ifndef __cplusplus # error utility.hpp header must be compiled as C++ #endif #include "opencv2/core.hpp" namespace cv { #ifdef CV_COLLECT_IMPL_DATA CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays // Get stored implementation flags and fucntions names arrays // Each implementation entry correspond to function name entry, so you can find which implementation was executed in which fucntion CV_EXPORTS int getImpl(std::vector &impl, std::vector &funName); CV_EXPORTS bool useCollection(); // return implementation collection state CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state #define CV_IMPL_PLAIN 0x01 // native CPU OpenCV implementation #define CV_IMPL_OCL 0x02 // OpenCL implementation #define CV_IMPL_IPP 0x04 // IPP implementation #define CV_IMPL_MT 0x10 // multithreaded implementation #define CV_IMPL_ADD(impl) \ if(cv::useCollection()) \ { \ cv::addImpl(impl, CV_Func); \ } #else #define CV_IMPL_ADD(impl) #endif //! @addtogroup core_utils //! @{ /** @brief Automatically Allocated Buffer Class The class is used for temporary buffers in functions and methods. If a temporary buffer is usually small (a few K's of memory), but its size depends on the parameters, it makes sense to create a small fixed-size array on stack and use it if it's large enough. If the required buffer size is larger than the fixed size, another buffer of sufficient size is allocated dynamically and released after the processing. Therefore, in typical cases, when the buffer size is small, there is no overhead associated with malloc()/free(). At the same time, there is no limit on the size of processed data. This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and the number of stack-allocated elements. Here is how the class is used: \code void my_func(const cv::Mat& m) { cv::AutoBuffer buf; // create automatic buffer containing 1000 floats buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, // otherwise the buffer of "m.rows" floats will be allocated // dynamically and deallocated in cv::AutoBuffer destructor ... } \endcode */ template class AutoBuffer { public: typedef _Tp value_type; //! the default constructor AutoBuffer(); //! constructor taking the real buffer size AutoBuffer(size_t _size); //! the copy constructor AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf); //! the assignment operator AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf); //! destructor. calls deallocate() ~AutoBuffer(); //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used void allocate(size_t _size); //! deallocates the buffer if it was dynamically allocated void deallocate(); //! resizes the buffer and preserves the content void resize(size_t _size); //! returns the current buffer size size_t size() const; //! returns pointer to the real buffer, stack-allocated or head-allocated operator _Tp* (); //! returns read-only pointer to the real buffer, stack-allocated or head-allocated operator const _Tp* () const; protected: //! pointer to the real buffer, can point to buf if the buffer is small enough _Tp* ptr; //! size of the real buffer size_t sz; //! pre-allocated buffer. At least 1 element to confirm C++ standard reqirements _Tp buf[(fixed_size > 0) ? fixed_size : 1]; }; /** @brief Sets/resets the break-on-error mode. When the break-on-error mode is set, the default error handler issues a hardware exception, which can make debugging more convenient. \return the previous state */ CV_EXPORTS bool setBreakOnError(bool flag); extern "C" typedef int (*ErrorCallback)( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); /** @brief Sets the new error handler and the optional user data. The function sets the new error handler, called from cv::error(). \param errCallback the new error handler. If NULL, the default error handler is used. \param userdata the optional user data pointer, passed to the callback. \param prevUserdata the optional output parameter where the previous user data pointer is stored \return the previous error handler */ CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); /** @brief Returns a text string formatted using the printf-like expression. The function acts like sprintf but forms and returns an STL string. It can be used to form an error message in the Exception constructor. @param fmt printf-compatible formatting specifiers. */ CV_EXPORTS String format( const char* fmt, ... ); CV_EXPORTS String tempfile( const char* suffix = 0); CV_EXPORTS void glob(String pattern, std::vector& result, bool recursive = false); /** @brief OpenCV will try to set the number of threads for the next parallel region. If threads == 0, OpenCV will disable threading optimizations and run all it's functions sequentially. Passing threads \< 0 will reset threads number to system default. This function must be called outside of parallel region. OpenCV will try to run it's functions with specified threads number, but some behaviour differs from framework: - `TBB` – User-defined parallel constructions will run with the same threads number, if another does not specified. If late on user creates own scheduler, OpenCV will be use it. - `OpenMP` – No special defined behaviour. - `Concurrency` – If threads == 1, OpenCV will disable threading optimizations and run it's functions sequentially. - `GCD` – Supports only values \<= 0. - `C=` – No special defined behaviour. @param nthreads Number of threads used by OpenCV. @sa getNumThreads, getThreadNum */ CV_EXPORTS_W void setNumThreads(int nthreads); /** @brief Returns the number of threads used by OpenCV for parallel regions. Always returns 1 if OpenCV is built without threading support. The exact meaning of return value depends on the threading framework used by OpenCV library: - `TBB` – The number of threads, that OpenCV will try to use for parallel regions. If there is any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns default number of threads used by TBB library. - `OpenMP` – An upper bound on the number of threads that could be used to form a new team. - `Concurrency` – The number of threads, that OpenCV will try to use for parallel regions. - `GCD` – Unsupported; returns the GCD thread pool limit (512) for compatibility. - `C=` – The number of threads, that OpenCV will try to use for parallel regions, if before called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs, available for the process. @sa setNumThreads, getThreadNum */ CV_EXPORTS_W int getNumThreads(); /** @brief Returns the index of the currently executed thread within the current parallel region. Always returns 0 if called outside of parallel region. The exact meaning of return value depends on the threading framework used by OpenCV library: - `TBB` – Unsupported with current 4.1 TBB release. May be will be supported in future. - `OpenMP` – The thread number, within the current team, of the calling thread. - `Concurrency` – An ID for the virtual processor that the current context is executing on (0 for master thread and unique number for others, but not necessary 1,2,3,...). - `GCD` – System calling thread's ID. Never returns 0 inside parallel region. - `C=` – The index of the current parallel task. @sa setNumThreads, getNumThreads */ CV_EXPORTS_W int getThreadNum(); /** @brief Returns full configuration time cmake output. Returned value is raw cmake output including version control system revision, compiler version, compiler flags, enabled modules and third party libraries, etc. Output format depends on target architecture. */ CV_EXPORTS_W const String& getBuildInformation(); /** @brief Returns the number of ticks. The function returns the number of ticks after the certain event (for example, when the machine was turned on). It can be used to initialize RNG or to measure a function execution time by reading the tick count before and after the function call. See also the tick frequency. */ CV_EXPORTS_W int64 getTickCount(); /** @brief Returns the number of ticks per second. The function returns the number of ticks per second. That is, the following code computes the execution time in seconds: @code double t = (double)getTickCount(); // do something ... t = ((double)getTickCount() - t)/getTickFrequency(); @endcode */ CV_EXPORTS_W double getTickFrequency(); /** @brief Returns the number of CPU ticks. The function returns the current number of CPU ticks on some architectures (such as x86, x64, PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU with its own counter. So, theoretically (and practically) the subsequent calls to the function do not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU frequency depending on the load, the number of CPU clocks spent in some code cannot be directly converted to time units. Therefore, getTickCount is generally a preferable solution for measuring execution time. */ CV_EXPORTS_W int64 getCPUTickCount(); /** @brief Returns true if the specified feature is supported by the host hardware. The function returns true if the host hardware supports the specified feature. When user calls setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code in OpenCV. @param feature The feature of interest, one of cv::CpuFeatures */ CV_EXPORTS_W bool checkHardwareSupport(int feature); /** @brief Returns the number of logical CPUs available for the process. */ CV_EXPORTS_W int getNumberOfCPUs(); /** @brief Aligns a pointer to the specified number of bytes. The function returns the aligned pointer of the same type as the input pointer: \f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f] @param ptr Aligned pointer. @param n Alignment size that must be a power of two. */ template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) { return (_Tp*)(((size_t)ptr + n-1) & -n); } /** @brief Aligns a buffer size to the specified number of bytes. The function returns the minimum number that is greater or equal to sz and is divisible by n : \f[\texttt{(sz + n-1) & -n}\f] @param sz Buffer size to align. @param n Alignment size that must be a power of two. */ static inline size_t alignSize(size_t sz, int n) { CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 return (sz + n-1) & -n; } /** @brief Enables or disables the optimized code. The function can be used to dynamically turn on and off optimized code (code that uses SSE2, AVX, and other instructions on the platforms that support it). It sets a global flag that is further checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only safe to call the function on the very top level in your application where you can be sure that no other OpenCV function is currently executed. By default, the optimized code is enabled unless you disable it in CMake. The current status can be retrieved using useOptimized. @param onoff The boolean flag specifying whether the optimized code should be used (onoff=true) or not (onoff=false). */ CV_EXPORTS_W void setUseOptimized(bool onoff); /** @brief Returns the status of optimized code usage. The function returns true if the optimized code is enabled. Otherwise, it returns false. */ CV_EXPORTS_W bool useOptimized(); static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); } /////////////////////////////// Parallel Primitives ////////////////////////////////// /** @brief Base class for parallel data processors */ class CV_EXPORTS ParallelLoopBody { public: virtual ~ParallelLoopBody(); virtual void operator() (const Range& range) const = 0; }; /** @brief Parallel data processor */ CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); /////////////////////////////// forEach method of cv::Mat //////////////////////////// template inline void Mat::forEach_impl(const Functor& operation) { if (false) { operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast(NULL)); // If your compiler fail in this line. // Please check that your functor signature is // (_Tp&, const int*) <- multidimential // or (_Tp&, void*) <- in case of you don't need current idx. } CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX); const int LINES = static_cast(this->total() / this->size[this->dims - 1]); class PixelOperationWrapper :public ParallelLoopBody { public: PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation) : mat(frame), op(_operation) {}; virtual ~PixelOperationWrapper(){}; // ! Overloaded virtual operator // convert range call to row call. virtual void operator()(const Range &range) const { const int DIMS = mat->dims; const int COLS = mat->size[DIMS - 1]; if (DIMS <= 2) { for (int row = range.start; row < range.end; ++row) { this->rowCall2(row, COLS); } } else { std::vector idx(COLS); /// idx is modified in this->rowCall idx[DIMS - 2] = range.start - 1; for (int line_num = range.start; line_num < range.end; ++line_num) { idx[DIMS - 2]++; for (int i = DIMS - 2; i >= 0; --i) { if (idx[i] >= mat->size[i]) { idx[i - 1] += idx[i] / mat->size[i]; idx[i] %= mat->size[i]; continue; // carry-over; } else { break; } } this->rowCall(&idx[0], COLS, DIMS); } } }; private: Mat_<_Tp>* const mat; const Functor op; // ! Call operator for each elements in this row. inline void rowCall(int* const idx, const int COLS, const int DIMS) const { int &col = idx[DIMS - 1]; col = 0; _Tp* pixel = &(mat->template at<_Tp>(idx)); while (col < COLS) { op(*pixel, const_cast(idx)); pixel++; col++; } col = 0; } // ! Call operator for each elements in this row. 2d mat special version. inline void rowCall2(const int row, const int COLS) const { union Index{ int body[2]; operator const int*() const { return reinterpret_cast(this); } int& operator[](const int i) { return body[i]; } } idx = {{row, 0}}; // Special union is needed to avoid // "error: array subscript is above array bounds [-Werror=array-bounds]" // when call the functor `op` such that access idx[3]. _Tp* pixel = &(mat->template at<_Tp>(idx)); const _Tp* const pixel_end = pixel + COLS; while(pixel < pixel_end) { op(*pixel++, static_cast(idx)); idx[1]++; } }; PixelOperationWrapper& operator=(const PixelOperationWrapper &) { CV_Assert(false); // We can not remove this implementation because Visual Studio warning C4822. return *this; }; }; parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast*>(this), operation)); } /////////////////////////// Synchronization Primitives /////////////////////////////// class CV_EXPORTS Mutex { public: Mutex(); ~Mutex(); Mutex(const Mutex& m); Mutex& operator = (const Mutex& m); void lock(); bool trylock(); void unlock(); struct Impl; protected: Impl* impl; }; class CV_EXPORTS AutoLock { public: AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); } ~AutoLock() { mutex->unlock(); } protected: Mutex* mutex; private: AutoLock(const AutoLock&); AutoLock& operator = (const AutoLock&); }; // TLS interface class CV_EXPORTS TLSDataContainer { protected: TLSDataContainer(); virtual ~TLSDataContainer(); void gatherData(std::vector &data) const; #if OPENCV_ABI_COMPATIBILITY > 300 void* getData() const; void release(); private: #else void release(); public: void* getData() const; #endif virtual void* createDataInstance() const = 0; virtual void deleteDataInstance(void* pData) const = 0; int key_; }; // Main TLS data class template class TLSData : protected TLSDataContainer { public: inline TLSData() {} inline ~TLSData() { release(); } // Release key and delete associated data inline T* get() const { return (T*)getData(); } // Get data assosiated with key // Get data from all threads inline void gather(std::vector &data) const { std::vector &dataVoid = reinterpret_cast&>(data); gatherData(dataVoid); } private: virtual void* createDataInstance() const {return new T;} // Wrapper to allocate data by template virtual void deleteDataInstance(void* pData) const {delete (T*)pData;} // Wrapper to release data by template // Disable TLS copy operations TLSData(TLSData &) {}; TLSData& operator =(const TLSData &) {return *this;}; }; /** @brief Designed for command line parsing The sample below demonstrates how to use CommandLineParser: @code CommandLineParser parser(argc, argv, keys); parser.about("Application name v1.0.0"); if (parser.has("help")) { parser.printMessage(); return 0; } int N = parser.get("N"); double fps = parser.get("fps"); String path = parser.get("path"); use_time_stamp = parser.has("timestamp"); String img1 = parser.get(0); String img2 = parser.get(1); int repeat = parser.get(2); if (!parser.check()) { parser.printErrors(); return 0; } @endcode ### Keys syntax The keys parameter is a string containing several blocks, each one is enclosed in curley braces and describes one argument. Each argument contains three parts separated by the `|` symbol: -# argument names is a space-separated list of option synonyms (to mark argument as positional, prefix it with the `@` symbol) -# default value will be used if the argument was not provided (can be empty) -# help message (can be empty) For example: @code{.cpp} const String keys = "{help h usage ? | | print this message }" "{@image1 | | image1 for compare }" "{@image2 || image2 for compare }" "{@repeat |1 | number }" "{path |. | path to file }" "{fps | -1.0 | fps for output video }" "{N count |100 | count of objects }" "{ts timestamp | | use time stamp }" ; } @endcode Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method. Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their actual value instead. String keys like `get("@image1")` return the empty string `""` by default - even with an empty default value. Use the special `` default value to enforce that the returned string must not be empty. (like in `get("@image2")`) ### Usage For the described keys: @code{.sh} # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true) $ ./app -N=200 1.png 2.jpg 19 -ts # Bad call $ ./app -fps=aaa ERRORS: Parameter 'fps': can not convert: [aaa] to [double] @endcode */ class CV_EXPORTS CommandLineParser { public: /** @brief Constructor Initializes command line parser object @param argc number of command line arguments (from main()) @param argv array of command line arguments (from main()) @param keys string describing acceptable command line parameters (see class description for syntax) */ CommandLineParser(int argc, const char* const argv[], const String& keys); /** @brief Copy constructor */ CommandLineParser(const CommandLineParser& parser); /** @brief Assignment operator */ CommandLineParser& operator = (const CommandLineParser& parser); /** @brief Destructor */ ~CommandLineParser(); /** @brief Returns application path This method returns the path to the executable from the command line (`argv[0]`). For example, if the application has been started with such command: @code{.sh} $ ./bin/my-executable @endcode this method will return `./bin`. */ String getPathToApplication() const; /** @brief Access arguments by name Returns argument converted to selected type. If the argument is not known or can not be converted to selected type, the error flag is set (can be checked with @ref check). For example, define: @code{.cpp} String keys = "{N count||}"; @endcode Call: @code{.sh} $ ./my-app -N=20 # or $ ./my-app --count=20 @endcode Access: @code{.cpp} int N = parser.get("N"); @endcode @param name name of the argument @param space_delete remove spaces from the left and right of the string @tparam T the argument will be converted to this type if possible @note You can access positional arguments by their `@`-prefixed name: @code{.cpp} parser.get("@image"); @endcode */ template T get(const String& name, bool space_delete = true) const { T val = T(); getByName(name, space_delete, ParamType::type, (void*)&val); return val; } /** @brief Access positional arguments by index Returns argument converted to selected type. Indexes are counted from zero. For example, define: @code{.cpp} String keys = "{@arg1||}{@arg2||}" @endcode Call: @code{.sh} ./my-app abc qwe @endcode Access arguments: @code{.cpp} String val_1 = parser.get(0); // returns "abc", arg1 String val_2 = parser.get(1); // returns "qwe", arg2 @endcode @param index index of the argument @param space_delete remove spaces from the left and right of the string @tparam T the argument will be converted to this type if possible */ template T get(int index, bool space_delete = true) const { T val = T(); getByIndex(index, space_delete, ParamType::type, (void*)&val); return val; } /** @brief Check if field was provided in the command line @param name argument name to check */ bool has(const String& name) const; /** @brief Check for parsing errors Returns true if error occured while accessing the parameters (bad conversion, missing arguments, etc.). Call @ref printErrors to print error messages list. */ bool check() const; /** @brief Set the about message The about message will be shown when @ref printMessage is called, right before arguments table. */ void about(const String& message); /** @brief Print help message This method will print standard help message containing the about message and arguments description. @sa about */ void printMessage() const; /** @brief Print list of errors occured @sa check */ void printErrors() const; protected: void getByName(const String& name, bool space_delete, int type, void* dst) const; void getByIndex(int index, bool space_delete, int type, void* dst) const; struct Impl; Impl* impl; }; //! @} core_utils //! @cond IGNORED /////////////////////////////// AutoBuffer implementation //////////////////////////////////////// template inline AutoBuffer<_Tp, fixed_size>::AutoBuffer() { ptr = buf; sz = fixed_size; } template inline AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) { ptr = buf; sz = fixed_size; allocate(_size); } template inline AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf ) { ptr = buf; sz = fixed_size; allocate(abuf.size()); for( size_t i = 0; i < sz; i++ ) ptr[i] = abuf.ptr[i]; } template inline AutoBuffer<_Tp, fixed_size>& AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf) { if( this != &abuf ) { deallocate(); allocate(abuf.size()); for( size_t i = 0; i < sz; i++ ) ptr[i] = abuf.ptr[i]; } return *this; } template inline AutoBuffer<_Tp, fixed_size>::~AutoBuffer() { deallocate(); } template inline void AutoBuffer<_Tp, fixed_size>::allocate(size_t _size) { if(_size <= sz) { sz = _size; return; } deallocate(); if(_size > fixed_size) { ptr = new _Tp[_size]; sz = _size; } } template inline void AutoBuffer<_Tp, fixed_size>::deallocate() { if( ptr != buf ) { delete[] ptr; ptr = buf; sz = fixed_size; } } template inline void AutoBuffer<_Tp, fixed_size>::resize(size_t _size) { if(_size <= sz) { sz = _size; return; } size_t i, prevsize = sz, minsize = MIN(prevsize, _size); _Tp* prevptr = ptr; ptr = _size > fixed_size ? new _Tp[_size] : buf; sz = _size; if( ptr != prevptr ) for( i = 0; i < minsize; i++ ) ptr[i] = prevptr[i]; for( i = prevsize; i < _size; i++ ) ptr[i] = _Tp(); if( prevptr != buf ) delete[] prevptr; } template inline size_t AutoBuffer<_Tp, fixed_size>::size() const { return sz; } template inline AutoBuffer<_Tp, fixed_size>::operator _Tp* () { return ptr; } template inline AutoBuffer<_Tp, fixed_size>::operator const _Tp* () const { return ptr; } #ifndef OPENCV_NOSTL template<> inline std::string CommandLineParser::get(int index, bool space_delete) const { return get(index, space_delete); } template<> inline std::string CommandLineParser::get(const String& name, bool space_delete) const { return get(name, space_delete); } #endif // OPENCV_NOSTL //! @endcond } //namespace cv #ifndef DISABLE_OPENCV_24_COMPATIBILITY #include "opencv2/core/core_c.h" #endif #endif //__OPENCV_CORE_UTILITY_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/va_intel.hpp ================================================ // This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // Copyright (C) 2015, Itseez, Inc., all rights reserved. // Third party copyrights are property of their respective owners. #ifndef __OPENCV_CORE_VA_INTEL_HPP__ #define __OPENCV_CORE_VA_INTEL_HPP__ #ifndef __cplusplus # error va_intel.hpp header must be compiled as C++ #endif #include "opencv2/core.hpp" #include "ocl.hpp" #if defined(HAVE_VA) # include "va/va.h" #else // HAVE_VA # if !defined(_VA_H_) typedef void* VADisplay; typedef unsigned int VASurfaceID; # endif // !_VA_H_ #endif // HAVE_VA namespace cv { namespace va_intel { /** @addtogroup core_va_intel This section describes Intel VA-API/OpenCL (CL-VA) interoperability. To enable CL-VA interoperability support, configure OpenCV using CMake with WITH_VA_INTEL=ON . Currently VA-API is supported on Linux only. You should also install Intel Media Server Studio (MSS) to use this feature. You may have to specify the path(s) to MSS components for cmake in environment variables: VA_INTEL_MSDK_ROOT for Media SDK (default is "/opt/intel/mediasdk"), and VA_INTEL_IOCL_ROOT for Intel OpenCL (default is "/opt/intel/opencl"). To use CL-VA interoperability you should first create VADisplay (libva), and then call initializeContextFromVA() function to create OpenCL context and set up interoperability. */ //! @{ /////////////////// CL-VA Interoperability Functions /////////////////// namespace ocl { using namespace cv::ocl; // TODO static functions in the Context class /** @brief Creates OpenCL context from VA. @param display - VADisplay for which CL interop should be established. @param tryInterop - try to set up for interoperability, if true; set up for use slow copy if false. @return Returns reference to OpenCL Context */ CV_EXPORTS Context& initializeContextFromVA(VADisplay display, bool tryInterop = true); } // namespace cv::va_intel::ocl /** @brief Converts InputArray to VASurfaceID object. @param display - VADisplay object. @param src - source InputArray. @param surface - destination VASurfaceID object. @param size - size of image represented by VASurfaceID object. */ CV_EXPORTS void convertToVASurface(VADisplay display, InputArray src, VASurfaceID surface, Size size); /** @brief Converts VASurfaceID object to OutputArray. @param display - VADisplay object. @param surface - source VASurfaceID object. @param size - size of image represented by VASurfaceID object. @param dst - destination OutputArray. */ CV_EXPORTS void convertFromVASurface(VADisplay display, VASurfaceID surface, Size size, OutputArray dst); //! @} }} // namespace cv::va_intel #endif /* __OPENCV_CORE_VA_INTEL_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/version.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright( C) 2000-2015, Intel Corporation, all rights reserved. // Copyright (C) 2011-2013, NVIDIA Corporation, all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages //(including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ /* definition of the current version of OpenCV Usefull to test in user programs */ #ifndef __OPENCV_VERSION_HPP__ #define __OPENCV_VERSION_HPP__ #define CV_VERSION_MAJOR 3 #define CV_VERSION_MINOR 1 #define CV_VERSION_REVISION 0 #define CV_VERSION_STATUS "" #define CVAUX_STR_EXP(__A) #__A #define CVAUX_STR(__A) CVAUX_STR_EXP(__A) #define CVAUX_STRW_EXP(__A) L#__A #define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A) #define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS /* old style version constants*/ #define CV_MAJOR_VERSION CV_VERSION_MAJOR #define CV_MINOR_VERSION CV_VERSION_MINOR #define CV_SUBMINOR_VERSION CV_VERSION_REVISION #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core/wimage.hpp ================================================ /*M////////////////////////////////////////////////////////////////////////////// // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to // this license. If you do not agree to this license, do not download, // install, copy or use the software. // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2008, Google, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation or contributors may not be used to endorse // or promote products derived from this software without specific // prior written permission. // // This software is provided by the copyright holders and contributors "as is" // and any express or implied warranties, including, but not limited to, the // implied warranties of merchantability and fitness for a particular purpose // are disclaimed. In no event shall the Intel Corporation or contributors be // liable for any direct, indirect, incidental, special, exemplary, or // consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. ///////////////////////////////////////////////////////////////////////////////// //M*/ #ifndef __OPENCV_CORE_WIMAGE_HPP__ #define __OPENCV_CORE_WIMAGE_HPP__ #include "opencv2/core/core_c.h" #ifdef __cplusplus namespace cv { //! @addtogroup core //! @{ template class WImage; template class WImageBuffer; template class WImageView; template class WImageC; template class WImageBufferC; template class WImageViewC; // Commonly used typedefs. typedef WImage WImage_b; typedef WImageView WImageView_b; typedef WImageBuffer WImageBuffer_b; typedef WImageC WImage1_b; typedef WImageViewC WImageView1_b; typedef WImageBufferC WImageBuffer1_b; typedef WImageC WImage3_b; typedef WImageViewC WImageView3_b; typedef WImageBufferC WImageBuffer3_b; typedef WImage WImage_f; typedef WImageView WImageView_f; typedef WImageBuffer WImageBuffer_f; typedef WImageC WImage1_f; typedef WImageViewC WImageView1_f; typedef WImageBufferC WImageBuffer1_f; typedef WImageC WImage3_f; typedef WImageViewC WImageView3_f; typedef WImageBufferC WImageBuffer3_f; // There isn't a standard for signed and unsigned short so be more // explicit in the typename for these cases. typedef WImage WImage_16s; typedef WImageView WImageView_16s; typedef WImageBuffer WImageBuffer_16s; typedef WImageC WImage1_16s; typedef WImageViewC WImageView1_16s; typedef WImageBufferC WImageBuffer1_16s; typedef WImageC WImage3_16s; typedef WImageViewC WImageView3_16s; typedef WImageBufferC WImageBuffer3_16s; typedef WImage WImage_16u; typedef WImageView WImageView_16u; typedef WImageBuffer WImageBuffer_16u; typedef WImageC WImage1_16u; typedef WImageViewC WImageView1_16u; typedef WImageBufferC WImageBuffer1_16u; typedef WImageC WImage3_16u; typedef WImageViewC WImageView3_16u; typedef WImageBufferC WImageBuffer3_16u; /** @brief Image class which provides a thin layer around an IplImage. The goals of the class design are: -# All the data has explicit ownership to avoid memory leaks -# No hidden allocations or copies for performance. -# Easy access to OpenCV methods (which will access IPP if available) -# Can easily treat external data as an image -# Easy to create images which are subsets of other images -# Fast pixel access which can take advantage of number of channels if known at compile time. The WImage class is the image class which provides the data accessors. The 'W' comes from the fact that it is also a wrapper around the popular but inconvenient IplImage class. A WImage can be constructed either using a WImageBuffer class which allocates and frees the data, or using a WImageView class which constructs a subimage or a view into external data. The view class does no memory management. Each class actually has two versions, one when the number of channels is known at compile time and one when it isn't. Using the one with the number of channels specified can provide some compile time optimizations by using the fact that the number of channels is a constant. We use the convention (c,r) to refer to column c and row r with (0,0) being the upper left corner. This is similar to standard Euclidean coordinates with the first coordinate varying in the horizontal direction and the second coordinate varying in the vertical direction. Thus (c,r) is usually in the domain [0, width) X [0, height) Example usage: @code WImageBuffer3_b im(5,7); // Make a 5X7 3 channel image of type uchar WImageView3_b sub_im(im, 2,2, 3,3); // 3X3 submatrix vector vec(10, 3.0f); WImageView1_f user_im(&vec[0], 2, 5); // 2X5 image w/ supplied data im.SetZero(); // same as cvSetZero(im.Ipl()) *im(2, 3) = 15; // Modify the element at column 2, row 3 MySetRand(&sub_im); // Copy the second row into the first. This can be done with no memory // allocation and will use SSE if IPP is available. int w = im.Width(); im.View(0,0, w,1).CopyFrom(im.View(0,1, w,1)); // Doesn't care about source of data since using WImage void MySetRand(WImage_b* im) { // Works with any number of channels for (int r = 0; r < im->Height(); ++r) { float* row = im->Row(r); for (int c = 0; c < im->Width(); ++c) { for (int ch = 0; ch < im->Channels(); ++ch, ++row) { *row = uchar(rand() & 255); } } } } @endcode Functions that are not part of the basic image allocation, viewing, and access should come from OpenCV, except some useful functions that are not part of OpenCV can be found in wimage_util.h */ template class WImage { public: typedef T BaseType; // WImage is an abstract class with no other virtual methods so make the // destructor virtual. virtual ~WImage() = 0; // Accessors IplImage* Ipl() {return image_; } const IplImage* Ipl() const {return image_; } T* ImageData() { return reinterpret_cast(image_->imageData); } const T* ImageData() const { return reinterpret_cast(image_->imageData); } int Width() const {return image_->width; } int Height() const {return image_->height; } // WidthStep is the number of bytes to go to the pixel with the next y coord int WidthStep() const {return image_->widthStep; } int Channels() const {return image_->nChannels; } int ChannelSize() const {return sizeof(T); } // number of bytes per channel // Number of bytes per pixel int PixelSize() const {return Channels() * ChannelSize(); } // Return depth type (e.g. IPL_DEPTH_8U, IPL_DEPTH_32F) which is the number // of bits per channel and with the signed bit set. // This is known at compile time using specializations. int Depth() const; inline const T* Row(int r) const { return reinterpret_cast(image_->imageData + r*image_->widthStep); } inline T* Row(int r) { return reinterpret_cast(image_->imageData + r*image_->widthStep); } // Pixel accessors which returns a pointer to the start of the channel inline T* operator() (int c, int r) { return reinterpret_cast(image_->imageData + r*image_->widthStep) + c*Channels(); } inline const T* operator() (int c, int r) const { return reinterpret_cast(image_->imageData + r*image_->widthStep) + c*Channels(); } // Copy the contents from another image which is just a convenience to cvCopy void CopyFrom(const WImage& src) { cvCopy(src.Ipl(), image_); } // Set contents to zero which is just a convenient to cvSetZero void SetZero() { cvSetZero(image_); } // Construct a view into a region of this image WImageView View(int c, int r, int width, int height); protected: // Disallow copy and assignment WImage(const WImage&); void operator=(const WImage&); explicit WImage(IplImage* img) : image_(img) { assert(!img || img->depth == Depth()); } void SetIpl(IplImage* image) { assert(!image || image->depth == Depth()); image_ = image; } IplImage* image_; }; /** Image class when both the pixel type and number of channels are known at compile time. This wrapper will speed up some of the operations like accessing individual pixels using the () operator. */ template class WImageC : public WImage { public: typedef typename WImage::BaseType BaseType; enum { kChannels = C }; explicit WImageC(IplImage* img) : WImage(img) { assert(!img || img->nChannels == Channels()); } // Construct a view into a region of this image WImageViewC View(int c, int r, int width, int height); // Copy the contents from another image which is just a convenience to cvCopy void CopyFrom(const WImageC& src) { cvCopy(src.Ipl(), WImage::image_); } // WImageC is an abstract class with no other virtual methods so make the // destructor virtual. virtual ~WImageC() = 0; int Channels() const {return C; } protected: // Disallow copy and assignment WImageC(const WImageC&); void operator=(const WImageC&); void SetIpl(IplImage* image) { assert(!image || image->depth == WImage::Depth()); WImage::SetIpl(image); } }; /** Image class which owns the data, so it can be allocated and is always freed. It cannot be copied but can be explicity cloned. */ template class WImageBuffer : public WImage { public: typedef typename WImage::BaseType BaseType; // Default constructor which creates an object that can be WImageBuffer() : WImage(0) {} WImageBuffer(int width, int height, int nchannels) : WImage(0) { Allocate(width, height, nchannels); } // Constructor which takes ownership of a given IplImage so releases // the image on destruction. explicit WImageBuffer(IplImage* img) : WImage(img) {} // Allocate an image. Does nothing if current size is the same as // the new size. void Allocate(int width, int height, int nchannels); // Set the data to point to an image, releasing the old data void SetIpl(IplImage* img) { ReleaseImage(); WImage::SetIpl(img); } // Clone an image which reallocates the image if of a different dimension. void CloneFrom(const WImage& src) { Allocate(src.Width(), src.Height(), src.Channels()); CopyFrom(src); } ~WImageBuffer() { ReleaseImage(); } // Release the image if it isn't null. void ReleaseImage() { if (WImage::image_) { IplImage* image = WImage::image_; cvReleaseImage(&image); WImage::SetIpl(0); } } bool IsNull() const {return WImage::image_ == NULL; } private: // Disallow copy and assignment WImageBuffer(const WImageBuffer&); void operator=(const WImageBuffer&); }; /** Like a WImageBuffer class but when the number of channels is known at compile time. */ template class WImageBufferC : public WImageC { public: typedef typename WImage::BaseType BaseType; enum { kChannels = C }; // Default constructor which creates an object that can be WImageBufferC() : WImageC(0) {} WImageBufferC(int width, int height) : WImageC(0) { Allocate(width, height); } // Constructor which takes ownership of a given IplImage so releases // the image on destruction. explicit WImageBufferC(IplImage* img) : WImageC(img) {} // Allocate an image. Does nothing if current size is the same as // the new size. void Allocate(int width, int height); // Set the data to point to an image, releasing the old data void SetIpl(IplImage* img) { ReleaseImage(); WImageC::SetIpl(img); } // Clone an image which reallocates the image if of a different dimension. void CloneFrom(const WImageC& src) { Allocate(src.Width(), src.Height()); CopyFrom(src); } ~WImageBufferC() { ReleaseImage(); } // Release the image if it isn't null. void ReleaseImage() { if (WImage::image_) { IplImage* image = WImage::image_; cvReleaseImage(&image); WImageC::SetIpl(0); } } bool IsNull() const {return WImage::image_ == NULL; } private: // Disallow copy and assignment WImageBufferC(const WImageBufferC&); void operator=(const WImageBufferC&); }; /** View into an image class which allows treating a subimage as an image or treating external data as an image */ template class WImageView : public WImage { public: typedef typename WImage::BaseType BaseType; // Construct a subimage. No checks are done that the subimage lies // completely inside the original image. WImageView(WImage* img, int c, int r, int width, int height); // Refer to external data. // If not given width_step assumed to be same as width. WImageView(T* data, int width, int height, int channels, int width_step = -1); // Refer to external data. This does NOT take ownership // of the supplied IplImage. WImageView(IplImage* img) : WImage(img) {} // Copy constructor WImageView(const WImage& img) : WImage(0) { header_ = *(img.Ipl()); WImage::SetIpl(&header_); } WImageView& operator=(const WImage& img) { header_ = *(img.Ipl()); WImage::SetIpl(&header_); return *this; } protected: IplImage header_; }; template class WImageViewC : public WImageC { public: typedef typename WImage::BaseType BaseType; enum { kChannels = C }; // Default constructor needed for vectors of views. WImageViewC(); virtual ~WImageViewC() {} // Construct a subimage. No checks are done that the subimage lies // completely inside the original image. WImageViewC(WImageC* img, int c, int r, int width, int height); // Refer to external data WImageViewC(T* data, int width, int height, int width_step = -1); // Refer to external data. This does NOT take ownership // of the supplied IplImage. WImageViewC(IplImage* img) : WImageC(img) {} // Copy constructor which does a shallow copy to allow multiple views // of same data. gcc-4.1.1 gets confused if both versions of // the constructor and assignment operator are not provided. WImageViewC(const WImageC& img) : WImageC(0) { header_ = *(img.Ipl()); WImageC::SetIpl(&header_); } WImageViewC(const WImageViewC& img) : WImageC(0) { header_ = *(img.Ipl()); WImageC::SetIpl(&header_); } WImageViewC& operator=(const WImageC& img) { header_ = *(img.Ipl()); WImageC::SetIpl(&header_); return *this; } WImageViewC& operator=(const WImageViewC& img) { header_ = *(img.Ipl()); WImageC::SetIpl(&header_); return *this; } protected: IplImage header_; }; // Specializations for depth template<> inline int WImage::Depth() const {return IPL_DEPTH_8U; } template<> inline int WImage::Depth() const {return IPL_DEPTH_8S; } template<> inline int WImage::Depth() const {return IPL_DEPTH_16S; } template<> inline int WImage::Depth() const {return IPL_DEPTH_16U; } template<> inline int WImage::Depth() const {return IPL_DEPTH_32S; } template<> inline int WImage::Depth() const {return IPL_DEPTH_32F; } template<> inline int WImage::Depth() const {return IPL_DEPTH_64F; } template inline WImage::~WImage() {} template inline WImageC::~WImageC() {} template inline void WImageBuffer::Allocate(int width, int height, int nchannels) { if (IsNull() || WImage::Width() != width || WImage::Height() != height || WImage::Channels() != nchannels) { ReleaseImage(); WImage::image_ = cvCreateImage(cvSize(width, height), WImage::Depth(), nchannels); } } template inline void WImageBufferC::Allocate(int width, int height) { if (IsNull() || WImage::Width() != width || WImage::Height() != height) { ReleaseImage(); WImageC::SetIpl(cvCreateImage(cvSize(width, height),WImage::Depth(), C)); } } template WImageView::WImageView(WImage* img, int c, int r, int width, int height) : WImage(0) { header_ = *(img->Ipl()); header_.imageData = reinterpret_cast((*img)(c, r)); header_.width = width; header_.height = height; WImage::SetIpl(&header_); } template WImageView::WImageView(T* data, int width, int height, int nchannels, int width_step) : WImage(0) { cvInitImageHeader(&header_, cvSize(width, height), WImage::Depth(), nchannels); header_.imageData = reinterpret_cast(data); if (width_step > 0) { header_.widthStep = width_step; } WImage::SetIpl(&header_); } template WImageViewC::WImageViewC(WImageC* img, int c, int r, int width, int height) : WImageC(0) { header_ = *(img->Ipl()); header_.imageData = reinterpret_cast((*img)(c, r)); header_.width = width; header_.height = height; WImageC::SetIpl(&header_); } template WImageViewC::WImageViewC() : WImageC(0) { cvInitImageHeader(&header_, cvSize(0, 0), WImage::Depth(), C); header_.imageData = reinterpret_cast(0); WImageC::SetIpl(&header_); } template WImageViewC::WImageViewC(T* data, int width, int height, int width_step) : WImageC(0) { cvInitImageHeader(&header_, cvSize(width, height), WImage::Depth(), C); header_.imageData = reinterpret_cast(data); if (width_step > 0) { header_.widthStep = width_step; } WImageC::SetIpl(&header_); } // Construct a view into a region of an image template WImageView WImage::View(int c, int r, int width, int height) { return WImageView(this, c, r, width, height); } template WImageViewC WImageC::View(int c, int r, int width, int height) { return WImageViewC(this, c, r, width, height); } //! @} core } // end of namespace #endif // __cplusplus #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/core.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2015, Intel Corporation, all rights reserved. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. // Copyright (C) 2015, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_CORE_HPP__ #define __OPENCV_CORE_HPP__ #ifndef __cplusplus # error core.hpp header must be compiled as C++ #endif #include "opencv2/core/cvdef.h" #include "opencv2/core/version.hpp" #include "opencv2/core/base.hpp" #include "opencv2/core/cvstd.hpp" #include "opencv2/core/traits.hpp" #include "opencv2/core/matx.hpp" #include "opencv2/core/types.hpp" #include "opencv2/core/mat.hpp" #include "opencv2/core/persistence.hpp" /** @defgroup core Core functionality @{ @defgroup core_basic Basic structures @defgroup core_c C structures and operations @{ @defgroup core_c_glue Connections with C++ @} @defgroup core_array Operations on arrays @defgroup core_xml XML/YAML Persistence @defgroup core_cluster Clustering @defgroup core_utils Utility and system functions and macros @{ @defgroup core_utils_sse SSE utilities @defgroup core_utils_neon NEON utilities @} @defgroup core_opengl OpenGL interoperability @defgroup core_ipp Intel IPP Asynchronous C/C++ Converters @defgroup core_optim Optimization Algorithms @defgroup core_directx DirectX interoperability @defgroup core_eigen Eigen support @defgroup core_opencl OpenCL support @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability @defgroup core_hal Hardware Acceleration Layer @{ @defgroup core_hal_functions Functions @defgroup core_hal_interface Interface @defgroup core_hal_intrin Universal intrinsics @{ @defgroup core_hal_intrin_impl Private implementation helpers @} @} @} */ namespace cv { //! @addtogroup core_utils //! @{ /*! @brief Class passed to an error. This class encapsulates all or almost all necessary information about the error happened in the program. The exception is usually constructed and thrown implicitly via CV_Error and CV_Error_ macros. @see error */ class CV_EXPORTS Exception : public std::exception { public: /*! Default constructor */ Exception(); /*! Full constructor. Normally the constuctor is not called explicitly. Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. */ Exception(int _code, const String& _err, const String& _func, const String& _file, int _line); virtual ~Exception() throw(); /*! \return the error description and the context as a text string. */ virtual const char *what() const throw(); void formatMessage(); String msg; ///< the formatted error message int code; ///< error code @see CVStatus String err; ///< error description String func; ///< function name. Available only when the compiler supports getting it String file; ///< source file name where the error has occured int line; ///< line number in the source file where the error has occured }; /*! @brief Signals an error and raises the exception. By default the function prints information about the error to stderr, then it either stops if cv::setBreakOnError() had been called before or raises the exception. It is possible to alternate error processing by using cv::redirectError(). @param exc the exception raisen. @deprecated drop this version */ CV_EXPORTS void error( const Exception& exc ); enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted //!< independently; this flag and the previous one are //!< mutually exclusive. SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending //!< order. SORT_DESCENDING = 16 //!< each matrix row is sorted in the //!< descending order; this flag and the previous one are also //!< mutually exclusive. }; //! @} core_utils //! @addtogroup core //! @{ //! Covariation flags enum CovarFlags { /** The output covariance matrix is calculated as: \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...],\f] The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of the "scrambled" covariance matrix. */ COVAR_SCRAMBLED = 0, /**The output covariance matrix is calculated as: \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...] \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T,\f] covar will be a square matrix of the same size as the total number of elements in each input vector. One and only one of COVAR_SCRAMBLED and COVAR_NORMAL must be specified.*/ COVAR_NORMAL = 1, /** If the flag is specified, the function does not calculate mean from the input vectors but, instead, uses the passed mean vector. This is useful if mean has been pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In this case, mean is not a mean vector of the input sub-set of vectors but rather the mean vector of the whole set.*/ COVAR_USE_AVG = 2, /** If the flag is specified, the covariance matrix is scaled. In the "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the total number of elements in each input vector. By default (if the flag is not specified), the covariance matrix is not scaled ( scale=1 ).*/ COVAR_SCALE = 4, /** If the flag is specified, all the input vectors are stored as rows of the samples matrix. mean should be a single-row vector in this case.*/ COVAR_ROWS = 8, /** If the flag is specified, all the input vectors are stored as columns of the samples matrix. mean should be a single-column vector in this case.*/ COVAR_COLS = 16 }; //! k-Means flags enum KmeansFlags { /** Select random initial centers in each attempt.*/ KMEANS_RANDOM_CENTERS = 0, /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/ KMEANS_PP_CENTERS = 2, /** During the first (and possibly the only) attempt, use the user-supplied labels instead of computing them from the initial centers. For the second and further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag to specify the exact method.*/ KMEANS_USE_INITIAL_LABELS = 1 }; //! type of line enum LineTypes { FILLED = -1, LINE_4 = 4, //!< 4-connected line LINE_8 = 8, //!< 8-connected line LINE_AA = 16 //!< antialiased line }; //! Only a subset of Hershey fonts //! are supported enum HersheyFonts { FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX) FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX) FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX FONT_ITALIC = 16 //!< flag for italic font }; enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix. REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix. REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix. REDUCE_MIN = 3 //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix. }; /** @brief Swaps two matrices */ CV_EXPORTS void swap(Mat& a, Mat& b); /** @overload */ CV_EXPORTS void swap( UMat& a, UMat& b ); //! @} core //! @addtogroup core_array //! @{ /** @brief Computes the source location of an extrapolated pixel. The function computes and returns the coordinate of a donor pixel corresponding to the specified extrapolated pixel when using the specified extrapolation border mode. For example, if you use cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img , it looks like: @code{.cpp} float val = img.at(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); @endcode Normally, the function is not called directly. It is used inside filtering functions and also in copyMakeBorder. @param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len @param len Length of the array along the corresponding axis. @param borderType Border type, one of the cv::BorderTypes, except for cv::BORDER_TRANSPARENT and cv::BORDER_ISOLATED . When borderType==cv::BORDER_CONSTANT , the function always returns -1, regardless of p and len. @sa copyMakeBorder */ CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType); /** @brief Forms a border around an image. The function copies the source image into the middle of the destination image. The areas to the left, to the right, above and below the copied source image will be filled with extrapolated pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but what other more complex functions, including your own, may do to simplify image boundary handling. The function supports the mode when src is already in the middle of dst . In this case, the function does not copy src itself but simply constructs the border, for example: @code{.cpp} // let border be the same in all directions int border=2; // constructs a larger image to fit both the image and the border Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); // select the middle part of it w/o copying data Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); // convert image from RGB to grayscale cvtColor(rgb, gray, COLOR_RGB2GRAY); // form a border in-place copyMakeBorder(gray, gray_buf, border, border, border, border, BORDER_REPLICATE); // now do some custom filtering ... ... @endcode @note When the source image is a part (ROI) of a bigger image, the function will try to use the pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as if src was not a ROI, use borderType | BORDER_ISOLATED. @param src Source image. @param dst Destination image of the same type as src and the size Size(src.cols+left+right, src.rows+top+bottom) . @param top @param bottom @param left @param right Parameter specifying how many pixels in each direction from the source image rectangle to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs to be built. @param borderType Border type. See borderInterpolate for details. @param value Border value if borderType==BORDER_CONSTANT . @sa borderInterpolate */ CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst, int top, int bottom, int left, int right, int borderType, const Scalar& value = Scalar() ); /** @brief Calculates the per-element sum of two arrays or an array and a scalar. The function add calculates: - Sum of two arrays when both input arrays have the same size and the same number of channels: \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] - Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of elements as `src1.channels()`: \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] - Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of elements as `src2.channels()`: \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each channel is processed independently. The first function in the list above can be replaced with matrix expressions: @code{.cpp} dst = src1 + src2; dst += src1; // equivalent to add(dst, src1, dst); @endcode The input arrays and the output array can all have the same or different depths. For example, you can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit floating-point array. Depth of the output array is determined by the dtype parameter. In the second and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this case, the output array will have the same depth as the input array, be it src1, src2 or both. @note Saturation is not applied when the output array has the depth CV_32S. You may even get result of an incorrect sign in the case of overflow. @param src1 first input array or a scalar. @param src2 second input array or a scalar. @param dst output array that has the same size and number of channels as the input array(s); the depth is defined by dtype or src1/src2. @param mask optional operation mask - 8-bit single channel array, that specifies elements of the output array to be changed. @param dtype optional depth of the output array (see the discussion below). @sa subtract, addWeighted, scaleAdd, Mat::convertTo */ CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), int dtype = -1); /** @brief Calculates the per-element difference between two arrays or array and a scalar. The function subtract calculates: - Difference between two arrays, when both input arrays have the same size and the same number of channels: \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] - Difference between an array and a scalar, when src2 is constructed from Scalar or has the same number of elements as `src1.channels()`: \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] - Difference between a scalar and an array, when src1 is constructed from Scalar or has the same number of elements as `src2.channels()`: \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] - The reverse difference between a scalar and an array in the case of `SubRS`: \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f] where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each channel is processed independently. The first function in the list above can be replaced with matrix expressions: @code{.cpp} dst = src1 - src2; dst -= src1; // equivalent to subtract(dst, src1, dst); @endcode The input arrays and the output array can all have the same or different depths. For example, you can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of the output array is determined by dtype parameter. In the second and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this case the output array will have the same depth as the input array, be it src1, src2 or both. @note Saturation is not applied when the output array has the depth CV_32S. You may even get result of an incorrect sign in the case of overflow. @param src1 first input array or a scalar. @param src2 second input array or a scalar. @param dst output array of the same size and the same number of channels as the input array. @param mask optional operation mask; this is an 8-bit single channel array that specifies elements of the output array to be changed. @param dtype optional depth of the output array @sa add, addWeighted, scaleAdd, Mat::convertTo */ CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), int dtype = -1); /** @brief Calculates the per-element scaled product of two arrays. The function multiply calculates the per-element product of two arrays: \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul . For a not-per-element matrix product, see gemm . @note Saturation is not applied when the output array has the depth CV_32S. You may even get result of an incorrect sign in the case of overflow. @param src1 first input array. @param src2 second input array of the same size and the same type as src1. @param dst output array of the same size and type as src1. @param scale optional scale factor. @param dtype optional depth of the output array @sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, Mat::convertTo */ CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1); /** @brief Performs per-element division of two arrays or a scalar by an array. The functions divide divide one array by another: \f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] or a scalar by an array when there is no src1 : \f[\texttt{dst(I) = saturate(scale/src2(I))}\f] When src2(I) is zero, dst(I) will also be zero. Different channels of multi-channel arrays are processed independently. @note Saturation is not applied when the output array has the depth CV_32S. You may even get result of an incorrect sign in the case of overflow. @param src1 first input array. @param src2 second input array of the same size and type as src1. @param scale scalar factor. @param dst output array of the same size and type as src2. @param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). @sa multiply, add, subtract */ CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1); /** @overload */ CV_EXPORTS_W void divide(double scale, InputArray src2, OutputArray dst, int dtype = -1); /** @brief Calculates the sum of a scaled array and another array. The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates the sum of a scaled array and another array: \f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f] The function can also be emulated with a matrix expression, for example: @code{.cpp} Mat A(3, 3, CV_64F); ... A.row(0) = A.row(1)*2 + A.row(2); @endcode @param src1 first input array. @param alpha scale factor for the first array. @param src2 second input array of the same size and type as src1. @param dst output array of the same size and type as src1. @sa add, addWeighted, subtract, Mat::dot, Mat::convertTo */ CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); /** @brief Calculates the weighted sum of two arrays. The function addWeighted calculates the weighted sum of two arrays as follows: \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each channel is processed independently. The function can be replaced with a matrix expression: @code{.cpp} dst = src1*alpha + src2*beta + gamma; @endcode @note Saturation is not applied when the output array has the depth CV_32S. You may even get result of an incorrect sign in the case of overflow. @param src1 first input array. @param alpha weight of the first array elements. @param src2 second input array of the same size and channel number as src1. @param beta weight of the second array elements. @param gamma scalar added to each sum. @param dst output array that has the same size and number of channels as the input arrays. @param dtype optional depth of the output array; when both input arrays have the same depth, dtype can be set to -1, which will be equivalent to src1.depth(). @sa add, subtract, scaleAdd, Mat::convertTo */ CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray dst, int dtype = -1); /** @brief Scales, calculates absolute values, and converts the result to 8-bit. On each element of the input array, the function convertScaleAbs performs three operations sequentially: scaling, taking an absolute value, conversion to an unsigned 8-bit type: \f[\texttt{dst} (I)= \texttt{saturate\_cast} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f] In case of multi-channel arrays, the function processes each channel independently. When the output is not 8-bit, the operation can be emulated by calling the Mat::convertTo method (or by using matrix expressions) and then by calculating an absolute value of the result. For example: @code{.cpp} Mat_ A(30,30); randu(A, Scalar(-100), Scalar(100)); Mat_ B = A*5 + 3; B = abs(B); // Mat_ B = abs(A*5+3) will also do the job, // but it will allocate a temporary matrix @endcode @param src input array. @param dst output array. @param alpha optional scale factor. @param beta optional delta added to the scaled values. @sa Mat::convertTo, cv::abs(const Mat&) */ CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst, double alpha = 1, double beta = 0); /** @brief Performs a look-up table transform of an array. The function LUT fills the output array with values from the look-up table. Indices of the entries are taken from the input array. That is, the function processes each element of src as follows: \f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f] where \f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f] @param src input array of 8-bit elements. @param lut look-up table of 256 elements; in case of multi-channel input array, the table should either have a single channel (in this case the same table is used for all channels) or the same number of channels as in the input array. @param dst output array of the same size and number of channels as src, and the same depth as lut. @sa convertScaleAbs, Mat::convertTo */ CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst); /** @brief Calculates the sum of array elements. The functions sum calculate and return the sum of array elements, independently for each channel. @param src input array that must have from 1 to 4 channels. @sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce */ CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); /** @brief Counts non-zero array elements. The function returns the number of non-zero elements in src : \f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] @param src single-channel array. @sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix */ CV_EXPORTS_W int countNonZero( InputArray src ); /** @brief Returns the list of locations of non-zero pixels Given a binary matrix (likely returned from an operation such as threshold(), compare(), >, ==, etc, return all of the non-zero indices as a cv::Mat or std::vector (x,y) For example: @code{.cpp} cv::Mat binaryImage; // input, binary image cv::Mat locations; // output, locations of non-zero pixels cv::findNonZero(binaryImage, locations); // access pixel coordinates Point pnt = locations.at(i); @endcode or @code{.cpp} cv::Mat binaryImage; // input, binary image vector locations; // output, locations of non-zero pixels cv::findNonZero(binaryImage, locations); // access pixel coordinates Point pnt = locations[i]; @endcode @param src single-channel array (type CV_8UC1) @param idx the output array, type of cv::Mat or std::vector, corresponding to non-zero indices in the input */ CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); /** @brief Calculates an average (mean) of array elements. The function mean calculates the mean value M of array elements, independently for each channel, and return it: \f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f] When all the mask elements are 0's, the functions return Scalar::all(0) @param src input array that should have from 1 to 4 channels so that the result can be stored in Scalar_ . @param mask optional operation mask. @sa countNonZero, meanStdDev, norm, minMaxLoc */ CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray()); /** Calculates a mean and standard deviation of array elements. The function meanStdDev calculates the mean and the standard deviation M of array elements independently for each channel and returns it via the output parameters: \f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f] When all the mask elements are 0's, the functions return mean=stddev=Scalar::all(0). @note The calculated standard deviation is only the diagonal of the complete normalized covariance matrix. If the full matrix is needed, you can reshape the multi-channel array M x N to the single-channel array M\*N x mtx.channels() (only possible when the matrix is continuous) and then pass the matrix to calcCovarMatrix . @param src input array that should have from 1 to 4 channels so that the results can be stored in Scalar_ 's. @param mean output parameter: calculated mean value. @param stddev output parameter: calculateded standard deviation. @param mask optional operation mask. @sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix */ CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, InputArray mask=noArray()); /** @brief Calculates an absolute array norm, an absolute difference norm, or a relative difference norm. The functions norm calculate an absolute norm of src1 (when there is no src2 ): \f[norm = \forkthree{\|\texttt{src1}\|_{L_{\infty}} = \max _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } { \| \texttt{src1} \| _{L_1} = \sum _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } { \| \texttt{src1} \| _{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) }\f] or an absolute or relative difference norm if src2 is there: \f[norm = \forkthree{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} = \max _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } { \| \texttt{src1} - \texttt{src2} \| _{L_1} = \sum _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } { \| \texttt{src1} - \texttt{src2} \| _{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) }\f] or \f[norm = \forkthree{\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} }{\|\texttt{src2}\|_{L_{\infty}} }}{if \(\texttt{normType} = \texttt{NORM_RELATIVE_INF}\) } { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE_L1}\) } { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE_L2}\) }\f] The functions norm return the calculated norm. When the mask parameter is specified and it is not empty, the norm is calculated only over the region specified by the mask. A multi-channel input arrays are treated as a single-channel, that is, the results for all channels are combined. @param src1 first input array. @param normType type of the norm (see cv::NormTypes). @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. */ CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray()); /** @overload @param src1 first input array. @param src2 second input array of the same size and the same type as src1. @param normType type of the norm (cv::NormTypes). @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. */ CV_EXPORTS_W double norm(InputArray src1, InputArray src2, int normType = NORM_L2, InputArray mask = noArray()); /** @overload @param src first input array. @param normType type of the norm (see cv::NormTypes). */ CV_EXPORTS double norm( const SparseMat& src, int normType ); /** @brief computes PSNR image/video quality metric see http://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio for details @todo document */ CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2); /** @brief naive nearest neighbor finder see http://en.wikipedia.org/wiki/Nearest_neighbor_search @todo document */ CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, OutputArray dist, int dtype, OutputArray nidx, int normType = NORM_L2, int K = 0, InputArray mask = noArray(), int update = 0, bool crosscheck = false); /** @brief Normalizes the norm or value range of an array. The functions normalize scale and shift the input array elements so that \f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that \f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or min-max but modify the whole array, you can use norm and Mat::convertTo. In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, the range transformation for sparse matrices is not allowed since it can shift the zero level. Possible usage with some positive example data: @code{.cpp} vector positiveData = { 2.0, 8.0, 10.0 }; vector normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; // Norm to probability (total count) // sum(numbers) = 20.0 // 2.0 0.1 (2.0/20.0) // 8.0 0.4 (8.0/20.0) // 10.0 0.5 (10.0/20.0) normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); // Norm to unit vector: ||positiveData|| = 1.0 // 2.0 0.15 // 8.0 0.62 // 10.0 0.77 normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); // Norm to max element // 2.0 0.2 (2.0/10.0) // 8.0 0.8 (8.0/10.0) // 10.0 1.0 (10.0/10.0) normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); // Norm to range [0.0;1.0] // 2.0 0.0 (shift to left border) // 8.0 0.75 (6.0/8.0) // 10.0 1.0 (shift to right border) normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); @endcode @param src input array. @param dst output array of the same size as src . @param alpha norm value to normalize to or the lower range boundary in case of the range normalization. @param beta upper range boundary in case of the range normalization; it is not used for the norm normalization. @param norm_type normalization type (see cv::NormTypes). @param dtype when negative, the output array has the same type as src; otherwise, it has the same number of channels as src and the depth =CV_MAT_DEPTH(dtype). @param mask optional operation mask. @sa norm, Mat::convertTo, SparseMat::convertTo */ CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray()); /** @overload @param src input array. @param dst output array of the same size as src . @param alpha norm value to normalize to or the lower range boundary in case of the range normalization. @param normType normalization type (see cv::NormTypes). */ CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); /** @brief Finds the global minimum and maximum in an array. The functions minMaxLoc find the minimum and maximum element values and their positions. The extremums are searched across the whole array or, if mask is not an empty array, in the specified array region. The functions do not work with multi-channel arrays. If you need to find minimum or maximum elements across all the channels, use Mat::reshape first to reinterpret the array as single-channel. Or you may extract the particular channel using either extractImageCOI , or mixChannels , or split . @param src input single-channel array. @param minVal pointer to the returned minimum value; NULL is used if not required. @param maxVal pointer to the returned maximum value; NULL is used if not required. @param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required. @param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required. @param mask optional mask used to select a sub-array. @sa max, min, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape */ CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0, CV_OUT Point* maxLoc = 0, InputArray mask = noArray()); /** @brief Finds the global minimum and maximum in an array The function minMaxIdx finds the minimum and maximum element values and their positions. The extremums are searched across the whole array or, if mask is not an empty array, in the specified array region. The function does not work with multi-channel arrays. If you need to find minimum or maximum elements across all the channels, use Mat::reshape first to reinterpret the array as single-channel. Or you may extract the particular channel using either extractImageCOI , or mixChannels , or split . In case of a sparse matrix, the minimum is found among non-zero elements only. @note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2 dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be (i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be (0,j1)/(0,j2)). @param src input single-channel array. @param minVal pointer to the returned minimum value; NULL is used if not required. @param maxVal pointer to the returned maximum value; NULL is used if not required. @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element in each dimension are stored there sequentially. @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. @param mask specified array region */ CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0, int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray()); /** @overload @param a input single-channel array. @param minVal pointer to the returned minimum value; NULL is used if not required. @param maxVal pointer to the returned maximum value; NULL is used if not required. @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element in each dimension are stored there sequentially. @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. */ CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, double* maxVal, int* minIdx = 0, int* maxIdx = 0); /** @brief Reduces a matrix to a vector. The function reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of a raster image. In case of REDUCE_SUM and REDUCE_AVG , the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes. @param src input 2D matrix. @param dst output vector. Its size and type is defined by dim and dtype parameters. @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row. 1 means that the matrix is reduced to a single column. @param rtype reduction operation that could be one of cv::ReduceTypes @param dtype when negative, the output vector will have the same type as the input matrix, otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). @sa repeat */ CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); /** @brief Creates one multi-channel array out of several single-channel ones. The function merge merges several arrays to make a single multi-channel array. That is, each element of the output array will be a concatenation of the elements of the input arrays, where elements of i-th input array are treated as mv[i].channels()-element vectors. The function cv::split does the reverse operation. If you need to shuffle channels in some other advanced way, use cv::mixChannels. @param mv input array of matrices to be merged; all the matrices in mv must have the same size and the same depth. @param count number of input matrices when mv is a plain C array; it must be greater than zero. @param dst output array of the same size and the same depth as mv[0]; The number of channels will be equal to the parameter count. @sa mixChannels, split, Mat::reshape */ CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); /** @overload @param mv input vector of matrices to be merged; all the matrices in mv must have the same size and the same depth. @param dst output array of the same size and the same depth as mv[0]; The number of channels will be the total number of channels in the matrix array. */ CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); /** @brief Divides a multi-channel array into several single-channel arrays. The functions split split a multi-channel array into separate single-channel arrays: \f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] If you need to extract a single channel or do some other sophisticated channel permutation, use mixChannels . @param src input multi-channel array. @param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are reallocated, if needed. @sa merge, mixChannels, cvtColor */ CV_EXPORTS void split(const Mat& src, Mat* mvbegin); /** @overload @param m input multi-channel array. @param mv output vector of arrays; the arrays themselves are reallocated, if needed. */ CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); /** @brief Copies specified channels from input arrays to the specified channels of output arrays. The function cv::mixChannels provides an advanced mechanism for shuffling image channels. cv::split and cv::merge and some forms of cv::cvtColor are partial cases of cv::mixChannels . In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R channels swapped) and a separate alpha-channel image: @code{.cpp} Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) ); Mat bgr( bgra.rows, bgra.cols, CV_8UC3 ); Mat alpha( bgra.rows, bgra.cols, CV_8UC1 ); // forming an array of matrices is a quite efficient operation, // because the matrix data is not copied, only the headers Mat out[] = { bgr, alpha }; // bgra[0] -> bgr[2], bgra[1] -> bgr[1], // bgra[2] -> bgr[0], bgra[3] -> alpha[0] int from_to[] = { 0,2, 1,1, 2,0, 3,3 }; mixChannels( &bgra, 1, out, 2, from_to, 4 ); @endcode @note Unlike many other new-style C++ functions in OpenCV (see the introduction section and Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the function. @param src input array or vector of matrices; all of the matrices must have the same size and the same depth. @param nsrcs number of matrices in `src`. @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and depth must be the same as in `src[0]`. @param ndsts number of matrices in `dst`. @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to src[0].channels()-1, the second input image channels are indexed from src[0].channels() to src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is filled with zero . @param npairs number of index pairs in `fromTo`. @sa cv::split, cv::merge, cv::cvtColor */ CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, const int* fromTo, size_t npairs); /** @overload @param src input array or vector of matrices; all of the matrices must have the same size and the same depth. @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and depth must be the same as in src[0]. @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to src[0].channels()-1, the second input image channels are indexed from src[0].channels() to src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is filled with zero . @param npairs number of index pairs in fromTo. */ CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, const int* fromTo, size_t npairs); /** @overload @param src input array or vector of matrices; all of the matrices must have the same size and the same depth. @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and depth must be the same as in src[0]. @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to src[0].channels()-1, the second input image channels are indexed from src[0].channels() to src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is filled with zero . */ CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, const std::vector& fromTo); /** @brief extracts a single channel from src (coi is 0-based index) @todo document */ CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi); /** @brief inserts a single channel to dst (coi is 0-based index) @todo document */ CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); /** @brief Flips a 2D array around vertical, horizontal, or both axes. The function flip flips the array in one of three different ways (row and column indices are 0-based): \f[\texttt{dst} _{ij} = \left\{ \begin{array}{l l} \texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ \texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ \texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ \end{array} \right.\f] The example scenarios of using the function are the following: * Vertical flipping of the image (flipCode == 0) to switch between top-left and bottom-left image origin. This is a typical operation in video processing on Microsoft Windows\* OS. * Horizontal flipping of the image with the subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry (flipCode \> 0). * Simultaneous horizontal and vertical flipping of the image with the subsequent shift and absolute difference calculation to check for a central symmetry (flipCode \< 0). * Reversing the order of point arrays (flipCode \> 0 or flipCode == 0). @param src input array. @param dst output array of the same size and type as src. @param flipCode a flag to specify how to flip the array; 0 means flipping around the x-axis and positive value (for example, 1) means flipping around y-axis. Negative value (for example, -1) means flipping around both axes. @sa transpose , repeat , completeSymm */ CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); /** @brief Fills the output array with repeated copies of the input array. The functions repeat duplicate the input array one or more times along each of the two axes: \f[\texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }\f] The second variant of the function is more convenient to use with @ref MatrixExpressions. @param src input array to replicate. @param dst output array of the same type as src. @param ny Flag to specify how many times the src is repeated along the vertical axis. @param nx Flag to specify how many times the src is repeated along the horizontal axis. @sa reduce */ CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst); /** @overload @param src input array to replicate. @param ny Flag to specify how many times the src is repeated along the vertical axis. @param nx Flag to specify how many times the src is repeated along the horizontal axis. */ CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx); /** @brief Applies horizontal concatenation to given matrices. The function horizontally concatenates two or more cv::Mat matrices (with the same number of rows). @code{.cpp} cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; cv::Mat out; cv::hconcat( matArray, 3, out ); //out: //[1, 2, 3; // 1, 2, 3; // 1, 2, 3; // 1, 2, 3] @endcode @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. @param nsrc number of matrices in src. @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. @sa cv::vconcat(const Mat*, size_t, OutputArray), @sa cv::vconcat(InputArrayOfArrays, OutputArray) and @sa cv::vconcat(InputArray, InputArray, OutputArray) */ CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst); /** @overload @code{.cpp} cv::Mat_ A = (cv::Mat_(3, 2) << 1, 4, 2, 5, 3, 6); cv::Mat_ B = (cv::Mat_(3, 2) << 7, 10, 8, 11, 9, 12); cv::Mat C; cv::hconcat(A, B, C); //C: //[1, 4, 7, 10; // 2, 5, 8, 11; // 3, 6, 9, 12] @endcode @param src1 first input array to be considered for horizontal concatenation. @param src2 second input array to be considered for horizontal concatenation. @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. */ CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); /** @overload @code{.cpp} std::vector matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; cv::Mat out; cv::hconcat( matrices, out ); //out: //[1, 2, 3; // 1, 2, 3; // 1, 2, 3; // 1, 2, 3] @endcode @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. same depth. */ CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); /** @brief Applies vertical concatenation to given matrices. The function vertically concatenates two or more cv::Mat matrices (with the same number of cols). @code{.cpp} cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; cv::Mat out; cv::vconcat( matArray, 3, out ); //out: //[1, 1, 1, 1; // 2, 2, 2, 2; // 3, 3, 3, 3] @endcode @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. @param nsrc number of matrices in src. @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. @sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray) */ CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); /** @overload @code{.cpp} cv::Mat_ A = (cv::Mat_(3, 2) << 1, 7, 2, 8, 3, 9); cv::Mat_ B = (cv::Mat_(3, 2) << 4, 10, 5, 11, 6, 12); cv::Mat C; cv::vconcat(A, B, C); //C: //[1, 7; // 2, 8; // 3, 9; // 4, 10; // 5, 11; // 6, 12] @endcode @param src1 first input array to be considered for vertical concatenation. @param src2 second input array to be considered for vertical concatenation. @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. */ CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); /** @overload @code{.cpp} std::vector matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; cv::Mat out; cv::vconcat( matrices, out ); //out: //[1, 1, 1, 1; // 2, 2, 2, 2; // 3, 3, 3, 3] @endcode @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. same depth. */ CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); /** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2) Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar. The function calculates the per-element bit-wise logical conjunction for: * Two arrays when src1 and src2 have the same size: \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] * An array and a scalar when src2 is constructed from Scalar or has the same number of elements as `src1.channels()`: \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] * A scalar and an array when src1 is constructed from Scalar or has the same number of elements as `src2.channels()`: \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] In case of floating-point arrays, their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. In case of multi-channel arrays, each channel is processed independently. In the second and third cases above, the scalar is first converted to the array type. @param src1 first input array or a scalar. @param src2 second input array or a scalar. @param dst output array that has the same size and type as the input arrays. @param mask optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. */ CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray()); /** @brief Calculates the per-element bit-wise disjunction of two arrays or an array and a scalar. The function calculates the per-element bit-wise logical disjunction for: * Two arrays when src1 and src2 have the same size: \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] * An array and a scalar when src2 is constructed from Scalar or has the same number of elements as `src1.channels()`: \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] * A scalar and an array when src1 is constructed from Scalar or has the same number of elements as `src2.channels()`: \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] In case of floating-point arrays, their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. In case of multi-channel arrays, each channel is processed independently. In the second and third cases above, the scalar is first converted to the array type. @param src1 first input array or a scalar. @param src2 second input array or a scalar. @param dst output array that has the same size and type as the input arrays. @param mask optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. */ CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray()); /** @brief Calculates the per-element bit-wise "exclusive or" operation on two arrays or an array and a scalar. The function calculates the per-element bit-wise logical "exclusive-or" operation for: * Two arrays when src1 and src2 have the same size: \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] * An array and a scalar when src2 is constructed from Scalar or has the same number of elements as `src1.channels()`: \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] * A scalar and an array when src1 is constructed from Scalar or has the same number of elements as `src2.channels()`: \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] In case of floating-point arrays, their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. In case of multi-channel arrays, each channel is processed independently. In the 2nd and 3rd cases above, the scalar is first converted to the array type. @param src1 first input array or a scalar. @param src2 second input array or a scalar. @param dst output array that has the same size and type as the input arrays. @param mask optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. */ CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray()); /** @brief Inverts every bit of an array. The function calculates per-element bit-wise inversion of the input array: \f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] In case of a floating-point input array, its machine-specific bit representation (usually IEEE754-compliant) is used for the operation. In case of multi-channel arrays, each channel is processed independently. @param src input array. @param dst output array that has the same size and type as the input array. @param mask optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. */ CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, InputArray mask = noArray()); /** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar. The function absdiff calculates: * Absolute difference between two arrays when they have the same size and type: \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] * Absolute difference between an array and a scalar when the second array is constructed from Scalar or has as many elements as the number of channels in `src1`: \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f] * Absolute difference between a scalar and an array when the first array is constructed from Scalar or has as many elements as the number of channels in `src2`: \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f] where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each channel is processed independently. @note Saturation is not applied when the arrays have the depth CV_32S. You may even get a negative value in the case of overflow. @param src1 first input array or a scalar. @param src2 second input array or a scalar. @param dst output array that has the same size and type as input arrays. @sa cv::abs(const Mat&) */ CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); /** @brief Checks if array elements lie between the elements of two other arrays. The function checks the range as follows: - For every element of a single-channel input array: \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f] - For two-channel arrays: \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f] - and so forth. That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the specified 1D, 2D, 3D, ... box and 0 otherwise. When the lower and/or upper boundary parameters are scalars, the indexes (I) at lowerb and upperb in the above formulas should be omitted. @param src first input array. @param lowerb inclusive lower boundary array or a scalar. @param upperb inclusive upper boundary array or a scalar. @param dst output array of the same size as src and CV_8U type. */ CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst); /** @brief Performs the per-element comparison of two arrays or an array and scalar value. The function compares: * Elements of two arrays when src1 and src2 have the same size: \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f] * Elements of src1 with a scalar src2 when src2 is constructed from Scalar or has a single element: \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f] * src1 with elements of src2 when src1 is constructed from Scalar or has a single element: \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f] When the comparison result is true, the corresponding element of output array is set to 255. The comparison operations can be replaced with the equivalent matrix expressions: @code{.cpp} Mat dst1 = src1 >= src2; Mat dst2 = src1 < 8; ... @endcode @param src1 first input array or a scalar; when it is an array, it must have a single channel. @param src2 second input array or a scalar; when it is an array, it must have a single channel. @param dst output array of type ref CV_8U that has the same size and the same number of channels as the input arrays. @param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes) @sa checkRange, min, max, threshold */ CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); /** @brief Calculates per-element minimum of two arrays or an array and a scalar. The functions min calculate the per-element minimum of two arrays: \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] or array and a scalar: \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f] @param src1 first input array. @param src2 second input array of the same size and type as src1. @param dst output array of the same size and type as src1. @sa max, compare, inRange, minMaxLoc */ CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst); /** @overload needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) */ CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); /** @overload needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) */ CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst); /** @brief Calculates per-element maximum of two arrays or an array and a scalar. The functions max calculate the per-element maximum of two arrays: \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] or array and a scalar: \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f] @param src1 first input array. @param src2 second input array of the same size and type as src1 . @param dst output array of the same size and type as src1. @sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions */ CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst); /** @overload needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) */ CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); /** @overload needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) */ CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst); /** @brief Calculates a square root of array elements. The functions sqrt calculate a square root of each input array element. In case of multi-channel arrays, each channel is processed independently. The accuracy is approximately the same as of the built-in std::sqrt . @param src input floating-point array. @param dst output array of the same size and type as src. */ CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); /** @brief Raises every array element to a power. The function pow raises every element of the input array to power : \f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f] So, for a non-integer power exponent, the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations. In the example below, computing the 5th root of array src shows: @code{.cpp} Mat mask = src < 0; pow(src, 1./5, dst); subtract(Scalar::all(0), dst, dst, mask); @endcode For some values of power, such as integer values, 0.5 and -0.5, specialized faster algorithms are used. Special values (NaN, Inf) are not handled. @param src input array. @param power exponent of power. @param dst output array of the same size and type as src. @sa sqrt, exp, log, cartToPolar, polarToCart */ CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); /** @brief Calculates the exponent of every array element. The function exp calculates the exponent of every element of the input array: \f[\texttt{dst} [I] = e^{ src(I) }\f] The maximum relative error is about 7e-6 for single-precision input and less than 1e-10 for double-precision input. Currently, the function converts denormalized values to zeros on output. Special values (NaN, Inf) are not handled. @param src input array. @param dst output array of the same size and type as src. @sa log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude */ CV_EXPORTS_W void exp(InputArray src, OutputArray dst); /** @brief Calculates the natural logarithm of every array element. The function log calculates the natural logarithm of the absolute value of every element of the input array: \f[\texttt{dst} (I) = \fork{\log |\texttt{src}(I)|}{if \(\texttt{src}(I) \ne 0\) }{\texttt{C}}{otherwise}\f] where C is a large negative number (about -700 in the current implementation). The maximum relative error is about 7e-6 for single-precision input and less than 1e-10 for double-precision input. Special values (NaN, Inf) are not handled. @param src input array. @param dst output array of the same size and type as src . @sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude */ CV_EXPORTS_W void log(InputArray src, OutputArray dst); /** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. The function polarToCart calculates the Cartesian coordinates of each 2D vector represented by the corresponding elements of magnitude and angle: \f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] The relative accuracy of the estimated coordinates is about 1e-6. @param magnitude input floating-point array of magnitudes of 2D vectors; it can be an empty matrix (=Mat()), in this case, the function assumes that all the magnitudes are =1; if it is not empty, it must have the same size and type as angle. @param angle input floating-point array of angles of 2D vectors. @param x output array of x-coordinates of 2D vectors; it has the same size and type as angle. @param y output array of y-coordinates of 2D vectors; it has the same size and type as angle. @param angleInDegrees when true, the input angles are measured in degrees, otherwise, they are measured in radians. @sa cartToPolar, magnitude, phase, exp, log, pow, sqrt */ CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, OutputArray x, OutputArray y, bool angleInDegrees = false); /** @brief Calculates the magnitude and angle of 2D vectors. The function cartToPolar calculates either the magnitude, angle, or both for every 2D vector (x(I),y(I)): \f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] The angles are calculated with accuracy about 0.3 degrees. For the point (0,0), the angle is set to 0. @param x array of x-coordinates; this must be a single-precision or double-precision floating-point array. @param y array of y-coordinates, that must have the same size and same type as x. @param magnitude output array of magnitudes of the same size and type as x. @param angle output array of angles that has the same size and type as x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). @param angleInDegrees a flag, indicating whether the angles are measured in radians (which is by default), or in degrees. @sa Sobel, Scharr */ CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y, OutputArray magnitude, OutputArray angle, bool angleInDegrees = false); /** @brief Calculates the rotation angle of 2D vectors. The function phase calculates the rotation angle of each 2D vector that is formed from the corresponding elements of x and y : \f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , the corresponding angle(I) is set to 0. @param x input floating-point array of x-coordinates of 2D vectors. @param y input array of y-coordinates of 2D vectors; it must have the same size and the same type as x. @param angle output array of vector angles; it has the same size and same type as x . @param angleInDegrees when true, the function calculates the angle in degrees, otherwise, they are measured in radians. */ CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees = false); /** @brief Calculates the magnitude of 2D vectors. The function magnitude calculates the magnitude of 2D vectors formed from the corresponding elements of x and y arrays: \f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f] @param x floating-point array of x-coordinates of the vectors. @param y floating-point array of y-coordinates of the vectors; it must have the same size as x. @param magnitude output array of the same size and type as x. @sa cartToPolar, polarToCart, phase, sqrt */ CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); /** @brief Checks every element of an input array for invalid values. The functions checkRange check that every array element is neither NaN nor infinite. When minVal \> -DBL_MAX and maxVal \< DBL_MAX, the functions also check that each value is between minVal and maxVal. In case of multi-channel arrays, each channel is processed independently. If some values are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the functions either return false (when quiet=true) or throw an exception. @param a input array. @param quiet a flag, indicating whether the functions quietly return false when the array elements are out of range or they throw an exception. @param pos optional output parameter, when not NULL, must be a pointer to array of src.dims elements. @param minVal inclusive lower boundary of valid values range. @param maxVal exclusive upper boundary of valid values range. */ CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0, double minVal = -DBL_MAX, double maxVal = DBL_MAX); /** @brief converts NaN's to the given number */ CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0); /** @brief Performs generalized matrix multiplication. The function performs generalized matrix multiplication similar to the gemm functions in BLAS level 3. For example, `gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)` corresponds to \f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f] In case of complex (two-channel) data, performed a complex matrix multiplication. The function can be replaced with a matrix expression. For example, the above call can be replaced with: @code{.cpp} dst = alpha*src1.t()*src2 + beta*src3.t(); @endcode @param src1 first multiplied input matrix that could be real(CV_32FC1, CV_64FC1) or complex(CV_32FC2, CV_64FC2). @param src2 second multiplied input matrix of the same type as src1. @param alpha weight of the matrix product. @param src3 third optional delta matrix added to the matrix product; it should have the same type as src1 and src2. @param beta weight of src3. @param dst output matrix; it has the proper size and the same type as input matrices. @param flags operation flags (cv::GemmFlags) @sa mulTransposed , transform */ CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, InputArray src3, double beta, OutputArray dst, int flags = 0); /** @brief Calculates the product of a matrix and its transposition. The function mulTransposed calculates the product of src and its transposition: \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f] if aTa=true , and \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f] otherwise. The function is used to calculate the covariance matrix. With zero delta, it can be used as a faster substitute for general matrix product A\*B when B=A' @param src input single-channel matrix. Note that unlike gemm, the function can multiply not only floating-point matrices. @param dst output square matrix. @param aTa Flag specifying the multiplication ordering. See the description below. @param delta Optional delta matrix subtracted from src before the multiplication. When the matrix is empty ( delta=noArray() ), it is assumed to be zero, that is, nothing is subtracted. If it has the same size as src , it is simply subtracted. Otherwise, it is "repeated" (see repeat ) to cover the full src and then subtracted. Type of the delta matrix, when it is not empty, must be the same as the type of created output matrix. See the dtype parameter description below. @param scale Optional scale factor for the matrix product. @param dtype Optional type of the output matrix. When it is negative, the output matrix will have the same type as src . Otherwise, it will be type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . @sa calcCovarMatrix, gemm, repeat, reduce */ CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa, InputArray delta = noArray(), double scale = 1, int dtype = -1 ); /** @brief Transposes a matrix. The function transpose transposes the matrix src : \f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] @note No complex conjugation is done in case of a complex matrix. It it should be done separately if needed. @param src input array. @param dst output array of the same type as src. */ CV_EXPORTS_W void transpose(InputArray src, OutputArray dst); /** @brief Performs the matrix transformation of every array element. The function transform performs the matrix transformation of every element of the array src and stores the results in dst : \f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f] (when m.cols=src.channels() ), or \f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f] (when m.cols=src.channels()+1 ) Every element of the N -channel array src is interpreted as N -element vector that is transformed using the M x N or M x (N+1) matrix m to M-element vector - the corresponding element of the output array dst . The function may be used for geometrical transformation of N -dimensional points, arbitrary linear color space transformation (such as various kinds of RGB to YUV transforms), shuffling the image channels, and so forth. @param src input array that must have as many channels (1 to 4) as m.cols or m.cols-1. @param dst output array of the same size and depth as src; it has as many channels as m.rows. @param m transformation 2x2 or 2x3 floating-point matrix. @sa perspectiveTransform, getAffineTransform, estimateRigidTransform, warpAffine, warpPerspective */ CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); /** @brief Performs the perspective matrix transformation of vectors. The function perspectiveTransform transforms every element of src by treating it as a 2D or 3D vector, in the following way: \f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f] where \f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f] and \f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f] Here a 3D vector transformation is shown. In case of a 2D vector transformation, the z component is omitted. @note The function transforms a sparse set of 2D or 3D vectors. If you want to transform an image using perspective transformation, use warpPerspective . If you have an inverse problem, that is, you want to compute the most probable perspective transformation out of several pairs of corresponding points, you can use getPerspectiveTransform or findHomography . @param src input two-channel or three-channel floating-point array; each element is a 2D/3D vector to be transformed. @param dst output array of the same size and type as src. @param m 3x3 or 4x4 floating-point transformation matrix. @sa transform, warpPerspective, getPerspectiveTransform, findHomography */ CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); /** @brief Copies the lower or the upper half of a square matrix to another half. The function completeSymm copies the lower half of a square matrix to its another half. The matrix diagonal remains unchanged: * \f$\texttt{mtx}_{ij}=\texttt{mtx}_{ji}\f$ for \f$i > j\f$ if lowerToUpper=false * \f$\texttt{mtx}_{ij}=\texttt{mtx}_{ji}\f$ for \f$i < j\f$ if lowerToUpper=true @param mtx input-output floating-point square matrix. @param lowerToUpper operation flag; if true, the lower half is copied to the upper half. Otherwise, the upper half is copied to the lower half. @sa flip, transpose */ CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper = false); /** @brief Initializes a scaled identity matrix. The function setIdentity initializes a scaled identity matrix: \f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f] The function can also be emulated using the matrix initializers and the matrix expressions: @code Mat A = Mat::eye(4, 3, CV_32F)*5; // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] @endcode @param mtx matrix to initialize (not necessarily square). @param s value to assign to diagonal elements. @sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= */ CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1)); /** @brief Returns the determinant of a square floating-point matrix. The function determinant calculates and returns the determinant of the specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the direct method is used. For larger matrices, the function uses LU factorization with partial pivoting. For symmetric positively-determined matrices, it is also possible to use eigen decomposition to calculate the determinant. @param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and square size. @sa trace, invert, solve, eigen, @ref MatrixExpressions */ CV_EXPORTS_W double determinant(InputArray mtx); /** @brief Returns the trace of a matrix. The function trace returns the sum of the diagonal elements of the matrix mtx . \f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f] @param mtx input matrix. */ CV_EXPORTS_W Scalar trace(InputArray mtx); /** @brief Finds the inverse or pseudo-inverse of a matrix. The function invert inverts the matrix src and stores the result in dst . When the matrix src is singular or non-square, the function calculates the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is minimal, where I is an identity matrix. In case of the DECOMP_LU method, the function returns non-zero value if the inverse has been successfully calculated and 0 if src is singular. In case of the DECOMP_SVD method, the function returns the inverse condition number of src (the ratio of the smallest singular value to the largest singular value) and 0 if src is singular. The SVD method calculates a pseudo-inverse matrix if src is singular. Similarly to DECOMP_LU, the method DECOMP_CHOLESKY works only with non-singular square matrices that should also be symmetrical and positively defined. In this case, the function stores the inverted matrix in dst and returns non-zero. Otherwise, it returns 0. @param src input floating-point M x N matrix. @param dst output matrix of N x M size and the same type as src. @param flags inversion method (cv::DecompTypes) @sa solve, SVD */ CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU); /** @brief Solves one or more linear systems or least-squares problems. The function solve solves a linear system or least-squares problem (the latter is possible with SVD or QR methods, or by specifying the flag DECOMP_NORMAL ): \f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f] If DECOMP_LU or DECOMP_CHOLESKY method is used, the function returns 1 if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise, it returns 0. In the latter case, dst is not valid. Other methods find a pseudo-solution in case of a singular left-hand side part. @note If you want to find a unity-norm solution of an under-defined singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve will not do the work. Use SVD::solveZ instead. @param src1 input matrix on the left-hand side of the system. @param src2 input matrix on the right-hand side of the system. @param dst output solution. @param flags solution (matrix inversion) method (cv::DecompTypes) @sa invert, SVD, eigen */ CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, OutputArray dst, int flags = DECOMP_LU); /** @brief Sorts each row or each column of a matrix. The function sort sorts each matrix row or each matrix column in ascending or descending order. So you should pass two operation flags to get desired behaviour. If you want to sort matrix rows or columns lexicographically, you can use STL std::sort generic function with the proper comparison predicate. @param src input single-channel array. @param dst output array of the same size and type as src. @param flags operation flags, a combination of cv::SortFlags @sa sortIdx, randShuffle */ CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags); /** @brief Sorts each row or each column of a matrix. The function sortIdx sorts each matrix row or each matrix column in the ascending or descending order. So you should pass two operation flags to get desired behaviour. Instead of reordering the elements themselves, it stores the indices of sorted elements in the output array. For example: @code Mat A = Mat::eye(3,3,CV_32F), B; sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); // B will probably contain // (because of equal elements in A some permutations are possible): // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] @endcode @param src input single-channel array. @param dst output integer array of the same size as src. @param flags operation flags that could be a combination of cv::SortFlags @sa sort, randShuffle */ CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags); /** @brief Finds the real roots of a cubic equation. The function solveCubic finds the real roots of a cubic equation: - if coeffs is a 4-element vector: \f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f] - if coeffs is a 3-element vector: \f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f] The roots are stored in the roots array. @param coeffs equation coefficients, an array of 3 or 4 elements. @param roots output array of real roots that has 1 or 3 elements. */ CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots); /** @brief Finds the real or complex roots of a polynomial equation. The function solvePoly finds real and complex roots of a polynomial equation: \f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f] @param coeffs array of polynomial coefficients. @param roots output (complex) array of roots. @param maxIters maximum number of iterations the algorithm does. */ CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300); /** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix. The functions eigen calculate just eigenvalues, or eigenvalues and eigenvectors of the symmetric matrix src: @code src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() @endcode @note in the new and the old interfaces different ordering of eigenvalues and eigenvectors parameters is used. @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical (src ^T^ == src). @param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored in the descending order. @param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. @sa completeSymm , PCA */ CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors = noArray()); /** @brief Calculates the covariance matrix of a set of vectors. The functions calcCovarMatrix calculate the covariance matrix and, optionally, the mean vector of the set of input vectors. @param samples samples stored as separate matrices @param nsamples number of samples @param covar output covariance matrix of the type ctype and square size. @param mean input or output (depending on the flags) array as the average value of the input vectors. @param flags operation flags as a combination of cv::CovarFlags @param ctype type of the matrixl; it equals 'CV_64F' by default. @sa PCA, mulTransposed, Mahalanobis @todo InputArrayOfArrays */ CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, int flags, int ctype = CV_64F); /** @overload @note use cv::COVAR_ROWS or cv::COVAR_COLS flag @param samples samples stored as rows/columns of a single matrix. @param covar output covariance matrix of the type ctype and square size. @param mean input or output (depending on the flags) array as the average value of the input vectors. @param flags operation flags as a combination of cv::CovarFlags @param ctype type of the matrixl; it equals 'CV_64F' by default. */ CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, InputOutputArray mean, int flags, int ctype = CV_64F); /** wrap PCA::operator() */ CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, OutputArray eigenvectors, int maxComponents = 0); /** wrap PCA::operator() */ CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, OutputArray eigenvectors, double retainedVariance); /** wrap PCA::project */ CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, InputArray eigenvectors, OutputArray result); /** wrap PCA::backProject */ CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, InputArray eigenvectors, OutputArray result); /** wrap SVD::compute */ CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 ); /** wrap SVD::backSubst */ CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt, InputArray rhs, OutputArray dst ); /** @brief Calculates the Mahalanobis distance between two vectors. The function Mahalanobis calculates and returns the weighted distance between two vectors: \f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f] The covariance matrix may be calculated using the cv::calcCovarMatrix function and then inverted using the invert function (preferably using the cv::DECOMP_SVD method, as the most accurate). @param v1 first 1D input vector. @param v2 second 1D input vector. @param icovar inverse covariance matrix. */ CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar); /** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. The function performs one of the following: - Forward the Fourier transform of a 1D vector of N elements: \f[Y = F^{(N)} \cdot X,\f] where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$ - Inverse the Fourier transform of a 1D vector of N elements: \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f] where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$ - Forward the 2D Fourier transform of a M x N matrix: \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f] - Inverse the 2D Fourier transform of a M x N matrix: \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f] In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* (complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here is how 2D *CCS* spectrum looks: \f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f] In case of 1D transform of a real vector, the output looks like the first row of the matrix above. So, the function chooses an operation mode depending on the flags and size of the input array: - If DFT_ROWS is set or the input array has a single row or single column, the function performs a 1D forward or inverse transform of each row of a matrix when DFT_ROWS is set. Otherwise, it performs a 2D transform. - If the input array is real and DFT_INVERSE is not set, the function performs a forward 1D or 2D transform: - When DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as input. - When DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as input. In case of 2D transform, it uses the packed format as shown above. In case of a single 1D transform, it looks like the first row of the matrix above. In case of multiple 1D transforms (when using the DFT_ROWS flag), each row of the output matrix looks like the first row of the matrix above. - If the input array is complex and either DFT_INVERSE or DFT_REAL_OUTPUT are not set, the output is a complex array of the same size as input. The function performs a forward or inverse 1D or 2D transform of the whole input array or each row of the input array independently, depending on the flags DFT_INVERSE and DFT_ROWS. - When DFT_INVERSE is set and the input array is real, or it is complex but DFT_REAL_OUTPUT is set, the output is a real array of the same size as input. The function performs a 1D or 2D inverse transformation of the whole input array or each individual row, depending on the flags DFT_INVERSE and DFT_ROWS. If DFT_SCALE is set, the scaling is done after the transformation. Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize method. The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: @code void convolveDFT(InputArray A, InputArray B, OutputArray C) { // reallocate the output array if needed C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type()); Size dftSize; // calculate the size of DFT transform dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); // allocate temporary buffers and initialize them with 0's Mat tempA(dftSize, A.type(), Scalar::all(0)); Mat tempB(dftSize, B.type(), Scalar::all(0)); // copy A and B to the top-left corners of tempA and tempB, respectively Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); A.copyTo(roiA); Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); B.copyTo(roiB); // now transform the padded A & B in-place; // use "nonzeroRows" hint for faster processing dft(tempA, tempA, 0, A.rows); dft(tempB, tempB, 0, B.rows); // multiply the spectrums; // the function handles packed spectrum representations well mulSpectrums(tempA, tempB, tempA); // transform the product back from the frequency domain. // Even though all the result rows will be non-zero, // you need only the first C.rows of them, and thus you // pass nonzeroRows == C.rows dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); // now copy the result back to C. tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); // all the temporary buffers will be deallocated automatically } @endcode To optimize this sample, consider the following approaches: - Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols) rightmost columns of the matrices. - This DFT-based convolution does not have to be applied to the whole big arrays, especially if B is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts. To do this, you need to split the output array C into multiple tiles. For each tile, estimate which parts of A and B are required to calculate convolution in this tile. If the tiles in C are too small, the speed will decrease a lot because of repeated work. In the ultimate case, when each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and there is also a slowdown because of bad cache locality. So, there is an optimal tile size somewhere in the middle. - If different tiles in C can be calculated in parallel and, thus, the convolution is done by parts, the loop can be threaded. All of the above improvements have been implemented in matchTemplate and filter2D . Therefore, by using them, you can get the performance even better than with the above theoretically optimal implementation. Though, those two functions actually calculate cross-correlation, not convolution, so you need to "flip" the second convolution operand B vertically and horizontally using flip . @note - An example using the discrete fourier transform can be found at opencv_source_code/samples/cpp/dft.cpp - (Python) An example using the dft functionality to perform Wiener deconvolution can be found at opencv_source/samples/python/deconvolution.py - (Python) An example rearranging the quadrants of a Fourier image can be found at opencv_source/samples/python/dft.py @param src input array that could be real or complex. @param dst output array whose size and type depends on the flags . @param flags transformation flags, representing a combination of the cv::DftFlags @param nonzeroRows when the parameter is not zero, the function assumes that only the first nonzeroRows rows of the input array (DFT_INVERSE is not set) or only the first nonzeroRows of the output array (DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the rows more efficiently and save some time; this technique is very useful for calculating array cross-correlation or convolution using DFT. @sa dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar , magnitude , phase */ CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); /** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. idft(src, dst, flags) is equivalent to dft(src, dst, flags | DFT_INVERSE) . @note None of dft and idft scales the result by default. So, you should pass DFT_SCALE to one of dft or idft explicitly to make these transforms mutually inverse. @sa dft, dct, idct, mulSpectrums, getOptimalDFTSize @param src input floating-point real or complex array. @param dst output array whose size and type depend on the flags. @param flags operation flags (see dft and cv::DftFlags). @param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see the convolution sample in dft description. */ CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); /** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array. The function dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D floating-point array: - Forward Cosine transform of a 1D vector of N elements: \f[Y = C^{(N)} \cdot X\f] where \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f] and \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*. - Inverse Cosine transform of a 1D vector of N elements: \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f] (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ ) - Forward 2D Cosine transform of M x N matrix: \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f] - Inverse 2D Cosine transform of M x N matrix: \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f] The function chooses the mode of operation by looking at the flags and size of the input array: - If (flags & DCT_INVERSE) == 0 , the function does a forward 1D or 2D transform. Otherwise, it is an inverse 1D or 2D transform. - If (flags & DCT_ROWS) != 0 , the function performs a 1D transform of each row. - If the array is a single column or a single row, the function performs a 1D transform. - If none of the above is true, the function performs a 2D transform. @note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you can pad the array when necessary. Also, the function performance depends very much, and not monotonically, on the array size (see getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as: @code size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } N1 = getOptimalDCTSize(N); @endcode @param src input floating-point array. @param dst output array of the same size and type as src . @param flags transformation flags as a combination of cv::DftFlags (DCT_*) @sa dft , getOptimalDFTSize , idct */ CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0); /** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). @param src input floating-point single-channel array. @param dst output array of the same size and type as src. @param flags operation flags. @sa dct, dft, idft, getOptimalDFTSize */ CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0); /** @brief Performs the per-element multiplication of two Fourier spectrums. The function mulSpectrums performs the per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform. The function, together with dft and idft , may be used to calculate convolution (pass conjB=false ) or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are simply multiplied (per element) with an optional conjugation of the second-array elements. When the arrays are real, they are assumed to be CCS-packed (see dft for details). @param a first input array. @param b second input array of the same size and type as src1 . @param c output array of the same size and type as src1 . @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. @param conjB optional flag that conjugates the second input array before the multiplication (true) or not (false). */ CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c, int flags, bool conjB = false); /** @brief Returns the optimal DFT size for a given vector size. DFT performance is not a monotonic function of a vector size. Therefore, when you calculate convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to pad the input data with zeros to get a bit larger array that can be transformed much faster than the original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2) are also processed quite efficiently. The function getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize so that the DFT of a vector of size N can be processed efficiently. In the current implementation N = 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r. The function returns a negative number if vecsize is too large (very close to INT_MAX ). While the function cannot be used directly to estimate the optimal vector size for DCT transform (since the current DCT implementation supports only even-size vectors), it can be easily processed as getOptimalDFTSize((vecsize+1)/2)\*2. @param vecsize vector size. @sa dft , dct , idft , idct , mulSpectrums */ CV_EXPORTS_W int getOptimalDFTSize(int vecsize); /** @brief Returns the default random number generator. The function theRNG returns the default random number generator. For each thread, there is a separate random number generator, so you can use the function safely in multi-thread environments. If you just need to get a single random number using this generator or initialize an array, you can use randu or randn instead. But if you are going to generate many random numbers inside a loop, it is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() . @sa RNG, randu, randn */ CV_EXPORTS RNG& theRNG(); /** @brief Generates a single uniformly-distributed random number or an array of random numbers. Non-template variant of the function fills the matrix dst with uniformly-distributed random numbers from the specified range: \f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f] @param dst output array of random numbers; the array must be pre-allocated. @param low inclusive lower boundary of the generated random numbers. @param high exclusive upper boundary of the generated random numbers. @sa RNG, randn, theRNG */ CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); /** @brief Fills the array with normally distributed random numbers. The function randn fills the matrix dst with normally distributed random numbers with the specified mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the value range of the output array data type. @param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. @param mean mean value (expectation) of the generated random numbers. @param stddev standard deviation of the generated random numbers; it can be either a vector (in which case a diagonal standard deviation matrix is assumed) or a square matrix. @sa RNG, randu */ CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); /** @brief Shuffles the array elements randomly. The function randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . @param dst input/output numerical 1D array. @param iterFactor scale factor that determines the number of random swap operations (see the details below). @param rng optional random number generator used for shuffling; if it is zero, theRNG () is used instead. @sa RNG, sort */ CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0); /** @brief Principal Component Analysis The class is used to calculate a special basis for a set of vectors. The basis will consist of eigenvectors of the covariance matrix calculated from the input set of vectors. The class %PCA can also transform vectors to/from the new coordinate space defined by the basis. Usually, in this new coordinate system, each vector from the original set (and any linear combination of such vectors) can be quite accurately approximated by taking its first few components, corresponding to the eigenvectors of the largest eigenvalues of the covariance matrix. Geometrically it means that you calculate a projection of the vector to a subspace formed by a few eigenvectors corresponding to the dominant eigenvalues of the covariance matrix. And usually such a projection is very close to the original vector. So, you can represent the original vector from a high-dimensional space with a much shorter vector consisting of the projected vector's coordinates in the subspace. Such a transformation is also known as Karhunen-Loeve Transform, or KLT. See http://en.wikipedia.org/wiki/Principal_component_analysis The sample below is the function that takes two matrices. The first function stores a set of vectors (a row per vector) that is used to calculate PCA. The second function stores another "test" set of vectors (a row per vector). First, these vectors are compressed with PCA, then reconstructed back, and then the reconstruction error norm is computed and printed for each vector. : @code{.cpp} using namespace cv; PCA compressPCA(const Mat& pcaset, int maxComponents, const Mat& testset, Mat& compressed) { PCA pca(pcaset, // pass the data Mat(), // we do not have a pre-computed mean vector, // so let the PCA engine to compute it PCA::DATA_AS_ROW, // indicate that the vectors // are stored as matrix rows // (use PCA::DATA_AS_COL if the vectors are // the matrix columns) maxComponents // specify, how many principal components to retain ); // if there is no test data, just return the computed basis, ready-to-use if( !testset.data ) return pca; CV_Assert( testset.cols == pcaset.cols ); compressed.create(testset.rows, maxComponents, testset.type()); Mat reconstructed; for( int i = 0; i < testset.rows; i++ ) { Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed; // compress the vector, the result will be stored // in the i-th row of the output matrix pca.project(vec, coeffs); // and then reconstruct it pca.backProject(coeffs, reconstructed); // and measure the error printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2)); } return pca; } @endcode @sa calcCovarMatrix, mulTransposed, SVD, dft, dct */ class CV_EXPORTS PCA { public: enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns USE_AVG = 2 //! }; /** @brief default constructor The default constructor initializes an empty %PCA structure. The other constructors initialize the structure and call PCA::operator()(). */ PCA(); /** @overload @param data input samples stored as matrix rows or matrix columns. @param mean optional mean value; if the matrix is empty (@c noArray()), the mean is computed from the data. @param flags operation flags; currently the parameter is only used to specify the data layout (PCA::Flags) @param maxComponents maximum number of components that %PCA should retain; by default, all the components are retained. */ PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0); /** @overload @param data input samples stored as matrix rows or matrix columns. @param mean optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. @param flags operation flags; currently the parameter is only used to specify the data layout (PCA::Flags) @param retainedVariance Percentage of variance that PCA should retain. Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2. */ PCA(InputArray data, InputArray mean, int flags, double retainedVariance); /** @brief performs %PCA The operator performs %PCA of the supplied dataset. It is safe to reuse the same PCA structure for multiple datasets. That is, if the structure has been previously used with another dataset, the existing internal data is reclaimed and the new eigenvalues, @ref eigenvectors , and @ref mean are allocated and computed. The computed eigenvalues are sorted from the largest to the smallest and the corresponding eigenvectors are stored as eigenvectors rows. @param data input samples stored as the matrix rows or as the matrix columns. @param mean optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. @param flags operation flags; currently the parameter is only used to specify the data layout. (Flags) @param maxComponents maximum number of components that PCA should retain; by default, all the components are retained. */ PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0); /** @overload @param data input samples stored as the matrix rows or as the matrix columns. @param mean optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. @param flags operation flags; currently the parameter is only used to specify the data layout. (PCA::Flags) @param retainedVariance Percentage of variance that %PCA should retain. Using this parameter will let the %PCA decided how many components to retain but it will always keep at least 2. */ PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance); /** @brief Projects vector(s) to the principal component subspace. The methods project one or more vectors to the principal component subspace, where each vector projection is represented by coefficients in the principal component basis. The first form of the method returns the matrix that the second form writes to the result. So the first form can be used as a part of expression while the second form can be more efficient in a processing loop. @param vec input vector(s); must have the same dimensionality and the same layout as the input data used at %PCA phase, that is, if DATA_AS_ROW are specified, then `vec.cols==data.cols` (vector dimensionality) and `vec.rows` is the number of vectors to project, and the same is true for the PCA::DATA_AS_COL case. */ Mat project(InputArray vec) const; /** @overload @param vec input vector(s); must have the same dimensionality and the same layout as the input data used at PCA phase, that is, if DATA_AS_ROW are specified, then `vec.cols==data.cols` (vector dimensionality) and `vec.rows` is the number of vectors to project, and the same is true for the PCA::DATA_AS_COL case. @param result output vectors; in case of PCA::DATA_AS_COL, the output matrix has as many columns as the number of input vectors, this means that `result.cols==vec.cols` and the number of rows match the number of principal components (for example, `maxComponents` parameter passed to the constructor). */ void project(InputArray vec, OutputArray result) const; /** @brief Reconstructs vectors from their PC projections. The methods are inverse operations to PCA::project. They take PC coordinates of projected vectors and reconstruct the original vectors. Unless all the principal components have been retained, the reconstructed vectors are different from the originals. But typically, the difference is small if the number of components is large enough (but still much smaller than the original vector dimensionality). As a result, PCA is used. @param vec coordinates of the vectors in the principal component subspace, the layout and size are the same as of PCA::project output vectors. */ Mat backProject(InputArray vec) const; /** @overload @param vec coordinates of the vectors in the principal component subspace, the layout and size are the same as of PCA::project output vectors. @param result reconstructed vectors; the layout and size are the same as of PCA::project input vectors. */ void backProject(InputArray vec, OutputArray result) const; /** @brief write and load PCA matrix */ void write(FileStorage& fs ) const; void read(const FileNode& fs); Mat eigenvectors; //!< eigenvectors of the covariation matrix Mat eigenvalues; //!< eigenvalues of the covariation matrix Mat mean; //!< mean value subtracted before the projection and added after the back projection }; /** @example pca.cpp An example using %PCA for dimensionality reduction while maintaining an amount of variance */ /** @brief Linear Discriminant Analysis @todo document this class */ class CV_EXPORTS LDA { public: /** @brief constructor Initializes a LDA with num_components (default 0). */ explicit LDA(int num_components = 0); /** Initializes and performs a Discriminant Analysis with Fisher's Optimization Criterion on given data in src and corresponding labels in labels. If 0 (or less) number of components are given, they are automatically determined for given data in computation. */ LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0); /** Serializes this object to a given filename. */ void save(const String& filename) const; /** Deserializes this object from a given filename. */ void load(const String& filename); /** Serializes this object to a given cv::FileStorage. */ void save(FileStorage& fs) const; /** Deserializes this object from a given cv::FileStorage. */ void load(const FileStorage& node); /** destructor */ ~LDA(); /** Compute the discriminants for data in src (row aligned) and labels. */ void compute(InputArrayOfArrays src, InputArray labels); /** Projects samples into the LDA subspace. src may be one or more row aligned samples. */ Mat project(InputArray src); /** Reconstructs projections from the LDA subspace. src may be one or more row aligned projections. */ Mat reconstruct(InputArray src); /** Returns the eigenvectors of this LDA. */ Mat eigenvectors() const { return _eigenvectors; } /** Returns the eigenvalues of this LDA. */ Mat eigenvalues() const { return _eigenvalues; } static Mat subspaceProject(InputArray W, InputArray mean, InputArray src); static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src); protected: bool _dataAsRow; // unused, but needed for 3.0 ABI compatibility. int _num_components; Mat _eigenvectors; Mat _eigenvalues; void lda(InputArrayOfArrays src, InputArray labels); }; /** @brief Singular Value Decomposition Class for computing Singular Value Decomposition of a floating-point matrix. The Singular Value Decomposition is used to solve least-square problems, under-determined linear systems, invert matrices, compute condition numbers, and so on. If you want to compute a condition number of a matrix or an absolute value of its determinant, you do not need `u` and `vt`. You can pass flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u and vt must be computed, which is not necessary most of the time. @sa invert, solve, eigen, determinant */ class CV_EXPORTS SVD { public: enum Flags { /** allow the algorithm to modify the decomposed matrix; it can save space and speed up processing. currently ignored. */ MODIFY_A = 1, /** indicates that only a vector of singular values `w` is to be processed, while u and vt will be set to empty matrices */ NO_UV = 2, /** when the matrix is not square, by default the algorithm produces u and vt matrices of sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is specified, u and vt will be full-size square orthogonal matrices.*/ FULL_UV = 4 }; /** @brief the default constructor initializes an empty SVD structure */ SVD(); /** @overload initializes an empty SVD structure and then calls SVD::operator() @param src decomposed matrix. @param flags operation flags (SVD::Flags) */ SVD( InputArray src, int flags = 0 ); /** @brief the operator that performs SVD. The previously allocated u, w and vt are released. The operator performs the singular value decomposition of the supplied matrix. The u,`vt` , and the vector of singular values w are stored in the structure. The same SVD structure can be reused many times with different matrices. Each time, if needed, the previous u,`vt` , and w are reclaimed and the new matrices are created, which is all handled by Mat::create. @param src decomposed matrix. @param flags operation flags (SVD::Flags) */ SVD& operator ()( InputArray src, int flags = 0 ); /** @brief decomposes matrix and stores the results to user-provided matrices The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor and SVD::operator(), they store the results to the user-provided matrices: @code{.cpp} Mat A, w, u, vt; SVD::compute(A, w, u, vt); @endcode @param src decomposed matrix @param w calculated singular values @param u calculated left singular vectors @param vt transposed matrix of right singular values @param flags operation flags - see SVD::SVD. */ static void compute( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 ); /** @overload computes singular values of a matrix @param src decomposed matrix @param w calculated singular values @param flags operation flags - see SVD::Flags. */ static void compute( InputArray src, OutputArray w, int flags = 0 ); /** @brief performs back substitution */ static void backSubst( InputArray w, InputArray u, InputArray vt, InputArray rhs, OutputArray dst ); /** @brief solves an under-determined singular linear system The method finds a unit-length solution x of a singular linear system A\*x = 0. Depending on the rank of A, there can be no solutions, a single solution or an infinite number of solutions. In general, the algorithm solves the following problem: \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f] @param src left-hand-side matrix. @param dst found solution. */ static void solveZ( InputArray src, OutputArray dst ); /** @brief performs a singular value back substitution. The method calculates a back substitution for the specified right-hand side: \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f] Using this technique you can either get a very accurate solution of the convenient linear system, or the best (in the least-squares terms) pseudo-solution of an overdetermined linear system. @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to be solved, where A has been previously decomposed. @param dst found solution of the system. @note Explicit SVD with the further back substitution only makes sense if you need to solve many linear systems with the same left-hand side (for example, src ). If all you need is to solve a single system (possibly with multiple rhs immediately available), simply call solve add pass DECOMP_SVD there. It does absolutely the same thing. */ void backSubst( InputArray rhs, OutputArray dst ) const; /** @todo document */ template static void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); /** @todo document */ template static void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ); /** @todo document */ template static void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); Mat u, w, vt; }; /** @brief Random Number Generator Random number generator. It encapsulates the state (currently, a 64-bit integer) and has methods to return scalar random values and to fill arrays with random values. Currently it supports uniform and Gaussian (normal) distributions. The generator uses Multiply-With-Carry algorithm, introduced by G. Marsaglia ( ). Gaussian-distribution random numbers are generated using the Ziggurat algorithm ( ), introduced by G. Marsaglia and W. W. Tsang. */ class CV_EXPORTS RNG { public: enum { UNIFORM = 0, NORMAL = 1 }; /** @brief constructor These are the RNG constructors. The first form sets the state to some pre-defined value, equal to 2\*\*32-1 in the current implementation. The second form sets the state to the specified value. If you passed state=0 , the constructor uses the above default value instead to avoid the singular random number sequence, consisting of all zeros. */ RNG(); /** @overload @param state 64-bit value used to initialize the RNG. */ RNG(uint64 state); /**The method updates the state using the MWC algorithm and returns the next 32-bit random number.*/ unsigned next(); /**Each of the methods updates the state using the MWC algorithm and returns the next random number of the specified type. In case of integer types, the returned number is from the available value range for the specified type. In case of floating-point types, the returned value is from [0,1) range. */ operator uchar(); /** @overload */ operator schar(); /** @overload */ operator ushort(); /** @overload */ operator short(); /** @overload */ operator unsigned(); /** @overload */ operator int(); /** @overload */ operator float(); /** @overload */ operator double(); /** @brief returns a random integer sampled uniformly from [0, N). The methods transform the state using the MWC algorithm and return the next random number. The first form is equivalent to RNG::next . The second form returns the random number modulo N , which means that the result is in the range [0, N) . */ unsigned operator ()(); /** @overload @param N upper non-inclusive boundary of the returned random number. */ unsigned operator ()(unsigned N); /** @brief returns uniformly distributed integer random number from [a,b) range The methods transform the state using the MWC algorithm and return the next uniformly-distributed random number of the specified type, deduced from the input parameter type, from the range [a, b) . There is a nuance illustrated by the following sample: @code{.cpp} RNG rng; // always produces 0 double a = rng.uniform(0, 1); // produces double from [0, 1) double a1 = rng.uniform((double)0, (double)1); // produces float from [0, 1) double b = rng.uniform(0.f, 1.f); // produces double from [0, 1) double c = rng.uniform(0., 1.); // may cause compiler error because of ambiguity: // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)? double d = rng.uniform(0, 0.999999); @endcode The compiler does not take into account the type of the variable to which you assign the result of RNG::uniform . The only thing that matters to the compiler is the type of a and b parameters. So, if you want a floating-point random number, but the range boundaries are integer numbers, either put dots in the end, if they are constants, or use explicit type cast operators, as in the a1 initialization above. @param a lower inclusive boundary of the returned random numbers. @param b upper non-inclusive boundary of the returned random numbers. */ int uniform(int a, int b); /** @overload */ float uniform(float a, float b); /** @overload */ double uniform(double a, double b); /** @brief Fills arrays with random numbers. @param mat 2D or N-dimensional matrix; currently matrices with more than 4 channels are not supported by the methods, use Mat::reshape as a possible workaround. @param distType distribution type, RNG::UNIFORM or RNG::NORMAL. @param a first distribution parameter; in case of the uniform distribution, this is an inclusive lower boundary, in case of the normal distribution, this is a mean value. @param b second distribution parameter; in case of the uniform distribution, this is a non-inclusive upper boundary, in case of the normal distribution, this is a standard deviation (diagonal of the standard deviation matrix or the full standard deviation matrix). @param saturateRange pre-saturation flag; for uniform distribution only; if true, the method will first convert a and b to the acceptable value range (according to the mat datatype) and then will generate uniformly distributed random numbers within the range [saturate(a), saturate(b)), if saturateRange=false, the method will generate uniformly distributed random numbers in the original range [a, b) and then will saturate them, it means, for example, that theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely produce array mostly filled with 0's and 255's, since the range (0, 255) is significantly smaller than [-DBL_MAX, DBL_MAX). Each of the methods fills the matrix with the random values from the specified distribution. As the new numbers are generated, the RNG state is updated accordingly. In case of multiple-channel images, every channel is filled independently, which means that RNG cannot generate samples from the multi-dimensional Gaussian distribution with non-diagonal covariance matrix directly. To do that, the method generates samples from multi-dimensional standard Gaussian distribution with zero mean and identity covariation matrix, and then transforms them using transform to get samples from the specified Gaussian distribution. */ void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false ); /** @brief Returns the next random number sampled from the Gaussian distribution @param sigma standard deviation of the distribution. The method transforms the state using the MWC algorithm and returns the next random number from the Gaussian distribution N(0,sigma) . That is, the mean value of the returned random numbers is zero and the standard deviation is the specified sigma . */ double gaussian(double sigma); uint64 state; }; /** @brief Mersenne Twister random number generator Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c @todo document */ class CV_EXPORTS RNG_MT19937 { public: RNG_MT19937(); RNG_MT19937(unsigned s); void seed(unsigned s); unsigned next(); operator int(); operator unsigned(); operator float(); operator double(); unsigned operator ()(unsigned N); unsigned operator ()(); /** @brief returns uniformly distributed integer random number from [a,b) range */ int uniform(int a, int b); /** @brief returns uniformly distributed floating-point random number from [a,b) range */ float uniform(float a, float b); /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range */ double uniform(double a, double b); private: enum PeriodParameters {N = 624, M = 397}; unsigned state[N]; int mti; }; //! @} core_array //! @addtogroup core_cluster //! @{ /** @example kmeans.cpp An example on K-means clustering */ /** @brief Finds centers of clusters and groups input samples around the clusters. The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters and groups the input samples around the clusters. As an output, \f$\texttt{labels}_i\f$ contains a 0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix. @note - (Python) An example on K-means clustering can be found at opencv_source_code/samples/python/kmeans.py @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. Examples of this array can be: - Mat points(count, 2, CV_32F); - Mat points(count, 1, CV_32FC2); - Mat points(1, count, CV_32FC2); - std::vector\ points(sampleCount); @param K Number of clusters to split the set by. @param bestLabels Input/output integer array that stores the cluster indices for every sample. @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster centers moves by less than criteria.epsilon on some iteration, the algorithm stops. @param attempts Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness (see the last function parameter). @param flags Flag that can take values of cv::KmeansFlags @param centers Output matrix of the cluster centers, one row per each cluster center. @return The function returns the compactness measure that is computed as \f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] after every attempt. The best (minimum) value is chosen and the corresponding labels and the compactness value are returned by the function. Basically, you can use only the core of the function, set the number of attempts to 1, initialize labels each time using a custom algorithm, pass them with the ( flags = KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering. */ CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray centers = noArray() ); //! @} core_cluster //! @addtogroup core_basic //! @{ /////////////////////////////// Formatted output of cv::Mat /////////////////////////// /** @todo document */ class CV_EXPORTS Formatted { public: virtual const char* next() = 0; virtual void reset() = 0; virtual ~Formatted(); }; /** @todo document */ class CV_EXPORTS Formatter { public: enum { FMT_DEFAULT = 0, FMT_MATLAB = 1, FMT_CSV = 2, FMT_PYTHON = 3, FMT_NUMPY = 4, FMT_C = 5 }; virtual ~Formatter(); virtual Ptr format(const Mat& mtx) const = 0; virtual void set32fPrecision(int p = 8) = 0; virtual void set64fPrecision(int p = 16) = 0; virtual void setMultiline(bool ml = true) = 0; static Ptr get(int fmt = FMT_DEFAULT); }; static inline String& operator << (String& out, Ptr fmtd) { fmtd->reset(); for(const char* str = fmtd->next(); str; str = fmtd->next()) out += cv::String(str); return out; } static inline String& operator << (String& out, const Mat& mtx) { return out << Formatter::get()->format(mtx); } //////////////////////////////////////// Algorithm //////////////////////////////////// class CV_EXPORTS Algorithm; template struct ParamType {}; /** @brief This is a base class for all more or less complex algorithms in OpenCV especially for classes of algorithms, for which there can be multiple implementations. The examples are stereo correspondence (for which there are algorithms like block matching, semi-global block matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck etc.). Here is example of SIFT use in your application via Algorithm interface: @code #include "opencv2/opencv.hpp" #include "opencv2/xfeatures2d.hpp" using namespace cv::xfeatures2d; Ptr sift = SIFT::create(); FileStorage fs("sift_params.xml", FileStorage::READ); if( fs.isOpened() ) // if we have file with parameters, read them { sift->read(fs["sift_params"]); fs.release(); } else // else modify the parameters and store them; user can later edit the file to use different parameters { sift->setContrastThreshold(0.01f); // lower the contrast threshold, compared to the default value { WriteStructContext ws(fs, "sift_params", CV_NODE_MAP); sift->write(fs); } } Mat image = imread("myimage.png", 0), descriptors; vector keypoints; sift->detectAndCompute(image, noArray(), keypoints, descriptors); @endcode */ class CV_EXPORTS_W Algorithm { public: Algorithm(); virtual ~Algorithm(); /** @brief Clears the algorithm state */ CV_WRAP virtual void clear() {} /** @brief Stores algorithm parameters in a file storage */ virtual void write(FileStorage& fs) const { (void)fs; } /** @brief Reads algorithm parameters from a file storage */ virtual void read(const FileNode& fn) { (void)fn; } /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read */ virtual bool empty() const { return false; } /** @brief Reads algorithm from the file node This is static template method of Algorithm. It's usage is following (in the case of SVM): @code Ptr svm = Algorithm::read(fn); @endcode In order to make this method work, the derived class must overwrite Algorithm::read(const FileNode& fn) and also have static create() method without parameters (or with all the optional parameters) */ template static Ptr<_Tp> read(const FileNode& fn) { Ptr<_Tp> obj = _Tp::create(); obj->read(fn); return !obj->empty() ? obj : Ptr<_Tp>(); } /** @brief Loads algorithm from the file @param filename Name of the file to read. @param objname The optional name of the node to read (if empty, the first top-level node will be used) This is static template method of Algorithm. It's usage is following (in the case of SVM): @code Ptr svm = Algorithm::load("my_svm_model.xml"); @endcode In order to make this method work, the derived class must overwrite Algorithm::read(const FileNode& fn). */ template static Ptr<_Tp> load(const String& filename, const String& objname=String()) { FileStorage fs(filename, FileStorage::READ); FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; Ptr<_Tp> obj = _Tp::create(); obj->read(fn); return !obj->empty() ? obj : Ptr<_Tp>(); } /** @brief Loads algorithm from a String @param strModel The string variable containing the model you want to load. @param objname The optional name of the node to read (if empty, the first top-level node will be used) This is static template method of Algorithm. It's usage is following (in the case of SVM): @code Ptr svm = Algorithm::loadFromString(myStringModel); @endcode */ template static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String()) { FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY); FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; Ptr<_Tp> obj = _Tp::create(); obj->read(fn); return !obj->empty() ? obj : Ptr<_Tp>(); } /** Saves the algorithm to a file. In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */ CV_WRAP virtual void save(const String& filename) const; /** Returns the algorithm string identifier. This string is used as top level xml/yml node tag when the object is saved to a file or string. */ CV_WRAP virtual String getDefaultName() const; }; struct Param { enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, UNSIGNED_INT=8, UINT64=9, UCHAR=11 }; }; template<> struct ParamType { typedef bool const_param_type; typedef bool member_type; enum { type = Param::BOOLEAN }; }; template<> struct ParamType { typedef int const_param_type; typedef int member_type; enum { type = Param::INT }; }; template<> struct ParamType { typedef double const_param_type; typedef double member_type; enum { type = Param::REAL }; }; template<> struct ParamType { typedef const String& const_param_type; typedef String member_type; enum { type = Param::STRING }; }; template<> struct ParamType { typedef const Mat& const_param_type; typedef Mat member_type; enum { type = Param::MAT }; }; template<> struct ParamType > { typedef const std::vector& const_param_type; typedef std::vector member_type; enum { type = Param::MAT_VECTOR }; }; template<> struct ParamType { typedef const Ptr& const_param_type; typedef Ptr member_type; enum { type = Param::ALGORITHM }; }; template<> struct ParamType { typedef float const_param_type; typedef float member_type; enum { type = Param::FLOAT }; }; template<> struct ParamType { typedef unsigned const_param_type; typedef unsigned member_type; enum { type = Param::UNSIGNED_INT }; }; template<> struct ParamType { typedef uint64 const_param_type; typedef uint64 member_type; enum { type = Param::UINT64 }; }; template<> struct ParamType { typedef uchar const_param_type; typedef uchar member_type; enum { type = Param::UCHAR }; }; //! @} core_basic } //namespace cv #include "opencv2/core/operations.hpp" #include "opencv2/core/cvstd.inl.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/core/optim.hpp" #endif /*__OPENCV_CORE_HPP__*/ ================================================ FILE: src/3rdparty/opencv/include/opencv2/cvconfig.h ================================================ /* OpenCV compiled as static or dynamic libs */ #define BUILD_SHARED_LIBS /* Compile for 'real' NVIDIA GPU architectures */ #define CUDA_ARCH_BIN "" /* Create PTX or BIN for 1.0 compute capability */ /* #undef CUDA_ARCH_BIN_OR_PTX_10 */ /* NVIDIA GPU features are used */ #define CUDA_ARCH_FEATURES "" /* Compile for 'virtual' NVIDIA PTX architectures */ #define CUDA_ARCH_PTX "" /* AVFoundation video libraries */ /* #undef HAVE_AVFOUNDATION */ /* V4L capturing support */ /* #undef HAVE_CAMV4L */ /* V4L2 capturing support */ /* #undef HAVE_CAMV4L2 */ /* Carbon windowing environment */ /* #undef HAVE_CARBON */ /* AMD's Basic Linear Algebra Subprograms Library*/ /* #undef HAVE_CLAMDBLAS */ /* AMD's OpenCL Fast Fourier Transform Library*/ /* #undef HAVE_CLAMDFFT */ /* Clp support */ /* #undef HAVE_CLP */ /* Cocoa API */ /* #undef HAVE_COCOA */ /* C= */ /* #undef HAVE_CSTRIPES */ /* NVidia Cuda Basic Linear Algebra Subprograms (BLAS) API*/ /* #undef HAVE_CUBLAS */ /* NVidia Cuda Runtime API*/ /* #undef HAVE_CUDA */ /* NVidia Cuda Fast Fourier Transform (FFT) API*/ /* #undef HAVE_CUFFT */ /* IEEE1394 capturing support */ /* #undef HAVE_DC1394 */ /* IEEE1394 capturing support - libdc1394 v2.x */ /* #undef HAVE_DC1394_2 */ /* DirectX */ #define HAVE_DIRECTX /* #undef HAVE_DIRECTX_NV12 */ #define HAVE_D3D11 #define HAVE_D3D10 #define HAVE_D3D9 /* DirectShow Video Capture library */ #define HAVE_DSHOW /* Eigen Matrix & Linear Algebra Library */ /* #undef HAVE_EIGEN */ /* FFMpeg video library */ #define HAVE_FFMPEG /* ffmpeg's libswscale */ #define HAVE_FFMPEG_SWSCALE /* ffmpeg in Gentoo */ #define HAVE_GENTOO_FFMPEG /* Geospatial Data Abstraction Library */ /* #undef HAVE_GDAL */ /* GStreamer multimedia framework */ /* #undef HAVE_GSTREAMER */ /* GTK+ 2.0 Thread support */ /* #undef HAVE_GTHREAD */ /* GTK+ 2.x toolkit */ /* #undef HAVE_GTK */ /* Define to 1 if you have the header file. */ /* #undef HAVE_INTTYPES_H */ /* Intel Perceptual Computing SDK library */ /* #undef HAVE_INTELPERC */ /* Intel Integrated Performance Primitives */ #define HAVE_IPP #define HAVE_IPP_ICV_ONLY /* Intel IPP Async */ /* #undef HAVE_IPP_A */ /* JPEG-2000 codec */ #define HAVE_JASPER /* IJG JPEG codec */ #define HAVE_JPEG /* libpng/png.h needs to be included */ /* #undef HAVE_LIBPNG_PNG_H */ /* V4L/V4L2 capturing support via libv4l */ /* #undef HAVE_LIBV4L */ /* Microsoft Media Foundation Capture library */ /* #undef HAVE_MSMF */ /* NVidia Video Decoding API*/ /* #undef HAVE_NVCUVID */ /* OpenCL Support */ #define HAVE_OPENCL /* #undef HAVE_OPENCL_STATIC */ /* #undef HAVE_OPENCL_SVM */ /* OpenEXR codec */ #define HAVE_OPENEXR /* OpenGL support*/ /* #undef HAVE_OPENGL */ /* OpenNI library */ /* #undef HAVE_OPENNI */ /* OpenNI library */ /* #undef HAVE_OPENNI2 */ /* PNG codec */ #define HAVE_PNG /* Posix threads (pthreads) */ /* #undef HAVE_PTHREADS */ /* parallel_for with pthreads */ /* #undef HAVE_PTHREADS_PF */ /* Qt support */ /* #undef HAVE_QT */ /* Qt OpenGL support */ /* #undef HAVE_QT_OPENGL */ /* QuickTime video libraries */ /* #undef HAVE_QUICKTIME */ /* QTKit video libraries */ /* #undef HAVE_QTKIT */ /* Intel Threading Building Blocks */ /* #undef HAVE_TBB */ /* TIFF codec */ #define HAVE_TIFF /* Unicap video capture library */ /* #undef HAVE_UNICAP */ /* Video for Windows support */ #define HAVE_VFW /* V4L2 capturing support in videoio.h */ /* #undef HAVE_VIDEOIO */ /* Win32 UI */ #define HAVE_WIN32UI /* XIMEA camera support */ /* #undef HAVE_XIMEA */ /* Xine video library */ /* #undef HAVE_XINE */ /* Define if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel and VAX). */ /* #undef WORDS_BIGENDIAN */ /* gPhoto2 library */ /* #undef HAVE_GPHOTO2 */ /* VA library (libva) */ /* #undef HAVE_VA */ /* Intel VA-API/OpenCL */ /* #undef HAVE_VA_INTEL */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/ar_hmdb.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_AR_HMDB_HPP #define OPENCV_DATASETS_AR_HMDB_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_ar //! @{ struct AR_hmdbObj : public Object { int id; std::string name; std::string videoName; }; class CV_EXPORTS AR_hmdb : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/ar_sports.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_AR_SPORTS_HPP #define OPENCV_DATASETS_AR_SPORTS_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_ar //! @{ struct AR_sportsObj : public Object { std::string videoUrl; std::vector labels; }; class CV_EXPORTS AR_sports : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/dataset.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_DATASET_HPP #define OPENCV_DATASETS_DATASET_HPP #include #include #include /** @defgroup datasets Framework for working with different datasets The datasets module includes classes for working with different datasets: load data, evaluate different algorithms on them, contains benchmarks, etc. It is planned to have: - basic: loading code for all datasets to help start work with them. - next stage: quick benchmarks for all datasets to show how to solve them using OpenCV and implement evaluation code. - finally: implement on OpenCV state-of-the-art algorithms, which solve these tasks. @{ @defgroup datasets_ar Action Recognition ### HMDB: A Large Human Motion Database Implements loading dataset: "HMDB: A Large Human Motion Database": Usage: -# From link above download dataset files: `hmdb51_org.rar` & `test_train_splits.rar`. -# Unpack them. Unpack all archives from directory: `hmdb51_org/` and remove them. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_ar_hmdb -p=/home/user/path_to_unpacked_folders/ ~~~ #### Benchmark For this dataset was implemented benchmark with accuracy: 0.107407 (using precomputed HOG/HOF "STIP" features from site, averaging for 3 splits) To run this benchmark execute: ~~~ ./opencv/build/bin/example_datasets_ar_hmdb_benchmark -p=/home/user/path_to_unpacked_folders/ ~~~ @note Precomputed features should be unpacked in the same folder: `/home/user/path_to_unpacked_folders/hmdb51_org_stips/`. Also unpack all archives from directory: `hmdb51_org_stips/` and remove them. ### Sports-1M %Dataset Implements loading dataset: "Sports-1M Dataset": Usage: -# From link above download dataset files (`git clone https://code.google.com/p/sports-1m-dataset/`). -# To load data run: ~~~ ./opencv/build/bin/example_datasets_ar_sports -p=/home/user/path_to_downloaded_folders/ ~~~ @defgroup datasets_fr Face Recognition ### Adience Implements loading dataset: "Adience": Usage: -# From link above download any dataset file: `faces.tar.gz\aligned.tar.gz` and files with splits: `fold_0_data.txt-fold_4_data.txt`, `fold_frontal_0_data.txt-fold_frontal_4_data.txt`. (For face recognition task another splits should be created) -# Unpack dataset file to some folder and place split files into the same folder. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_fr_adience -p=/home/user/path_to_created_folder/ ~~~ ### Labeled Faces in the Wild Implements loading dataset: "Labeled Faces in the Wild": Usage: -# From link above download any dataset file: `lfw.tgz\lfwa.tar.gz\lfw-deepfunneled.tgz\lfw-funneled.tgz` and files with pairs: 10 test splits: `pairs.txt` and developer train split: `pairsDevTrain.txt`. -# Unpack dataset file and place `pairs.txt` and `pairsDevTrain.txt` in created folder. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_fr_lfw -p=/home/user/path_to_unpacked_folder/lfw2/ ~~~ #### Benchmark For this dataset was implemented benchmark with accuracy: 0.623833 +- 0.005223 (train split: `pairsDevTrain.txt`, dataset: lfwa) To run this benchmark execute: ~~~ ./opencv/build/bin/example_datasets_fr_lfw_benchmark -p=/home/user/path_to_unpacked_folder/lfw2/ ~~~ @defgroup datasets_gr Gesture Recognition ### ChaLearn Looking at People Implements loading dataset: "ChaLearn Looking at People": Usage -# Follow instruction from site above, download files for dataset "Track 3: Gesture Recognition": `Train1.zip`-`Train5.zip`, `Validation1.zip`-`Validation3.zip` (Register on site: www.codalab.org and accept the terms and conditions of competition: There are three mirrors for downloading dataset files. When I downloaded data only mirror: "Universitat Oberta de Catalunya" works). -# Unpack train archives `Train1.zip`-`Train5.zip` to folder `Train/`, validation archives `Validation1.zip`-`Validation3.zip` to folder `Validation/` -# Unpack all archives in `Train/` & `Validation/` in the folders with the same names, for example: `Sample0001.zip` to `Sample0001/` -# To load data run: ~~~ ./opencv/build/bin/example_datasets_gr_chalearn -p=/home/user/path_to_unpacked_folders/ ~~~ ### Sheffield Kinect Gesture Dataset Implements loading dataset: "Sheffield Kinect Gesture Dataset": Usage: -# From link above download dataset files: `subject1_dep.7z`-`subject6_dep.7z`, `subject1_rgb.7z`-`subject6_rgb.7z`. -# Unpack them. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_gr_skig -p=/home/user/path_to_unpacked_folders/ ~~~ @defgroup datasets_hpe Human Pose Estimation ### HumanEva Dataset Implements loading dataset: "HumanEva Dataset": Usage: -# From link above download dataset files for `HumanEva-I` (tar) & `HumanEva-II`. -# Unpack them to `HumanEva_1` & `HumanEva_2` accordingly. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_hpe_humaneva -p=/home/user/path_to_unpacked_folders/ ~~~ ### PARSE Dataset Implements loading dataset: "PARSE Dataset": Usage: -# From link above download dataset file: `people.zip`. -# Unpack it. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_hpe_parse -p=/home/user/path_to_unpacked_folder/people_all/ ~~~ @defgroup datasets_ir Image Registration ### Affine Covariant Regions Datasets Implements loading dataset: "Affine Covariant Regions Datasets": Usage: -# From link above download dataset files: `bark\bikes\boat\graf\leuven\trees\ubc\wall.tar.gz`. -# Unpack them. -# To load data, for example, for "bark", run: ``` ./opencv/build/bin/example_datasets_ir_affine -p=/home/user/path_to_unpacked_folder/bark/ ``` ### Robot Data Set Implements loading dataset: "Robot Data Set, Point Feature Data Set – 2010": Usage: -# From link above download dataset files: `SET001_6.tar.gz`-`SET055_60.tar.gz` -# Unpack them to one folder. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_ir_robot -p=/home/user/path_to_unpacked_folder/ ~~~ @defgroup datasets_is Image Segmentation ### The Berkeley Segmentation Dataset and Benchmark Implements loading dataset: "The Berkeley Segmentation Dataset and Benchmark": Usage: -# From link above download dataset files: `BSDS300-human.tgz` & `BSDS300-images.tgz`. -# Unpack them. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_is_bsds -p=/home/user/path_to_unpacked_folder/BSDS300/ ~~~ ### Weizmann Segmentation Evaluation Database Implements loading dataset: "Weizmann Segmentation Evaluation Database": Usage: -# From link above download dataset files: `Weizmann_Seg_DB_1obj.ZIP` & `Weizmann_Seg_DB_2obj.ZIP`. -# Unpack them. -# To load data, for example, for `1 object` dataset, run: ~~~ ./opencv/build/bin/example_datasets_is_weizmann -p=/home/user/path_to_unpacked_folder/1obj/ ~~~ @defgroup datasets_msm Multiview Stereo Matching ### EPFL Multi-View Stereo Implements loading dataset: "EPFL Multi-View Stereo": Usage: -# From link above download dataset files: `castle_dense\castle_dense_large\castle_entry\fountain\herzjesu_dense\herzjesu_dense_large_bounding\cameras\images\p.tar.gz`. -# Unpack them in separate folder for each object. For example, for "fountain", in folder `fountain/` : `fountain_dense_bounding.tar.gz -> bounding/`, `fountain_dense_cameras.tar.gz -> camera/`, `fountain_dense_images.tar.gz -> png/`, `fountain_dense_p.tar.gz -> P/` -# To load data, for example, for "fountain", run: ~~~ ./opencv/build/bin/example_datasets_msm_epfl -p=/home/user/path_to_unpacked_folder/fountain/ ~~~ ### Stereo – Middlebury Computer Vision Implements loading dataset: "Stereo – Middlebury Computer Vision": Usage: -# From link above download dataset files: `dino\dinoRing\dinoSparseRing\temple\templeRing\templeSparseRing.zip` -# Unpack them. -# To load data, for example "temple" dataset, run: ~~~ ./opencv/build/bin/example_datasets_msm_middlebury -p=/home/user/path_to_unpacked_folder/temple/ ~~~ @defgroup datasets_or Object Recognition ### ImageNet Implements loading dataset: "ImageNet": Usage: -# From link above download dataset files: `ILSVRC2010_images_train.tar\ILSVRC2010_images_test.tar\ILSVRC2010_images_val.tar` & devkit: `ILSVRC2010_devkit-1.0.tar.gz` (Implemented loading of 2010 dataset as only this dataset has ground truth for test data, but structure for ILSVRC2014 is similar) -# Unpack them to: `some_folder/train/`, `some_folder/test/`, `some_folder/val` & `some_folder/ILSVRC2010_validation_ground_truth.txt`, `some_folder/ILSVRC2010_test_ground_truth.txt`. -# Create file with labels: `some_folder/labels.txt`, for example, using python script below (each file's row format: `synset,labelID,description`. For example: "n07751451,18,plum"). -# Unpack all tar files in train. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_or_imagenet -p=/home/user/some_folder/ ~~~ Python script to parse `meta.mat`: ~~~{py} import scipy.io meta_mat = scipy.io.loadmat("devkit-1.0/data/meta.mat") labels_dic = dict((m[0][1][0], m[0][0][0][0]-1) for m in meta_mat['synsets'] label_names_dic = dict((m[0][1][0], m[0][2][0]) for m in meta_mat['synsets'] for label in labels_dic.keys(): print "{0},{1},{2}".format(label, labels_dic[label], label_names_dic[label]) ~~~ ### MNIST Implements loading dataset: "MNIST": Usage: -# From link above download dataset files: `t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`, `train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`. -# Unpack them. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_or_mnist -p=/home/user/path_to_unpacked_files/ ~~~ ### SUN Database Implements loading dataset: "SUN Database, Scene Recognition Benchmark. SUN397": Usage: -# From link above download dataset file: `SUN397.tar` & file with splits: `Partitions.zip` -# Unpack `SUN397.tar` into folder: `SUN397/` & `Partitions.zip` into folder: `SUN397/Partitions/` -# To load data run: ~~~ ./opencv/build/bin/example_datasets_or_sun -p=/home/user/path_to_unpacked_files/SUN397/ ~~~ @defgroup datasets_pd Pedestrian Detection ### Caltech Pedestrian Detection Benchmark Implements loading dataset: "Caltech Pedestrian Detection Benchmark": @note First version of Caltech Pedestrian dataset loading. Code to unpack all frames from seq files commented as their number is huge! So currently load only meta information without data. Also ground truth isn't processed, as need to convert it from mat files first. Usage: -# From link above download dataset files: `set00.tar`-`set10.tar`. -# Unpack them to separate folder. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_pd_caltech -p=/home/user/path_to_unpacked_folders/ ~~~ @defgroup datasets_slam SLAM ### KITTI Vision Benchmark Implements loading dataset: "KITTI Vision Benchmark": Usage: -# From link above download "Odometry" dataset files: `data_odometry_gray\data_odometry_color\data_odometry_velodyne\data_odometry_poses\data_odometry_calib.zip`. -# Unpack `data_odometry_poses.zip`, it creates folder `dataset/poses/`. After that unpack `data_odometry_gray.zip`, `data_odometry_color.zip`, `data_odometry_velodyne.zip`. Folder `dataset/sequences/` will be created with folders `00/..21/`. Each of these folders will contain: `image_0/`, `image_1/`, `image_2/`, `image_3/`, `velodyne/` and files `calib.txt` & `times.txt`. These two last files will be replaced after unpacking `data_odometry_calib.zip` at the end. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_slam_kitti -p=/home/user/path_to_unpacked_folder/dataset/ ~~~ ### TUMindoor Dataset Implements loading dataset: "TUMindoor Dataset": Usage: -# From link above download dataset files: `dslr\info\ladybug\pointcloud.tar.bz2` for each dataset: `11-11-28 (1st floor)\11-12-13 (1st floor N1)\11-12-17a (4th floor)\11-12-17b (3rd floor)\11-12-17c (Ground I)\11-12-18a (Ground II)\11-12-18b (2nd floor)` -# Unpack them in separate folder for each dataset. `dslr.tar.bz2 -> dslr/`, `info.tar.bz2 -> info/`, `ladybug.tar.bz2 -> ladybug/`, `pointcloud.tar.bz2 -> pointcloud/`. -# To load each dataset run: ~~~ ./opencv/build/bin/example_datasets_slam_tumindoor -p=/home/user/path_to_unpacked_folders/ ~~~ @defgroup datasets_tr Text Recognition ### The Chars74K Dataset Implements loading dataset: "The Chars74K Dataset": Usage: -# From link above download dataset files: `EnglishFnt\EnglishHnd\EnglishImg\KannadaHnd\KannadaImg.tgz`, `ListsTXT.tgz`. -# Unpack them. -# Move `.m` files from folder `ListsTXT/` to appropriate folder. For example, `English/list_English_Img.m` for `EnglishImg.tgz`. -# To load data, for example "EnglishImg", run: ~~~ ./opencv/build/bin/example_datasets_tr_chars -p=/home/user/path_to_unpacked_folder/English/ ~~~ ### The Street View Text Dataset Implements loading dataset: "The Street View Text Dataset": Usage: -# From link above download dataset file: `svt.zip`. -# Unpack it. -# To load data run: ~~~ ./opencv/build/bin/example_datasets_tr_svt -p=/home/user/path_to_unpacked_folder/svt/svt1/ ~~~ #### Benchmark For this dataset was implemented benchmark with accuracy (mean f1): 0.217 To run benchmark execute: ~~~ ./opencv/build/bin/example_datasets_tr_svt_benchmark -p=/home/user/path_to_unpacked_folders/svt/svt1/ ~~~ @defgroup datasets_track Tracking ### VOT 2015 Database Implements loading dataset: "VOT 2015 dataset comprises 60 short sequences showing various objects in challenging backgrounds. The sequences were chosen from a large pool of sequences including the ALOV dataset, OTB2 dataset, non-tracking datasets, Computer Vision Online, Professor Bob Fisher’s Image Database, Videezy, Center for Research in Computer Vision, University of Central Florida, USA, NYU Center for Genomics and Systems Biology, Data Wrangling, Open Access Directory and Learning and Recognition in Vision Group, INRIA, France. The VOT sequence selection protocol was applied to obtain a representative set of challenging sequences.": Usage: -# From link above download dataset file: `vot2015.zip` -# Unpack `vot2015.zip` into folder: `VOT2015/` -# To load data run: ~~~ ./opencv/build/bin/example_datasets_track_vot -p=/home/user/path_to_unpacked_files/VOT2015/ ~~~ @} */ namespace cv { namespace datasets { //! @addtogroup datasets //! @{ struct Object { }; class CV_EXPORTS Dataset { public: Dataset() {} virtual ~Dataset() {} virtual void load(const std::string &path) = 0; std::vector< Ptr >& getTrain(int splitNum = 0); std::vector< Ptr >& getTest(int splitNum = 0); std::vector< Ptr >& getValidation(int splitNum = 0); int getNumSplits() const; protected: std::vector< std::vector< Ptr > > train; std::vector< std::vector< Ptr > > test; std::vector< std::vector< Ptr > > validation; private: std::vector< Ptr > empty; }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/fr_adience.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_FR_ADIENCE_HPP #define OPENCV_DATASETS_FR_ADIENCE_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_fr //! @{ enum genderType { male = 0, female, none }; struct FR_adienceObj : public Object { std::string user_id; std::string original_image; int face_id; std::string age; genderType gender; int x; int y; int dx; int dy; int tilt_ang; int fiducial_yaw_angle; int fiducial_score; }; class CV_EXPORTS FR_adience : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); std::vector paths; }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/fr_lfw.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_FR_LFW_HPP #define OPENCV_DATASETS_FR_LFW_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_fr //! @{ struct FR_lfwObj : public Object { std::string image1, image2; bool same; }; class CV_EXPORTS FR_lfw : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/gr_chalearn.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_GR_CHALEARN_HPP #define OPENCV_DATASETS_GR_CHALEARN_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_gr //! @{ struct groundTruth { int gestureID, initialFrame, lastFrame; }; struct join { double Wx, Wy, Wz, Rx, Ry, Rz, Rw, Px, Py; }; struct skeleton { join s[20]; }; struct GR_chalearnObj : public Object { std::string name, nameColor, nameDepth, nameUser; int numFrames, fps, depth; std::vector groundTruths; std::vector skeletons; }; class CV_EXPORTS GR_chalearn : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/gr_skig.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_GR_SKIG_HPP #define OPENCV_DATASETS_GR_SKIG_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_gr //! @{ enum actionType { circle = 1, triangle, updown, rightleft, wave, z, cross, comehere, turnaround, pat }; enum poseType { fist = 1, index, flat }; enum illuminationType { light = 1, dark }; enum backgroundType { woodenBoard = 1, whitePaper, paperWithCharacters }; struct GR_skigObj : public Object { std::string rgb; std::string dep; char person; // 1..6 backgroundType background; illuminationType illumination; poseType pose; actionType type; }; class CV_EXPORTS GR_skig : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/hpe_humaneva.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_HPE_HUMANEVA_HPP #define OPENCV_DATASETS_HPE_HUMANEVA_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_hpe //! @{ struct HPE_humanevaObj : public Object { char person; // 1..4 std::string action; int type1; std::string type2; Matx13d ofs; std::string fileName; std::vector imageNames; // for HumanEva_II }; enum datasetType { humaneva_1 = 1, humaneva_2 }; class CV_EXPORTS HPE_humaneva : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(int num=humaneva_1); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/hpe_parse.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_HPE_PARSE_HPP #define OPENCV_DATASETS_HPE_PARSE_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_hpe //! @{ struct HPE_parseObj : public Object { std::string name; }; class CV_EXPORTS HPE_parse : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/ir_affine.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_IR_AFFINE_HPP #define OPENCV_DATASETS_IR_AFFINE_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include #include namespace cv { namespace datasets { //! @addtogroup datasets_ir //! @{ struct IR_affineObj : public Object { std::string imageName; Matx33d mat; }; class CV_EXPORTS IR_affine : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/ir_robot.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_IR_ROBOT_HPP #define OPENCV_DATASETS_IR_ROBOT_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_ir //! @{ // calibration matrix from calibrationFile.mat // 2.8290e+03 0.0000e+00 8.0279e+02 // 0.0000e+00 2.8285e+03 6.1618e+02 // 0.0000e+00 0.0000e+00 1.0000e+00 struct cameraPos { std::vector images; }; struct IR_robotObj : public Object { std::string name; std::vector pos; }; class CV_EXPORTS IR_robot : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/is_bsds.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_IS_BSDS_HPP #define OPENCV_DATASETS_IS_BSDS_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_is //! @{ struct IS_bsdsObj : public Object { std::string name; }; class CV_EXPORTS IS_bsds : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/is_weizmann.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_IS_WEIZMANN_HPP #define OPENCV_DATASETS_IS_WEIZMANN_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_is //! @{ struct IS_weizmannObj : public Object { std::string imageName; std::string srcBw; std::string srcColor; std::string humanSeg; // TODO: read human segmented }; class CV_EXPORTS IS_weizmann : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/msm_epfl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_MSM_EPFL_HPP #define OPENCV_DATASETS_MSM_EPFL_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_msm //! @{ struct cameraParam { Matx33d mat1; double mat2[3]; Matx33d mat3; double mat4[3]; int imageWidth, imageHeight; }; struct MSM_epflObj : public Object { std::string imageName; Matx23d bounding; Matx34d p; cameraParam camera; }; class CV_EXPORTS MSM_epfl : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/msm_middlebury.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_MSM_MIDDLEBURY_HPP #define OPENCV_DATASETS_MSM_MIDDLEBURY_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_msm //! @{ struct MSM_middleburyObj : public Object { std::string imageName; Matx33d k; Matx33d r; double t[3]; }; class CV_EXPORTS MSM_middlebury : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/or_imagenet.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_OR_IMAGENET_HPP #define OPENCV_DATASETS_OR_IMAGENET_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_or //! @{ struct OR_imagenetObj : public Object { int id; std::string image; }; class CV_EXPORTS OR_imagenet : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/or_mnist.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_OR_MNIST_HPP #define OPENCV_DATASETS_OR_MNIST_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_or //! @{ struct OR_mnistObj : public Object { char label; // 0..9 Mat image; // [28][28] }; class CV_EXPORTS OR_mnist : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/or_pascal.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_VOC_PASCAL_HPP #define OPENCV_DATASETS_VOC_PASCAL_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_or //! @{ struct PascalPart: public Object { std::string name; int xmin; int ymin; int xmax; int ymax; }; struct PascalObj: public PascalPart { std::string pose; bool truncated; bool difficult; bool occluded; std::vector parts; }; struct OR_pascalObj : public Object { std::string filename; int width; int height; int depth; std::vector objects; }; class CV_EXPORTS OR_pascal : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} }// namespace dataset }// namespace cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/or_sun.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_OR_SUN_HPP #define OPENCV_DATASETS_OR_SUN_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_or //! @{ struct OR_sunObj : public Object { int label; std::string name; }; class CV_EXPORTS OR_sun : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); std::vector paths; }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/pd_caltech.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_PD_CALTECH_HPP #define OPENCV_DATASETS_PD_CALTECH_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_pd //! @{ struct PD_caltechObj : public Object { //double groundTrue[][]; //Mat image; std::string name; std::vector< std::string > imageNames; }; // // first version of Caltech Pedestrian dataset loading // code to unpack all frames from seq files commented as their number is huge // so currently load only meta information without data // // also ground truth isn't processed, as need to convert it from mat files first // class CV_EXPORTS PD_caltech : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/pd_inria.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_PD_INRIA_HPP #define OPENCV_DATASETS_PD_INRIA_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_pd //! @{ enum sampleType { POS = 0, NEG = 1 }; struct PD_inriaObj : public Object { // image file name std::string filename; // positive or negative sampleType sType; // image size int width; int height; int depth; // bounding boxes std::vector< Rect > bndboxes; }; class CV_EXPORTS PD_inria : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/slam_kitti.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_SLAM_KITTI_HPP #define OPENCV_DATASETS_SLAM_KITTI_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_slam //! @{ struct pose { double elem[12]; }; struct SLAM_kittiObj : public Object { std::string name; std::vector images[4]; std::vector velodyne; std::vector times, p[4]; std::vector posesArray; }; class CV_EXPORTS SLAM_kitti : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/slam_tumindoor.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_SLAM_TUMINDOOR_HPP #define OPENCV_DATASETS_SLAM_TUMINDOOR_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_slam //! @{ enum imageType { LEFT = 0, RIGHT, LADYBUG }; struct SLAM_tumindoorObj : public Object { std::string name; Matx44d transformMat; imageType type; }; class CV_EXPORTS SLAM_tumindoor : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/tr_chars.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_TR_CHARS_HPP #define OPENCV_DATASETS_TR_CHARS_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_tr //! @{ struct TR_charsObj : public Object { std::string imgName; int label; }; class CV_EXPORTS TR_chars : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/tr_icdar.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_TR_ICDAR_HPP #define OPENCV_DATASETS_TR_ICDAR_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_tr //! @{ struct word { std::string value; int height, width, x, y; }; struct TR_icdarObj : public Object { std::string fileName; std::vector lex100; std::vector lexFull; std::vector words; }; class CV_EXPORTS TR_icdar : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/tr_svt.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_TR_SVT_HPP #define OPENCV_DATASETS_TR_SVT_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include namespace cv { namespace datasets { //! @addtogroup datasets_tr //! @{ struct tag { std::string value; int height, width, x, y; }; struct TR_svtObj : public Object { std::string fileName; std::vector lex; std::vector tags; }; class CV_EXPORTS TR_svt : public Dataset { public: virtual void load(const std::string &path) = 0; static Ptr create(); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/track_vot.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_TRACK_VOT_HPP #define OPENCV_DATASETS_TRACK_VOT_HPP #include #include #include "opencv2/datasets/dataset.hpp" #include "opencv2/datasets/util.hpp" using namespace std; namespace cv { namespace datasets { //! @addtogroup datasets_track //! @{ struct TRACK_votObj : public Object { int id; std::string imagePath; vector gtbb; }; class CV_EXPORTS TRACK_vot : public Dataset { public: static Ptr create(); virtual void load(const std::string &path) = 0; virtual int getDatasetsNum() = 0; virtual int getDatasetLength(int id) = 0; virtual bool initDataset(int id) = 0; virtual bool getNextFrame(Mat &frame) = 0; virtual vector getGT() = 0; protected: vector > > data; int activeDatasetID; int frameCounter; }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/datasets/util.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_DATASETS_UTIL_HPP #define OPENCV_DATASETS_UTIL_HPP #include #include #include #include // atoi, atof #include #include namespace cv { namespace datasets { //! @addtogroup datasets //! @{ void CV_EXPORTS split(const std::string &s, std::vector &elems, char delim); void CV_EXPORTS createDirectory(const std::string &path); void CV_EXPORTS getDirList(const std::string &dirName, std::vector &fileNames); //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/dnn/blob.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DNN_DNN_BLOB_HPP__ #define __OPENCV_DNN_DNN_BLOB_HPP__ #include #include #include namespace cv { namespace dnn { //! @addtogroup dnn //! @{ /** @brief Lightweight class for storing and processing a shape of blob (or anything else). */ struct BlobShape { explicit BlobShape(int ndims = 4, int fill = 1); //!< Creates n-dim shape and fill its by @p fill BlobShape(int num, int cn, int rows, int cols); //!< Creates 4-dim shape [@p num, @p cn, @p rows, @p cols] BlobShape(int ndims, const int *sizes); //!< Creates n-dim shape from the @p sizes array BlobShape(const std::vector &sizes); //!< Creates n-dim shape from the @p sizes vector template BlobShape(const Vec &shape); //!< Creates n-dim shape from @ref cv::Vec /** @brief Returns number of dimensions. */ int dims() const; /** @brief Returns reference to the size of the specified @p axis. * * Negative @p axis is supported, in this case a counting starts from the last axis, * i. e. -1 corresponds to last axis. * If non-existing axis was passed then an error will be generated. */ int &size(int axis); /** @brief Returns the size of the specified @p axis. * @see size() */ int size(int axis) const; int operator[](int axis) const; //!< Does the same thing as size(axis). int &operator[](int axis); //!< Does the same thing as size(int) const. /** @brief Returns the size of the specified @p axis. * * Does the same thing as size(int) const, but if non-existing axis will be passed then 1 will be returned, * therefore this function always finishes successfully. */ int xsize(int axis) const; /** @brief Returns the product of all sizes of axes. */ ptrdiff_t total(); /** @brief Returns pointer to the first element of continuous size array. */ const int *ptr() const; /** @brief Checks equality of two shapes. */ bool equal(const BlobShape &other) const; bool operator== (const BlobShape &r) const; private: cv::AutoBuffer sz; }; /** @brief This class provides methods for continuous n-dimensional CPU and GPU array processing. * * The class is realized as a wrapper over @ref cv::Mat and @ref cv::UMat. * It will support methods for switching and logical synchronization between CPU and GPU. */ class CV_EXPORTS Blob { public: explicit Blob(); /** @brief Constructs blob with specified @p shape and @p type. */ explicit Blob(const BlobShape &shape, int type = CV_32F); /** @brief Constucts 4-dimensional blob (so-called batch) from image or array of images. * @param image 2-dimensional multi-channel or 3-dimensional single-channel image (or array of images) * @param dstCn specify size of second axis of ouptut blob */ explicit Blob(InputArray image, int dstCn = -1); /** @brief Creates blob with specified @p shape and @p type. */ void create(const BlobShape &shape, int type = CV_32F); /** @brief Creates blob from cv::Mat or cv::UMat without copying the data */ void fill(InputArray in); /** @brief Creates blob from user data. * @details If @p deepCopy is false then CPU data will not be allocated. */ void fill(const BlobShape &shape, int type, void *data, bool deepCopy = true); Mat& matRef(); //!< Returns reference to cv::Mat, containing blob data. const Mat& matRefConst() const; //!< Returns reference to cv::Mat, containing blob data, for read-only purposes. UMat &umatRef(); //!< Returns reference to cv::UMat, containing blob data (not implemented yet). const UMat &umatRefConst() const; //!< Returns reference to cv::UMat, containing blob data, for read-only purposes (not implemented yet). /** @brief Returns number of blob dimensions. */ int dims() const; /** @brief Returns the size of the specified @p axis. * * Negative @p axis is supported, in this case a counting starts from the last axis, * i. e. -1 corresponds to last axis. * If non-existing axis was passed then an error will be generated. */ int size(int axis) const; /** @brief Returns the size of the specified @p axis. * * Does the same thing as size(int) const, but if non-existing axis will be passed then 1 will be returned, * therefore this function always finishes successfully. */ int xsize(int axis) const; /** @brief Computes the product of sizes of axes among the specified axes range [@p startAxis; @p endAxis). * @param startAxis the first axis to include in the range. * @param endAxis the first axis to exclude from the range. * @details Negative axis indexing can be used. */ size_t total(int startAxis = 0, int endAxis = INT_MAX) const; /** @brief Converts @p axis index to canonical format (where 0 <= axis < dims()). */ int canonicalAxis(int axis) const; /** @brief Returns shape of the blob. */ BlobShape shape() const; /** @brief Checks equality of two blobs shapes. */ bool equalShape(const Blob &other) const; /** @brief Returns slice of first two dimensions. * @details The behaviour is similar to the following numpy code: blob[n, cn, ...] */ Mat getPlane(int n, int cn); /* Shape getters of 4-dimensional blobs. */ int cols() const; //!< Returns size of the fourth axis blob. int rows() const; //!< Returns size of the thrid axis blob. int channels() const; //!< Returns size of the second axis blob. int num() const; //!< Returns size of the first axis blob. Size size2() const; //!< Returns cv::Size(cols(), rows()) Vec4i shape4() const; //!< Returns shape of first four blob axes. /** @brief Returns linear index of the element with specified coordinates in the blob. * * If @p n < dims() then unspecified coordinates will be filled by zeros. * If @p n > dims() then extra coordinates will be ignored. */ template size_t offset(const Vec &pos) const; /** @overload */ size_t offset(int n = 0, int cn = 0, int row = 0, int col = 0) const; /* CPU pointer getters */ /** @brief Returns pointer to the blob element with the specified position, stored in CPU memory. * * @p n correspond to the first axis, @p cn - to the second, etc. * If dims() > 4 then unspecified coordinates will be filled by zeros. * If dims() < 4 then extra coordinates will be ignored. */ uchar *ptr(int n = 0, int cn = 0, int row = 0, int col = 0); /** @overload */ template TFloat *ptr(int n = 0, int cn = 0, int row = 0, int col = 0); /** @overload ptr() */ float *ptrf(int n = 0, int cn = 0, int row = 0, int col = 0); //TODO: add const ptr methods /** @brief Shares data from other @p blob. * @returns *this */ Blob &shareFrom(const Blob &blob); /** @brief Changes shape of the blob without copying the data. * @returns *this */ Blob &reshape(const BlobShape &shape); /** @brief Returns type of the blob. */ int type() const; private: const int *sizes() const; Mat m; }; //! @} } } #include "blob.inl.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/dnn/blob.inl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DNN_DNN_BLOB_INL_HPP__ #define __OPENCV_DNN_DNN_BLOB_INL_HPP__ #include "blob.hpp" namespace cv { namespace dnn { inline BlobShape::BlobShape(int ndims, int fill) : sz( (size_t)std::max(ndims, 0) ) { CV_Assert(ndims >= 0); for (int i = 0; i < ndims; i++) sz[i] = fill; } inline BlobShape::BlobShape(int ndims, const int *sizes) : sz( (size_t)std::max(ndims, 0) ) { CV_Assert(ndims >= 0); for (int i = 0; i < ndims; i++) sz[i] = sizes[i]; } inline BlobShape::BlobShape(int num, int cn, int rows, int cols) : sz(4) { sz[0] = num; sz[1] = cn; sz[2] = rows; sz[3] = cols; } inline BlobShape::BlobShape(const std::vector &sizes) : sz( sizes.size() ) { for (int i = 0; i < (int)sizes.size(); i++) sz[i] = sizes[i]; } template inline BlobShape::BlobShape(const Vec &shape) : sz(n) { for (int i = 0; i < n; i++) sz[i] = shape[i]; } inline int BlobShape::dims() const { return (int)sz.size(); } inline int BlobShape::xsize(int axis) const { if (axis < -dims() || axis >= dims()) return 1; return sz[(axis < 0) ? axis + dims() : axis]; } inline int BlobShape::size(int axis) const { CV_Assert(-dims() <= axis && axis < dims()); return sz[(axis < 0) ? axis + dims() : axis]; } inline int &BlobShape::size(int axis) { CV_Assert(-dims() <= axis && axis < dims()); return sz[(axis < 0) ? axis + dims() : axis]; } inline int BlobShape::operator[] (int axis) const { CV_Assert(-dims() <= axis && axis < dims()); return sz[(axis < 0) ? axis + dims() : axis]; } inline int &BlobShape::operator[] (int axis) { CV_Assert(-dims() <= axis && axis < dims()); return sz[(axis < 0) ? axis + dims() : axis]; } inline ptrdiff_t BlobShape::total() { if (dims() == 0) return 0; ptrdiff_t res = 1; for (int i = 0; i < dims(); i++) res *= sz[i]; return res; } inline const int *BlobShape::ptr() const { return sz; } inline bool BlobShape::equal(const BlobShape &other) const { if (this->dims() != other.dims()) return false; for (int i = 0; i < other.dims(); i++) { if (sz[i] != other.sz[i]) return false; } return true; } inline bool BlobShape::operator==(const BlobShape &r) const { return this->equal(r); } CV_EXPORTS std::ostream &operator<< (std::ostream &stream, const BlobShape &shape); ///////////////////////////////////////////////////////////////////// inline int Blob::canonicalAxis(int axis) const { CV_Assert(-dims() <= axis && axis < dims()); return (axis < 0) ? axis + dims() : axis; } inline int Blob::dims() const { return m.dims; } inline int Blob::xsize(int axis) const { if (axis < -dims() || axis >= dims()) return 1; return sizes()[(axis < 0) ? axis + dims() : axis]; } inline int Blob::size(int axis) const { CV_Assert(-dims() <= axis && axis < dims()); return sizes()[(axis < 0) ? axis + dims() : axis]; } inline size_t Blob::total(int startAxis, int endAxis) const { if (startAxis < 0) startAxis += dims(); if (endAxis == INT_MAX) endAxis = dims(); else if (endAxis < 0) endAxis += dims(); CV_Assert(0 <= startAxis && startAxis <= endAxis && endAxis <= dims()); size_t size = 1; //fix: assume that slice isn't empty for (int i = startAxis; i < endAxis; i++) size *= (size_t)sizes()[i]; return size; } template inline size_t Blob::offset(const Vec &pos) const { size_t ofs = 0; int i; for (i = 0; i < std::min(n, dims()); i++) { CV_DbgAssert(pos[i] >= 0 && pos[i] < size(i)); ofs = ofs * (size_t)size(i) + pos[i]; } for (; i < dims(); i++) ofs *= (size_t)size(i); return ofs; } inline size_t Blob::offset(int n, int cn, int row, int col) const { return offset(Vec4i(n, cn, row, col)); } inline float *Blob::ptrf(int n, int cn, int row, int col) { CV_Assert(type() == CV_32F); return (float*)m.data + offset(n, cn, row, col); } inline uchar *Blob::ptr(int n, int cn, int row, int col) { return m.data + m.elemSize() * offset(n, cn, row, col); } template inline TFloat* Blob::ptr(int n, int cn, int row, int col) { CV_Assert(type() == cv::DataDepth::value); return (TFloat*) ptr(n, cn, row, col); } inline BlobShape Blob::shape() const { return BlobShape(dims(), sizes()); } inline bool Blob::equalShape(const Blob &other) const { if (this->dims() != other.dims()) return false; for (int i = 0; i < dims(); i++) { if (this->sizes()[i] != other.sizes()[i]) return false; } return true; } inline Mat& Blob::matRef() { return m; } inline const Mat& Blob::matRefConst() const { return m; } inline UMat &Blob::umatRef() { CV_Error(Error::StsNotImplemented, ""); return *(new UMat()); } inline const UMat &Blob::umatRefConst() const { CV_Error(Error::StsNotImplemented, ""); return *(new UMat()); } inline Mat Blob::getPlane(int n, int cn) { CV_Assert(dims() > 2); return Mat(dims() - 2, sizes() + 2, type(), ptr(n, cn)); } inline int Blob::cols() const { return xsize(3); } inline int Blob::rows() const { return xsize(2); } inline int Blob::channels() const { return xsize(1); } inline int Blob::num() const { return xsize(0); } inline Size Blob::size2() const { return Size(cols(), rows()); } inline int Blob::type() const { return m.depth(); } inline const int * Blob::sizes() const { return &m.size[0]; } inline Blob &Blob::shareFrom(const Blob &blob) { this->m = blob.m; return *this; } inline Blob &Blob::reshape(const BlobShape &shape) { m = m.reshape(1, shape.dims(), shape.ptr()); return *this; } } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/dnn/dict.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DNN_DNN_DICT_HPP__ #define __OPENCV_DNN_DNN_DICT_HPP__ #include #include #include namespace cv { namespace dnn { //! @addtogroup dnn //! @{ /** @brief This struct stores the scalar value (or array) of one of the following type: double, cv::String or int64. * @todo Maybe int64 is useless because double type exactly stores at least 2^52 integers. */ struct DictValue { DictValue(const DictValue &r); DictValue(int p = 0) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = p; } //!< Constructs integer scalar DictValue(unsigned p) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = p; } //!< Constructs integer scalar DictValue(double p) : type(Param::REAL), pd(new AutoBuffer) { (*pd)[0] = p; } //!< Constructs floating point scalar DictValue(const String &p) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = p; } //!< Constructs string scalar template static DictValue arrayInt(TypeIter begin, int size); //!< Constructs integer array template static DictValue arrayReal(TypeIter begin, int size); //!< Constructs floating point array template static DictValue arrayString(TypeIter begin, int size); //!< Constructs array of strings template T get(int idx = -1) const; //!< Tries to convert array element with specified index to requested type and returns its. int size() const; bool isInt() const; bool isString() const; bool isReal() const; DictValue &operator=(const DictValue &r); friend std::ostream &operator<<(std::ostream &stream, const DictValue &dictv); ~DictValue(); private: int type; union { AutoBuffer *pi; AutoBuffer *pd; AutoBuffer *ps; void *p; }; DictValue(int _type, void *_p) : type(_type), p(_p) {} void release(); }; /** @brief This class implements name-value dictionary, values are instances of DictValue. */ class CV_EXPORTS Dict { typedef std::map _Dict; _Dict dict; public: //! Checks a presence of the @p key in the dictionary. bool has(const String &key); //! If the @p key in the dictionary then returns pointer to its value, else returns NULL. DictValue *ptr(const String &key); //! If the @p key in the dictionary then returns its value, else an error will be generated. const DictValue &get(const String &key) const; /** @overload */ template T get(const String &key) const; //! If the @p key in the dictionary then returns its value, else returns @p defaultValue. template T get(const String &key, const T &defaultValue) const; //! Sets new @p value for the @p key, or adds new key-value pair into the dictionary. template const T &set(const String &key, const T &value); friend std::ostream &operator<<(std::ostream &stream, const Dict &dict); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/dnn/dnn.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DNN_DNN_HPP__ #define __OPENCV_DNN_DNN_HPP__ #include #include #include #include namespace cv { namespace dnn //! This namespace is used for dnn module functionlaity. { //! @addtogroup dnn //! @{ /** @brief Initialize dnn module and built-in layers. * * This function automatically called on most of OpenCV builds, * but you need to call it manually on some specific configurations (iOS for example). */ CV_EXPORTS void initModule(); /** @brief This class provides all data needed to initialize layer. * * It includes dictionary with scalar params (which can be readed by using Dict interface), * blob params #blobs and optional meta information: #name and #type of layer instance. */ struct CV_EXPORTS LayerParams : public Dict { std::vector blobs; //!< List of learned parameters stored as blobs. String name; //!< Name of the layer instance (optional, can be used internal purposes). String type; //!< Type name which was used for creating layer by layer factory (optional). }; /** @brief This interface class allows to build new Layers - are building blocks of networks. * * Each class, derived from Layer, must implement allocate() methods to declare own outputs and forward() to compute outputs. * Also before using the new layer into networks you must register your layer by using one of @ref LayerFactoryModule "LayerFactory" macros. */ struct CV_EXPORTS Layer { //! List of learned parameters must be stored here to allow read them by using Net::getParam(). std::vector blobs; /** @brief Allocates internal buffers and output blobs with respect to the shape of inputs. * @param[in] input vector of already allocated input blobs * @param[out] output vector of output blobs, which must be allocated * * This method must create each produced blob according to shape of @p input blobs and internal layer params. * If this method is called first time then @p output vector consists from empty blobs and its size determined by number of output connections. * This method can be called multiple times if size of any @p input blob was changed. */ virtual void allocate(const std::vector &input, std::vector &output) = 0; /** @brief Given the @p input blobs, computes the output @p blobs. * @param[in] input the input blobs. * @param[out] output allocated output blobs, which will store results of the computation. */ virtual void forward(std::vector &input, std::vector &output) = 0; /** @brief Returns index of input blob into the input array. * @param inputName label of input blob * * Each layer input and output can be labeled to easily identify them using "%[.output_name]" notation. * This method maps label of input blob to its index into input vector. */ virtual int inputNameToIndex(String inputName); /** @brief Returns index of output blob in output array. * @see inputNameToIndex() */ virtual int outputNameToIndex(String outputName); String name; //!< Name of the layer instance, can be used for logging or other internal purposes. String type; //!< Type name which was used for creating layer by layer factory. Layer(); explicit Layer(const LayerParams ¶ms); //!< Initialize only #name, #type and #blobs fields. virtual ~Layer(); }; /** @brief This class allows to create and manipulate comprehensive artificial neural networks. * * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances, * and edges specify relationships between layers inputs and outputs. * * Each network layer has unique integer id and unique string name inside its network. * LayerId can store either layer name or layer id. * * This class supports reference counting of its instances, i. e. copies point to the same instance. */ class CV_EXPORTS Net { public: Net(); //!< Default constructor. ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore. /** @brief Adds new layer to the net. * @param name unique name of the adding layer. * @param type typename of the adding layer (type must be registered in LayerRegister). * @param params parameters which will be used to initialize the creating layer. * @returns unique identifier of created layer, or -1 if a failure will happen. */ int addLayer(const String &name, const String &type, LayerParams ¶ms); /** @brief Adds new layer and connects its first input to the first output of previously added layer. * @see addLayer() */ int addLayerToPrev(const String &name, const String &type, LayerParams ¶ms); /** @brief Converts string name of the layer to the integer identifier. * @returns id of the layer, or -1 if the layer wasn't found. */ int getLayerId(const String &layer); /** @brief Container for strings and integers. */ typedef DictValue LayerId; /** @brief Delete layer for the network (not implemented yet) */ void deleteLayer(LayerId layer); /** @brief Connects output of the first layer to input of the second layer. * @param outPin descriptor of the first layer output. * @param inpPin descriptor of the second layer input. * * Descriptors have the following template <layer_name>[.input_number]: * - the first part of the template layer_name is sting name of the added layer. * If this part is empty then the network input pseudo layer will be used; * - the second optional part of the template input_number * is either number of the layer input, either label one. * If this part is omitted then the first layer input will be used. * * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex() */ void connect(String outPin, String inpPin); /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer. * @param outLayerId identifier of the first layer * @param inpLayerId identifier of the second layer * @param outNum number of the first layer output * @param inpNum number of the second layer input */ void connect(int outLayerId, int outNum, int inpLayerId, int inpNum); /** @brief Sets ouputs names of the network input pseudo layer. * * Each net always has special own the network input pseudo layer with id=0. * This layer stores the user blobs only and don't make any computations. * In fact, this layer provides the only way to pass user data into the network. * As any other layer, this layer can label its outputs and this function provides an easy way to do this. */ void setNetInputs(const std::vector &inputBlobNames); /** @brief Runs forward pass for the whole network */ void forward(); /** @brief Runs forward pass to compute output of layer @p toLayer */ void forward(LayerId toLayer); /** @brief Runs forward pass to compute output of layer @p toLayer, but computations start from @p startLayer */ void forward(LayerId startLayer, LayerId toLayer); /** @overload */ void forward(const std::vector &startLayers, const std::vector &toLayers); //TODO: /** @brief Optimized forward. * @warning Not implemented yet. * @details Makes forward only those layers which weren't changed after previous forward(). */ void forwardOpt(LayerId toLayer); /** @overload */ void forwardOpt(const std::vector &toLayers); /** @brief Sets the new value for the layer output blob * @param outputName descriptor of the updating layer output blob. * @param blob new blob. * @see connect(String, String) to know format of the descriptor. * @note If updating blob is not empty then @p blob must have the same shape, * because network reshaping is not implemented yet. */ void setBlob(String outputName, const Blob &blob); /** @brief Returns the layer output blob. * @param outputName the descriptor of the returning layer output blob. * @see connect(String, String) */ Blob getBlob(String outputName); /** @brief Sets the new value for the learned param of the layer. * @param layer name or id of the layer. * @param numParam index of the layer parameter in the Layer::blobs array. * @param blob the new value. * @see Layer::blobs * @note If shape of the new blob differs from the previous shape, * then the following forward pass may fail. */ void setParam(LayerId layer, int numParam, const Blob &blob); /** @brief Returns parameter blob of the layer. * @param layer name or id of the layer. * @param numParam index of the layer parameter in the Layer::blobs array. * @see Layer::blobs */ Blob getParam(LayerId layer, int numParam = 0); private: struct Impl; Ptr impl; }; /** @brief Small interface class for loading trained serialized models of different dnn-frameworks. */ class Importer { public: /** @brief Adds loaded layers into the @p net and sets connetions between them. */ virtual void populateNet(Net net) = 0; virtual ~Importer(); }; /** @brief Creates the importer of Caffe framework network. * @param prototxt path to the .prototxt file with text description of the network architecture. * @param caffeModel path to the .caffemodel file with learned network. * @returns Pointer to the created importer, NULL in failure cases. */ CV_EXPORTS Ptr createCaffeImporter(const String &prototxt, const String &caffeModel = String()); /** @brief Creates the importer of Torch7 framework network. * @param filename path to the file, dumped from Torch by using torch.save() function. * @param isBinary specifies whether the network was serialized in ascii mode or binary. * @returns Pointer to the created importer, NULL in failure cases. * * @warning Torch7 importer is experimental now, you need explicitly set CMake opencv_dnn_BUILD_TORCH_IMPORTER flag to compile its. * * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use long type of C language, * which has different bit-length on different systems. * * The loading file must contain serialized nn.Module object * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors. * * List of supported layers (i.e. object instances derived from Torch nn.Module class): * - nn.Sequential * - nn.Parallel * - nn.Concat * - nn.Linear * - nn.SpatialConvolution * - nn.SpatialMaxPooling, nn.SpatialAveragePooling * - nn.ReLU, nn.TanH, nn.Sigmoid * - nn.Reshape * * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported. */ CV_EXPORTS Ptr createTorchImporter(const String &filename, bool isBinary = true); /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework. * @warning This function has the same limitations as createTorchImporter(). */ CV_EXPORTS Blob readTorchBlob(const String &filename, bool isBinary = true); //! @} } } #include #include #endif /* __OPENCV_DNN_DNN_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/dnn/dnn.inl.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DNN_DNN_INL_HPP__ #define __OPENCV_DNN_DNN_INL_HPP__ #include namespace cv { namespace dnn { template DictValue DictValue::arrayInt(TypeIter begin, int size) { DictValue res(Param::INT, new AutoBuffer(size)); for (int j = 0; j < size; begin++, j++) (*res.pi)[j] = *begin; return res; } template DictValue DictValue::arrayReal(TypeIter begin, int size) { DictValue res(Param::REAL, new AutoBuffer(size)); for (int j = 0; j < size; begin++, j++) (*res.pd)[j] = *begin; return res; } template DictValue DictValue::arrayString(TypeIter begin, int size) { DictValue res(Param::STRING, new AutoBuffer(size)); for (int j = 0; j < size; begin++, j++) (*res.ps)[j] = *begin; return res; } template<> inline DictValue DictValue::get(int idx) const { CV_Assert(idx == -1); return *this; } template<> inline int64 DictValue::get(int idx) const { CV_Assert(idx == -1 && size() == 1 || idx >= 0 && idx < size()); idx = (idx == -1) ? 0 : idx; if (type == Param::INT) { return (*pi)[idx]; } else if (type == Param::REAL) { double doubleValue = (*pd)[idx]; double fracpart, intpart; fracpart = std::modf(doubleValue, &intpart); CV_Assert(fracpart == 0.0); return (int64)doubleValue; } else { CV_Assert(isInt() || isReal()); return 0; } } template<> inline int DictValue::get(int idx) const { return (int)get(idx); } template<> inline unsigned DictValue::get(int idx) const { return (unsigned)get(idx); } template<> inline bool DictValue::get(int idx) const { return (get(idx) != 0); } template<> inline double DictValue::get(int idx) const { CV_Assert(idx == -1 && size() == 1 || idx >= 0 && idx < size()); idx = (idx == -1) ? 0 : idx; if (type == Param::REAL) { return (*pd)[idx]; } else if (type == Param::INT) { return (double)(*pi)[idx]; } else { CV_Assert(isReal() || isInt()); return 0; } } template<> inline float DictValue::get(int idx) const { return (float)get(idx); } template<> inline String DictValue::get(int idx) const { CV_Assert(isString()); CV_Assert(idx == -1 && ps->size() == 1 || idx >= 0 && idx < (int)ps->size()); return (*ps)[(idx == -1) ? 0 : idx]; } inline void DictValue::release() { switch (type) { case Param::INT: delete pi; break; case Param::STRING: delete ps; break; case Param::REAL: delete pd; break; } } inline DictValue::~DictValue() { release(); } inline DictValue & DictValue::operator=(const DictValue &r) { if (&r == this) return *this; if (r.type == Param::INT) { AutoBuffer *tmp = new AutoBuffer(*r.pi); release(); pi = tmp; } else if (r.type == Param::STRING) { AutoBuffer *tmp = new AutoBuffer(*r.ps); release(); ps = tmp; } else if (r.type == Param::REAL) { AutoBuffer *tmp = new AutoBuffer(*r.pd); release(); pd = tmp; } type = r.type; return *this; } inline DictValue::DictValue(const DictValue &r) { type = r.type; if (r.type == Param::INT) pi = new AutoBuffer(*r.pi); else if (r.type == Param::STRING) ps = new AutoBuffer(*r.ps); else if (r.type == Param::REAL) pd = new AutoBuffer(*r.pd); } inline bool DictValue::isString() const { return (type == Param::STRING); } inline bool DictValue::isInt() const { return (type == Param::INT); } inline bool DictValue::isReal() const { return (type == Param::REAL || type == Param::INT); } inline int DictValue::size() const { switch (type) { case Param::INT: return (int)pi->size(); break; case Param::STRING: return (int)ps->size(); break; case Param::REAL: return (int)pd->size(); break; default: CV_Error(Error::StsInternal, ""); return -1; } } inline std::ostream &operator<<(std::ostream &stream, const DictValue &dictv) { int i; if (dictv.isInt()) { for (i = 0; i < dictv.size() - 1; i++) stream << dictv.get(i) << ", "; stream << dictv.get(i); } else if (dictv.isReal()) { for (i = 0; i < dictv.size() - 1; i++) stream << dictv.get(i) << ", "; stream << dictv.get(i); } else if (dictv.isString()) { for (i = 0; i < dictv.size() - 1; i++) stream << "\"" << dictv.get(i) << "\", "; stream << dictv.get(i); } return stream; } ///////////////////////////////////////////////////////////////// inline bool Dict::has(const String &key) { return dict.count(key) != 0; } inline DictValue *Dict::ptr(const String &key) { _Dict::iterator i = dict.find(key); return (i == dict.end()) ? NULL : &i->second; } inline const DictValue &Dict::get(const String &key) const { _Dict::const_iterator i = dict.find(key); if (i == dict.end()) CV_Error(Error::StsObjectNotFound, "Required argument \"" + key + "\" not found into dictionary"); return i->second; } template inline T Dict::get(const String &key) const { return this->get(key).get(); } template inline T Dict::get(const String &key, const T &defaultValue) const { _Dict::const_iterator i = dict.find(key); if (i != dict.end()) return i->second.get(); else return defaultValue; } template inline const T &Dict::set(const String &key, const T &value) { _Dict::iterator i = dict.find(key); if (i != dict.end()) i->second = DictValue(value); else dict.insert(std::make_pair(key, DictValue(value))); return value; } inline std::ostream &operator<<(std::ostream &stream, const Dict &dict) { Dict::_Dict::const_iterator it; for (it = dict.dict.begin(); it != dict.dict.end(); it++) stream << it->first << " : " << it->second << "\n"; return stream; } } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/dnn/layer.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DNN_LAYER_HPP__ #define __OPENCV_DNN_LAYER_HPP__ #include namespace cv { namespace dnn { //! @addtogroup dnn //! @{ //! //! @defgroup LayerFactoryModule Utilities for new layers registration //! @{ /** @brief %Layer factory allows to create instances of registered layers. */ class CV_EXPORTS LayerFactory { public: //! Each Layer class must provide this function to the factory typedef Ptr(*Constuctor)(LayerParams ¶ms); //! Registers the layer class with typename @p type and specified @p constructor. static void registerLayer(const String &type, Constuctor constructor); //! Unregisters registered layer with specified type name. static void unregisterLayer(const String &type); /** @brief Creates instance of registered layer. * @param type type name of creating layer. * @param params parameters which will be used for layer initialization. */ static Ptr createLayerInstance(const String &type, LayerParams& params); private: LayerFactory(); struct Impl; static Ptr impl(); }; /** @brief Registers layer constructor in runtime. * @param type string, containing type name of the layer. * @param constuctorFunc pointer to the function of type LayerRegister::Constuctor, which creates the layer. * @details This macros must be placed inside the function code. */ #define REG_RUNTIME_LAYER_FUNC(type, constuctorFunc) \ LayerFactory::registerLayer(#type, constuctorFunc); /** @brief Registers layer class in runtime. * @param type string, containing type name of the layer. * @param class C++ class, derived from Layer. * @details This macros must be placed inside the function code. */ #define REG_RUNTIME_LAYER_CLASS(type, class) \ LayerFactory::registerLayer(#type, _layerDynamicRegisterer); /** @brief Registers layer constructor on module load time. * @param type string, containing type name of the layer. * @param constuctorFunc pointer to the function of type LayerRegister::Constuctor, which creates the layer. * @details This macros must be placed outside the function code. */ #define REG_STATIC_LAYER_FUNC(type, constuctorFunc) \ static _LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, constuctorFunc); /** @brief Registers layer class on module load time. * @param type string, containing type name of the layer. * @param class C++ class, derived from Layer. * @details This macros must be placed outside the function code. */ #define REG_STATIC_LAYER_CLASS(type, class) \ Ptr __LayerStaticRegisterer_func_##type(LayerParams ¶ms) \ { return Ptr(new class(params)); } \ static _LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, __LayerStaticRegisterer_func_##type); //! @} //! @} template Ptr _layerDynamicRegisterer(LayerParams ¶ms) { return Ptr(new LayerClass(params)); } //allows automatically register created layer on module load time struct _LayerStaticRegisterer { String type; _LayerStaticRegisterer(const String &type, LayerFactory::Constuctor constuctor) { this->type = type; LayerFactory::registerLayer(type, constuctor); } ~_LayerStaticRegisterer() { LayerFactory::unregisterLayer(type); } }; } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/dnn.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DNN_HPP__ #define __OPENCV_DNN_HPP__ // This is an umbrealla header to include into you project. // We are free to change headers layout in dnn subfolder, so please include // this header for future compartibility /** @defgroup dnn Deep Neural Network module @{ This module contains: - API for new layers creation, layers are building bricks of neural networks; - set of built-in most-useful Layers; - API to constuct and modify comprehensive neural networks from layers; - functionality for loading serialized networks models from differnet frameworks. Functionality of this module is designed only for forward pass computations (i. e. network testing). A network training is in principle not supported. @} */ #include #endif /* __OPENCV_DNN_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/dpm.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Itseez Inc or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // // Implementation authors: // Jiaolong Xu - jiaolongxu@gmail.com // Evgeniy Kozinov - evgeniy.kozinov@gmail.com // Valentina Kustikova - valentina.kustikova@gmail.com // Nikolai Zolotykh - Nikolai.Zolotykh@gmail.com // Iosif Meyerov - meerov@vmk.unn.ru // Alexey Polovinkin - polovinkin.alexey@gmail.com // //M*/ #ifndef __OPENCV_LATENTSVM_HPP__ #define __OPENCV_LATENTSVM_HPP__ #include "opencv2/core.hpp" #include #include #include /** @defgroup dpm Deformable Part-based Models Discriminatively Trained Part Based Models for Object Detection --------------------------------------------------------------- The object detector described below has been initially proposed by P.F. Felzenszwalb in @cite Felzenszwalb2010a . It is based on a Dalal-Triggs detector that uses a single filter on histogram of oriented gradients (HOG) features to represent an object category. This detector uses a sliding window approach, where a filter is applied at all positions and scales of an image. The first innovation is enriching the Dalal-Triggs model using a star-structured part-based model defined by a "root" filter (analogous to the Dalal-Triggs filter) plus a set of parts filters and associated deformation models. The score of one of star models at a particular position and scale within an image is the score of the root filter at the given location plus the sum over parts of the maximum, over placements of that part, of the part filter score on its location minus a deformation cost easuring the deviation of the part from its ideal location relative to the root. Both root and part filter scores are defined by the dot product between a filter (a set of weights) and a subwindow of a feature pyramid computed from the input image. Another improvement is a representation of the class of models by a mixture of star models. The score of a mixture model at a particular position and scale is the maximum over components, of the score of that component model at the given location. The detector was dramatically speeded-up with cascade algorithm proposed by P.F. Felzenszwalb in @cite Felzenszwalb2010b . The algorithm prunes partial hypotheses using thresholds on their scores.The basic idea of the algorithm is to use a hierarchy of models defined by an ordering of the original model's parts. For a model with (n+1) parts, including the root, a sequence of (n+1) models is obtained. The i-th model in this sequence is defined by the first i parts from the original model. Using this hierarchy, low scoring hypotheses can be pruned after looking at the best configuration of a subset of the parts. Hypotheses that score high under a weak model are evaluated further using a richer model. In OpenCV there is an C++ implementation of DPM cascade detector. */ namespace cv { namespace dpm { /** @brief This is a C++ abstract class, it provides external user API to work with DPM. */ class CV_EXPORTS_W DPMDetector { public: struct CV_EXPORTS_W ObjectDetection { ObjectDetection(); ObjectDetection( const Rect& rect, float score, int classID=-1 ); Rect rect; float score; int classID; }; virtual bool isEmpty() const = 0; /** @brief Find rectangular regions in the given image that are likely to contain objects of loaded classes (models) and corresponding confidence levels. @param image An image. @param objects The detections: rectangulars, scores and class IDs. */ virtual void detect(cv::Mat &image, CV_OUT std::vector &objects) = 0; /** @brief Return the class (model) names that were passed in constructor or method load or extracted from models filenames in those methods. */ virtual std::vector const& getClassNames() const = 0; /** @brief Return a count of loaded models (classes). */ virtual size_t getClassCount() const = 0; /** @brief Load the trained models from given .xml files and return cv::Ptr\. @param filenames A set of filenames storing the trained detectors (models). Each file contains one model. See examples of such files here `/opencv_extra/testdata/cv/dpm/VOC2007_Cascade/`. @param classNames A set of trained models names. If it's empty then the name of each model will be constructed from the name of file containing the model. E.g. the model stored in "/home/user/cat.xml" will get the name "cat". */ static cv::Ptr create(std::vector const &filenames, std::vector const &classNames = std::vector()); virtual ~DPMDetector(){} }; } // namespace dpm } // namespace cv #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/face/facerec.hpp ================================================ // This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // Copyright (c) 2011,2012. Philipp Wagner . // Third party copyrights are property of their respective owners. #ifndef __OPENCV_FACEREC_HPP__ #define __OPENCV_FACEREC_HPP__ #include "opencv2/face.hpp" #include "opencv2/core.hpp" namespace cv { namespace face { //! @addtogroup face //! @{ // base for two classes class CV_EXPORTS_W BasicFaceRecognizer : public FaceRecognizer { public: /** @see setNumComponents */ CV_WRAP virtual int getNumComponents() const = 0; /** @copybrief getNumComponents @see getNumComponents */ CV_WRAP virtual void setNumComponents(int val) = 0; /** @see setThreshold */ CV_WRAP virtual double getThreshold() const = 0; /** @copybrief getThreshold @see getThreshold */ CV_WRAP virtual void setThreshold(double val) = 0; CV_WRAP virtual std::vector getProjections() const = 0; CV_WRAP virtual cv::Mat getLabels() const = 0; CV_WRAP virtual cv::Mat getEigenValues() const = 0; CV_WRAP virtual cv::Mat getEigenVectors() const = 0; CV_WRAP virtual cv::Mat getMean() const = 0; }; /** @param num_components The number of components (read: Eigenfaces) kept for this Principal Component Analysis. As a hint: There's no rule how many components (read: Eigenfaces) should be kept for good reconstruction capabilities. It is based on your input data, so experiment with the number. Keeping 80 components should almost always be sufficient. @param threshold The threshold applied in the prediction. ### Notes: - Training and prediction must be done on grayscale images, use cvtColor to convert between the color spaces. - **THE EIGENFACES METHOD MAKES THE ASSUMPTION, THAT THE TRAINING AND TEST IMAGES ARE OF EQUAL SIZE.** (caps-lock, because I got so many mails asking for this). You have to make sure your input data has the correct shape, else a meaningful exception is thrown. Use resize to resize the images. - This model does not support updating. ### Model internal data: - num_components see createEigenFaceRecognizer. - threshold see createEigenFaceRecognizer. - eigenvalues The eigenvalues for this Principal Component Analysis (ordered descending). - eigenvectors The eigenvectors for this Principal Component Analysis (ordered by their eigenvalue). - mean The sample mean calculated from the training data. - projections The projections of the training data. - labels The threshold applied in the prediction. If the distance to the nearest neighbor is larger than the threshold, this method returns -1. */ CV_EXPORTS_W Ptr createEigenFaceRecognizer(int num_components = 0, double threshold = DBL_MAX); /** @param num_components The number of components (read: Fisherfaces) kept for this Linear Discriminant Analysis with the Fisherfaces criterion. It's useful to keep all components, that means the number of your classes c (read: subjects, persons you want to recognize). If you leave this at the default (0) or set it to a value less-equal 0 or greater (c-1), it will be set to the correct number (c-1) automatically. @param threshold The threshold applied in the prediction. If the distance to the nearest neighbor is larger than the threshold, this method returns -1. ### Notes: - Training and prediction must be done on grayscale images, use cvtColor to convert between the color spaces. - **THE FISHERFACES METHOD MAKES THE ASSUMPTION, THAT THE TRAINING AND TEST IMAGES ARE OF EQUAL SIZE.** (caps-lock, because I got so many mails asking for this). You have to make sure your input data has the correct shape, else a meaningful exception is thrown. Use resize to resize the images. - This model does not support updating. ### Model internal data: - num_components see createFisherFaceRecognizer. - threshold see createFisherFaceRecognizer. - eigenvalues The eigenvalues for this Linear Discriminant Analysis (ordered descending). - eigenvectors The eigenvectors for this Linear Discriminant Analysis (ordered by their eigenvalue). - mean The sample mean calculated from the training data. - projections The projections of the training data. - labels The labels corresponding to the projections. */ CV_EXPORTS_W Ptr createFisherFaceRecognizer(int num_components = 0, double threshold = DBL_MAX); class CV_EXPORTS_W LBPHFaceRecognizer : public FaceRecognizer { public: /** @see setGridX */ CV_WRAP virtual int getGridX() const = 0; /** @copybrief getGridX @see getGridX */ CV_WRAP virtual void setGridX(int val) = 0; /** @see setGridY */ CV_WRAP virtual int getGridY() const = 0; /** @copybrief getGridY @see getGridY */ CV_WRAP virtual void setGridY(int val) = 0; /** @see setRadius */ CV_WRAP virtual int getRadius() const = 0; /** @copybrief getRadius @see getRadius */ CV_WRAP virtual void setRadius(int val) = 0; /** @see setNeighbors */ CV_WRAP virtual int getNeighbors() const = 0; /** @copybrief getNeighbors @see getNeighbors */ CV_WRAP virtual void setNeighbors(int val) = 0; /** @see setThreshold */ CV_WRAP virtual double getThreshold() const = 0; /** @copybrief getThreshold @see getThreshold */ CV_WRAP virtual void setThreshold(double val) = 0; CV_WRAP virtual std::vector getHistograms() const = 0; CV_WRAP virtual cv::Mat getLabels() const = 0; }; /** @param radius The radius used for building the Circular Local Binary Pattern. The greater the radius, the @param neighbors The number of sample points to build a Circular Local Binary Pattern from. An appropriate value is to use `8` sample points. Keep in mind: the more sample points you include, the higher the computational cost. @param grid_x The number of cells in the horizontal direction, 8 is a common value used in publications. The more cells, the finer the grid, the higher the dimensionality of the resulting feature vector. @param grid_y The number of cells in the vertical direction, 8 is a common value used in publications. The more cells, the finer the grid, the higher the dimensionality of the resulting feature vector. @param threshold The threshold applied in the prediction. If the distance to the nearest neighbor is larger than the threshold, this method returns -1. ### Notes: - The Circular Local Binary Patterns (used in training and prediction) expect the data given as grayscale images, use cvtColor to convert between the color spaces. - This model supports updating. ### Model internal data: - radius see createLBPHFaceRecognizer. - neighbors see createLBPHFaceRecognizer. - grid_x see createLBPHFaceRecognizer. - grid_y see createLBPHFaceRecognizer. - threshold see createLBPHFaceRecognizer. - histograms Local Binary Patterns Histograms calculated from the given training data (empty if none was given). - labels Labels corresponding to the calculated Local Binary Patterns Histograms. */ CV_EXPORTS_W Ptr createLBPHFaceRecognizer(int radius=1, int neighbors=8, int grid_x=8, int grid_y=8, double threshold = DBL_MAX); //! @} }} //namespace cv::face #endif //__OPENCV_FACEREC_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/face/predict_collector.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2000-2015, Intel Corporation, all rights reserved. Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. Copyright (C) 2009-2015, NVIDIA Corporation, all rights reserved. Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. Copyright (C) 2015, OpenCV Foundation, all rights reserved. Copyright (C) 2015, Itseez Inc., all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_PREDICT_COLLECTOR_HPP__ #define __OPENCV_PREDICT_COLLECTOR_HPP__ #include #include "opencv2/core/cvdef.h" #include "opencv2/core/cvstd.hpp" namespace cv { namespace face { //! @addtogroup face //! @{ /** @brief Abstract base class for all strategies of prediction result handling */ class CV_EXPORTS_W PredictCollector { protected: double _threshhold; int _size; int _state; public: /** @brief creates new predict collector with given threshhold */ PredictCollector(double threshhold = DBL_MAX) :_threshhold(threshhold) {}; CV_WRAP virtual ~PredictCollector() {} /** @brief called once at start of recognition @param size total size of prediction evaluation that recognizer could perform @param state user defined send-to-back optional value to allow multi-thread, multi-session or aggregation scenarios */ CV_WRAP virtual void init(const int size, const int state = 0); /** @brief called with every recognition result @param label current prediction label @param dist current prediction distance (confidence) @param state user defined send-to-back optional value to allow multi-thread, multi-session or aggregation scenarios @return true if recognizer should proceed prediction , false - if recognizer should terminate prediction */ CV_WRAP virtual bool emit(const int label, const double dist, const int state = 0); //not abstract while Python generation require non-abstract class }; /** @brief default predict collector that trace minimal distance with treshhold checking (that is default behavior for most predict logic) */ class CV_EXPORTS_W MinDistancePredictCollector : public PredictCollector { private: int _label; double _dist; public: /** @brief creates new MinDistancePredictCollector with given threshhold */ CV_WRAP MinDistancePredictCollector(double threshhold = DBL_MAX) : PredictCollector(threshhold) { _label = 0; _dist = DBL_MAX; }; CV_WRAP bool emit(const int label, const double dist, const int state = 0); /** @brief result label, 0 if not found */ CV_WRAP int getLabel() const; /** @brief result distance (confidence) DBL_MAX if not found */ CV_WRAP double getDist() const; /** @brief factory method to create cv-pointers to MinDistancePredictCollector */ CV_WRAP static Ptr create(double threshold = DBL_MAX); }; //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/face.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_FACE_HPP__ #define __OPENCV_FACE_HPP__ /** @defgroup face Face Recognition - @ref face_changelog - @ref tutorial_face_main */ #include "opencv2/core.hpp" #include "face/predict_collector.hpp" #include namespace cv { namespace face { //! @addtogroup face //! @{ /** @brief Abstract base class for all face recognition models All face recognition models in OpenCV are derived from the abstract base class FaceRecognizer, which provides a unified access to all face recongition algorithms in OpenCV. ### Description I'll go a bit more into detail explaining FaceRecognizer, because it doesn't look like a powerful interface at first sight. But: Every FaceRecognizer is an Algorithm, so you can easily get/set all model internals (if allowed by the implementation). Algorithm is a relatively new OpenCV concept, which is available since the 2.4 release. I suggest you take a look at its description. Algorithm provides the following features for all derived classes: - So called “virtual constructor”. That is, each Algorithm derivative is registered at program start and you can get the list of registered algorithms and create instance of a particular algorithm by its name (see Algorithm::create). If you plan to add your own algorithms, it is good practice to add a unique prefix to your algorithms to distinguish them from other algorithms. - Setting/Retrieving algorithm parameters by name. If you used video capturing functionality from OpenCV highgui module, you are probably familar with cv::cvSetCaptureProperty, ocvcvGetCaptureProperty, VideoCapture::set and VideoCapture::get. Algorithm provides similar method where instead of integer id's you specify the parameter names as text Strings. See Algorithm::set and Algorithm::get for details. - Reading and writing parameters from/to XML or YAML files. Every Algorithm derivative can store all its parameters and then read them back. There is no need to re-implement it each time. Moreover every FaceRecognizer supports the: - **Training** of a FaceRecognizer with FaceRecognizer::train on a given set of images (your face database!). - **Prediction** of a given sample image, that means a face. The image is given as a Mat. - **Loading/Saving** the model state from/to a given XML or YAML. - **Setting/Getting labels info**, that is stored as a string. String labels info is useful for keeping names of the recognized people. @note When using the FaceRecognizer interface in combination with Python, please stick to Python 2. Some underlying scripts like create_csv will not work in other versions, like Python 3. Setting the Thresholds +++++++++++++++++++++++ Sometimes you run into the situation, when you want to apply a threshold on the prediction. A common scenario in face recognition is to tell, whether a face belongs to the training dataset or if it is unknown. You might wonder, why there's no public API in FaceRecognizer to set the threshold for the prediction, but rest assured: It's supported. It just means there's no generic way in an abstract class to provide an interface for setting/getting the thresholds of *every possible* FaceRecognizer algorithm. The appropriate place to set the thresholds is in the constructor of the specific FaceRecognizer and since every FaceRecognizer is a Algorithm (see above), you can get/set the thresholds at runtime! Here is an example of setting a threshold for the Eigenfaces method, when creating the model: @code // Let's say we want to keep 10 Eigenfaces and have a threshold value of 10.0 int num_components = 10; double threshold = 10.0; // Then if you want to have a cv::FaceRecognizer with a confidence threshold, // create the concrete implementation with the appropiate parameters: Ptr model = createEigenFaceRecognizer(num_components, threshold); @endcode Sometimes it's impossible to train the model, just to experiment with threshold values. Thanks to Algorithm it's possible to set internal model thresholds during runtime. Let's see how we would set/get the prediction for the Eigenface model, we've created above: @code // The following line reads the threshold from the Eigenfaces model: double current_threshold = model->getDouble("threshold"); // And this line sets the threshold to 0.0: model->set("threshold", 0.0); @endcode If you've set the threshold to 0.0 as we did above, then: @code // Mat img = imread("person1/3.jpg", CV_LOAD_IMAGE_GRAYSCALE); // Get a prediction from the model. Note: We've set a threshold of 0.0 above, // since the distance is almost always larger than 0.0, you'll get -1 as // label, which indicates, this face is unknown int predicted_label = model->predict(img); // ... @endcode is going to yield -1 as predicted label, which states this face is unknown. ### Getting the name of a FaceRecognizer Since every FaceRecognizer is a Algorithm, you can use Algorithm::name to get the name of a FaceRecognizer: @code // Create a FaceRecognizer: Ptr model = createEigenFaceRecognizer(); // And here's how to get its name: String name = model->name(); @endcode */ class CV_EXPORTS_W FaceRecognizer : public Algorithm { public: /** @brief Trains a FaceRecognizer with given data and associated labels. @param src The training images, that means the faces you want to learn. The data has to be given as a vector\. @param labels The labels corresponding to the images have to be given either as a vector\ or a The following source code snippet shows you how to learn a Fisherfaces model on a given set of images. The images are read with imread and pushed into a std::vector\. The labels of each image are stored within a std::vector\ (you could also use a Mat of type CV_32SC1). Think of the label as the subject (the person) this image belongs to, so same subjects (persons) should have the same label. For the available FaceRecognizer you don't have to pay any attention to the order of the labels, just make sure same persons have the same label: @code // holds images and labels vector images; vector labels; // images for first person images.push_back(imread("person0/0.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0); images.push_back(imread("person0/1.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0); images.push_back(imread("person0/2.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0); // images for second person images.push_back(imread("person1/0.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1); images.push_back(imread("person1/1.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1); images.push_back(imread("person1/2.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1); @endcode Now that you have read some images, we can create a new FaceRecognizer. In this example I'll create a Fisherfaces model and decide to keep all of the possible Fisherfaces: @code // Create a new Fisherfaces model and retain all available Fisherfaces, // this is the most common usage of this specific FaceRecognizer: // Ptr model = createFisherFaceRecognizer(); @endcode And finally train it on the given dataset (the face images and labels): @code // This is the common interface to train all of the available cv::FaceRecognizer // implementations: // model->train(images, labels); @endcode */ CV_WRAP virtual void train(InputArrayOfArrays src, InputArray labels) = 0; /** @brief Updates a FaceRecognizer with given data and associated labels. @param src The training images, that means the faces you want to learn. The data has to be given as a vector\. @param labels The labels corresponding to the images have to be given either as a vector\ or a This method updates a (probably trained) FaceRecognizer, but only if the algorithm supports it. The Local Binary Patterns Histograms (LBPH) recognizer (see createLBPHFaceRecognizer) can be updated. For the Eigenfaces and Fisherfaces method, this is algorithmically not possible and you have to re-estimate the model with FaceRecognizer::train. In any case, a call to train empties the existing model and learns a new model, while update does not delete any model data. @code // Create a new LBPH model (it can be updated) and use the default parameters, // this is the most common usage of this specific FaceRecognizer: // Ptr model = createLBPHFaceRecognizer(); // This is the common interface to train all of the available cv::FaceRecognizer // implementations: // model->train(images, labels); // Some containers to hold new image: vector newImages; vector newLabels; // You should add some images to the containers: // // ... // // Now updating the model is as easy as calling: model->update(newImages,newLabels); // This will preserve the old model data and extend the existing model // with the new features extracted from newImages! @endcode Calling update on an Eigenfaces model (see createEigenFaceRecognizer), which doesn't support updating, will throw an error similar to: @code OpenCV Error: The function/feature is not implemented (This FaceRecognizer (FaceRecognizer.Eigenfaces) does not support updating, you have to use FaceRecognizer::train to update it.) in update, file /home/philipp/git/opencv/modules/contrib/src/facerec.cpp, line 305 terminate called after throwing an instance of 'cv::Exception' @endcode @note The FaceRecognizer does not store your training images, because this would be very memory intense and it's not the responsibility of te FaceRecognizer to do so. The caller is responsible for maintaining the dataset, he want to work with. */ CV_WRAP virtual void update(InputArrayOfArrays src, InputArray labels); /** @overload */ CV_WRAP int predict(InputArray src) const; /** @brief Predicts a label and associated confidence (e.g. distance) for a given input image. @param src Sample image to get a prediction from. @param label The predicted label for the given image. @param confidence Associated confidence (e.g. distance) for the predicted label. The suffix const means that prediction does not affect the internal model state, so the method can be safely called from within different threads. The following example shows how to get a prediction from a trained model: @code using namespace cv; // Do your initialization here (create the cv::FaceRecognizer model) ... // ... // Read in a sample image: Mat img = imread("person1/3.jpg", CV_LOAD_IMAGE_GRAYSCALE); // And get a prediction from the cv::FaceRecognizer: int predicted = model->predict(img); @endcode Or to get a prediction and the associated confidence (e.g. distance): @code using namespace cv; // Do your initialization here (create the cv::FaceRecognizer model) ... // ... Mat img = imread("person1/3.jpg", CV_LOAD_IMAGE_GRAYSCALE); // Some variables for the predicted label and associated confidence (e.g. distance): int predicted_label = -1; double predicted_confidence = 0.0; // Get the prediction and associated confidence from the model model->predict(img, predicted_label, predicted_confidence); @endcode */ CV_WRAP void predict(InputArray src, CV_OUT int &label, CV_OUT double &confidence) const; /** @brief - if implemented - send all result of prediction to collector that can be used for somehow custom result handling @param src Sample image to get a prediction from. @param collector User-defined collector object that accepts all results @param state - optional user-defined state token that should be passed back from FaceRecognizer implementation To implement this method u just have to do same internal cycle as in predict(InputArray src, CV_OUT int &label, CV_OUT double &confidence) but not try to get "best@ result, just resend it to caller side with given collector */ CV_WRAP virtual void predict(InputArray src, Ptr collector, const int state = 0) const = 0; /** @brief Saves a FaceRecognizer and its model state. Saves this model to a given filename, either as XML or YAML. @param filename The filename to store this FaceRecognizer to (either XML/YAML). Every FaceRecognizer overwrites FaceRecognizer::save(FileStorage& fs) to save the internal model state. FaceRecognizer::save(const String& filename) saves the state of a model to the given filename. The suffix const means that prediction does not affect the internal model state, so the method can be safely called from within different threads. */ CV_WRAP virtual void save(const String& filename) const; /** @brief Loads a FaceRecognizer and its model state. Loads a persisted model and state from a given XML or YAML file . Every FaceRecognizer has to overwrite FaceRecognizer::load(FileStorage& fs) to enable loading the model state. FaceRecognizer::load(FileStorage& fs) in turn gets called by FaceRecognizer::load(const String& filename), to ease saving a model. */ CV_WRAP virtual void load(const String& filename); /** @overload Saves this model to a given FileStorage. @param fs The FileStorage to store this FaceRecognizer to. */ virtual void save(FileStorage& fs) const = 0; /** @overload */ virtual void load(const FileStorage& fs) = 0; /** @brief Sets string info for the specified model's label. The string info is replaced by the provided value if it was set before for the specified label. */ CV_WRAP virtual void setLabelInfo(int label, const String& strInfo); /** @brief Gets string information by label. If an unknown label id is provided or there is no label information associated with the specified label id the method returns an empty string. */ CV_WRAP virtual String getLabelInfo(int label) const; /** @brief Gets vector of labels by string. The function searches for the labels containing the specified sub-string in the associated string info. */ CV_WRAP virtual std::vector getLabelsByString(const String& str) const; /** @brief threshhold parameter accessor - required for default BestMinDist collector */ virtual double getThreshold() const = 0; protected: // Stored pairs "label id - string info" std::map _labelsInfo; }; //! @} }} #include "opencv2/face/facerec.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/features2d/features2d.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/features2d.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/features2d.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_FEATURES_2D_HPP__ #define __OPENCV_FEATURES_2D_HPP__ #include "opencv2/core.hpp" #include "opencv2/flann/miniflann.hpp" /** @defgroup features2d 2D Features Framework @{ @defgroup features2d_main Feature Detection and Description @defgroup features2d_match Descriptor Matchers Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables you to easily switch between different algorithms solving the same problem. This section is devoted to matching descriptors that are represented as vectors in a multidimensional space. All objects that implement vector descriptor matchers inherit the DescriptorMatcher interface. @note - An example explaining keypoint matching can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp - An example on descriptor matching evaluation can be found at opencv_source_code/samples/cpp/detector_descriptor_matcher_evaluation.cpp - An example on one to many image matching can be found at opencv_source_code/samples/cpp/matching_to_many_images.cpp @defgroup features2d_draw Drawing Function of Keypoints and Matches @defgroup features2d_category Object Categorization This section describes approaches based on local 2D features and used to categorize objects. @note - A complete Bag-Of-Words sample can be found at opencv_source_code/samples/cpp/bagofwords_classification.cpp - (Python) An example using the features2D framework to perform object categorization can be found at opencv_source_code/samples/python/find_obj.py @} */ namespace cv { //! @addtogroup features2d //! @{ // //! writes vector of keypoints to the file storage // CV_EXPORTS void write(FileStorage& fs, const String& name, const std::vector& keypoints); // //! reads vector of keypoints from the specified file storage node // CV_EXPORTS void read(const FileNode& node, CV_OUT std::vector& keypoints); /** @brief A class filters a vector of keypoints. Because now it is difficult to provide a convenient interface for all usage scenarios of the keypoints filter class, it has only several needed by now static methods. */ class CV_EXPORTS KeyPointsFilter { public: KeyPointsFilter(){} /* * Remove keypoints within borderPixels of an image edge. */ static void runByImageBorder( std::vector& keypoints, Size imageSize, int borderSize ); /* * Remove keypoints of sizes out of range. */ static void runByKeypointSize( std::vector& keypoints, float minSize, float maxSize=FLT_MAX ); /* * Remove keypoints from some image by mask for pixels of this image. */ static void runByPixelsMask( std::vector& keypoints, const Mat& mask ); /* * Remove duplicated keypoints. */ static void removeDuplicated( std::vector& keypoints ); /* * Retain the specified number of the best keypoints (according to the response) */ static void retainBest( std::vector& keypoints, int npoints ); }; /************************************ Base Classes ************************************/ /** @brief Abstract base class for 2D image feature detectors and descriptor extractors */ class CV_EXPORTS_W Feature2D : public virtual Algorithm { public: virtual ~Feature2D(); /** @brief Detects keypoints in an image (first variant) or image set (second variant). @param image Image. @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set of keypoints detected in images[i] . @param mask Mask specifying where to look for keypoints (optional). It must be a 8-bit integer matrix with non-zero values in the region of interest. */ CV_WRAP virtual void detect( InputArray image, CV_OUT std::vector& keypoints, InputArray mask=noArray() ); /** @overload @param images Image set. @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set of keypoints detected in images[i] . @param masks Masks for each input image specifying where to look for keypoints (optional). masks[i] is a mask for images[i]. */ virtual void detect( InputArrayOfArrays images, std::vector >& keypoints, InputArrayOfArrays masks=noArray() ); /** @brief Computes the descriptors for a set of keypoints detected in an image (first variant) or image set (second variant). @param image Image. @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint with several dominant orientations (for each orientation). @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the descriptor for keypoint j-th keypoint. */ CV_WRAP virtual void compute( InputArray image, CV_OUT CV_IN_OUT std::vector& keypoints, OutputArray descriptors ); /** @overload @param images Image set. @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint with several dominant orientations (for each orientation). @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the descriptor for keypoint j-th keypoint. */ virtual void compute( InputArrayOfArrays images, std::vector >& keypoints, OutputArrayOfArrays descriptors ); /** Detects keypoints and computes the descriptors */ CV_WRAP virtual void detectAndCompute( InputArray image, InputArray mask, CV_OUT std::vector& keypoints, OutputArray descriptors, bool useProvidedKeypoints=false ); CV_WRAP virtual int descriptorSize() const; CV_WRAP virtual int descriptorType() const; CV_WRAP virtual int defaultNorm() const; //! Return true if detector object is empty CV_WRAP virtual bool empty() const; }; /** Feature detectors in OpenCV have wrappers with a common interface that enables you to easily switch between different algorithms solving the same problem. All objects that implement keypoint detectors inherit the FeatureDetector interface. */ typedef Feature2D FeatureDetector; /** Extractors of keypoint descriptors in OpenCV have wrappers with a common interface that enables you to easily switch between different algorithms solving the same problem. This section is devoted to computing descriptors represented as vectors in a multidimensional space. All objects that implement the vector descriptor extractors inherit the DescriptorExtractor interface. */ typedef Feature2D DescriptorExtractor; //! @addtogroup features2d_main //! @{ /** @brief Class implementing the BRISK keypoint detector and descriptor extractor, described in @cite LCS11 . */ class CV_EXPORTS_W BRISK : public Feature2D { public: /** @brief The BRISK constructor @param thresh AGAST detection threshold score. @param octaves detection octaves. Use 0 to do single scale. @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a keypoint. */ CV_WRAP static Ptr create(int thresh=30, int octaves=3, float patternScale=1.0f); /** @brief The BRISK constructor for a custom pattern @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for keypoint scale 1). @param numberList defines the number of sampling points on the sampling circle. Must be the same size as radiusList.. @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint scale 1). @param dMin threshold for the long pairings used for orientation determination (in pixels for keypoint scale 1). @param indexChange index remapping of the bits. */ CV_WRAP static Ptr create(const std::vector &radiusList, const std::vector &numberList, float dMax=5.85f, float dMin=8.2f, const std::vector& indexChange=std::vector()); }; /** @brief Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, selects the strongest features using FAST or Harris response, finds their orientation using first-order moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or k-tuples) are rotated according to the measured orientation). */ class CV_EXPORTS_W ORB : public Feature2D { public: enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 }; /** @brief The ORB constructor @param nfeatures The maximum number of features to retain. @param scaleFactor Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor will mean that to cover certain scale range you will need more pyramid levels and so the speed will suffer. @param nlevels The number of pyramid levels. The smallest level will have linear size equal to input_image_linear_size/pow(scaleFactor, nlevels). @param edgeThreshold This is size of the border where the features are not detected. It should roughly match the patchSize parameter. @param firstLevel It should be 0 in the current implementation. @param WTA_K The number of points that produce each element of the oriented BRIEF descriptor. The default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 random points (of course, those point coordinates are random, but they are generated from the pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3). @param scoreType The default HARRIS_SCORE means that Harris algorithm is used to rank features (the score is written to KeyPoint::score and is used to retain best nfeatures features); FAST_SCORE is alternative value of the parameter that produces slightly less stable keypoints, but it is a little faster to compute. @param patchSize size of the patch used by the oriented BRIEF descriptor. Of course, on smaller pyramid layers the perceived image area covered by a feature will be larger. @param fastThreshold */ CV_WRAP static Ptr create(int nfeatures=500, float scaleFactor=1.2f, int nlevels=8, int edgeThreshold=31, int firstLevel=0, int WTA_K=2, int scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20); CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; CV_WRAP virtual int getMaxFeatures() const = 0; CV_WRAP virtual void setScaleFactor(double scaleFactor) = 0; CV_WRAP virtual double getScaleFactor() const = 0; CV_WRAP virtual void setNLevels(int nlevels) = 0; CV_WRAP virtual int getNLevels() const = 0; CV_WRAP virtual void setEdgeThreshold(int edgeThreshold) = 0; CV_WRAP virtual int getEdgeThreshold() const = 0; CV_WRAP virtual void setFirstLevel(int firstLevel) = 0; CV_WRAP virtual int getFirstLevel() const = 0; CV_WRAP virtual void setWTA_K(int wta_k) = 0; CV_WRAP virtual int getWTA_K() const = 0; CV_WRAP virtual void setScoreType(int scoreType) = 0; CV_WRAP virtual int getScoreType() const = 0; CV_WRAP virtual void setPatchSize(int patchSize) = 0; CV_WRAP virtual int getPatchSize() const = 0; CV_WRAP virtual void setFastThreshold(int fastThreshold) = 0; CV_WRAP virtual int getFastThreshold() const = 0; }; /** @brief Maximally stable extremal region extractor The class encapsulates all the parameters of the %MSER extraction algorithm (see [wiki article](http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions)). - there are two different implementation of %MSER: one for grey image, one for color image - the grey image algorithm is taken from: @cite nister2008linear ; the paper claims to be faster than union-find method; it actually get 1.5~2m/s on my centrino L7200 1.2GHz laptop. - the color image algorithm is taken from: @cite forssen2007maximally ; it should be much slower than grey image method ( 3~4 times ); the chi_table.h file is taken directly from paper's source code which is distributed under GPL. - (Python) A complete example showing the use of the %MSER detector can be found at samples/python/mser.py */ class CV_EXPORTS_W MSER : public Feature2D { public: /** @brief Full consturctor for %MSER detector @param _delta it compares \f$(size_{i}-size_{i-delta})/size_{i-delta}\f$ @param _min_area prune the area which smaller than minArea @param _max_area prune the area which bigger than maxArea @param _max_variation prune the area have simliar size to its children @param _min_diversity for color image, trace back to cut off mser with diversity less than min_diversity @param _max_evolution for color image, the evolution steps @param _area_threshold for color image, the area threshold to cause re-initialize @param _min_margin for color image, ignore too small margin @param _edge_blur_size for color image, the aperture size for edge blur */ CV_WRAP static Ptr create( int _delta=5, int _min_area=60, int _max_area=14400, double _max_variation=0.25, double _min_diversity=.2, int _max_evolution=200, double _area_threshold=1.01, double _min_margin=0.003, int _edge_blur_size=5 ); /** @brief Detect %MSER regions @param image input image (8UC1, 8UC3 or 8UC4) @param msers resulting list of point sets @param bboxes resulting bounding boxes */ CV_WRAP virtual void detectRegions( InputArray image, CV_OUT std::vector >& msers, std::vector& bboxes ) = 0; CV_WRAP virtual void setDelta(int delta) = 0; CV_WRAP virtual int getDelta() const = 0; CV_WRAP virtual void setMinArea(int minArea) = 0; CV_WRAP virtual int getMinArea() const = 0; CV_WRAP virtual void setMaxArea(int maxArea) = 0; CV_WRAP virtual int getMaxArea() const = 0; CV_WRAP virtual void setPass2Only(bool f) = 0; CV_WRAP virtual bool getPass2Only() const = 0; }; /** @overload */ CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, int threshold, bool nonmaxSuppression=true ); /** @brief Detects corners using the FAST algorithm @param image grayscale image where keypoints (corners) are detected. @param keypoints keypoints detected on the image. @param threshold threshold on difference between intensity of the central pixel and pixels of a circle around this pixel. @param nonmaxSuppression if true, non-maximum suppression is applied to detected corners (keypoints). @param type one of the three neighborhoods as defined in the paper: FastFeatureDetector::TYPE_9_16, FastFeatureDetector::TYPE_7_12, FastFeatureDetector::TYPE_5_8 Detects corners using the FAST algorithm by @cite Rosten06 . @note In Python API, types are given as cv2.FAST_FEATURE_DETECTOR_TYPE_5_8, cv2.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv2.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner detection, use cv2.FAST.detect() method. */ CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, int threshold, bool nonmaxSuppression, int type ); //! @} features2d_main //! @addtogroup features2d_main //! @{ /** @brief Wrapping class for feature detection using the FAST method. : */ class CV_EXPORTS_W FastFeatureDetector : public Feature2D { public: enum { TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2, THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002, }; CV_WRAP static Ptr create( int threshold=10, bool nonmaxSuppression=true, int type=FastFeatureDetector::TYPE_9_16 ); CV_WRAP virtual void setThreshold(int threshold) = 0; CV_WRAP virtual int getThreshold() const = 0; CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; CV_WRAP virtual bool getNonmaxSuppression() const = 0; CV_WRAP virtual void setType(int type) = 0; CV_WRAP virtual int getType() const = 0; }; /** @overload */ CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, int threshold, bool nonmaxSuppression=true ); /** @brief Detects corners using the AGAST algorithm @param image grayscale image where keypoints (corners) are detected. @param keypoints keypoints detected on the image. @param threshold threshold on difference between intensity of the central pixel and pixels of a circle around this pixel. @param nonmaxSuppression if true, non-maximum suppression is applied to detected corners (keypoints). @param type one of the four neighborhoods as defined in the paper: AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d, AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16 For non-Intel platforms, there is a tree optimised variant of AGAST with same numerical results. The 32-bit binary tree tables were generated automatically from original code using perl script. The perl script and examples of tree generation are placed in features2d/doc folder. Detects corners using the AGAST algorithm by @cite mair2010_agast . */ CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, int threshold, bool nonmaxSuppression, int type ); //! @} features2d_main //! @addtogroup features2d_main //! @{ /** @brief Wrapping class for feature detection using the AGAST method. : */ class CV_EXPORTS_W AgastFeatureDetector : public Feature2D { public: enum { AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3, THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001, }; CV_WRAP static Ptr create( int threshold=10, bool nonmaxSuppression=true, int type=AgastFeatureDetector::OAST_9_16 ); CV_WRAP virtual void setThreshold(int threshold) = 0; CV_WRAP virtual int getThreshold() const = 0; CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; CV_WRAP virtual bool getNonmaxSuppression() const = 0; CV_WRAP virtual void setType(int type) = 0; CV_WRAP virtual int getType() const = 0; }; /** @brief Wrapping class for feature detection using the goodFeaturesToTrack function. : */ class CV_EXPORTS_W GFTTDetector : public Feature2D { public: CV_WRAP static Ptr create( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; CV_WRAP virtual int getMaxFeatures() const = 0; CV_WRAP virtual void setQualityLevel(double qlevel) = 0; CV_WRAP virtual double getQualityLevel() const = 0; CV_WRAP virtual void setMinDistance(double minDistance) = 0; CV_WRAP virtual double getMinDistance() const = 0; CV_WRAP virtual void setBlockSize(int blockSize) = 0; CV_WRAP virtual int getBlockSize() const = 0; CV_WRAP virtual void setHarrisDetector(bool val) = 0; CV_WRAP virtual bool getHarrisDetector() const = 0; CV_WRAP virtual void setK(double k) = 0; CV_WRAP virtual double getK() const = 0; }; /** @brief Class for extracting blobs from an image. : The class implements a simple algorithm for extracting blobs from an image: 1. Convert the source image to binary images by applying thresholding with several thresholds from minThreshold (inclusive) to maxThreshold (exclusive) with distance thresholdStep between neighboring thresholds. 2. Extract connected components from every binary image by findContours and calculate their centers. 3. Group centers from several binary images by their coordinates. Close centers form one group that corresponds to one blob, which is controlled by the minDistBetweenBlobs parameter. 4. From the groups, estimate final centers of blobs and their radiuses and return as locations and sizes of keypoints. This class performs several filtrations of returned blobs. You should set filterBy\* to true/false to turn on/off corresponding filtration. Available filtrations: - **By color**. This filter compares the intensity of a binary image at the center of a blob to blobColor. If they differ, the blob is filtered out. Use blobColor = 0 to extract dark blobs and blobColor = 255 to extract light blobs. - **By area**. Extracted blobs have an area between minArea (inclusive) and maxArea (exclusive). - **By circularity**. Extracted blobs have circularity (\f$\frac{4*\pi*Area}{perimeter * perimeter}\f$) between minCircularity (inclusive) and maxCircularity (exclusive). - **By ratio of the minimum inertia to maximum inertia**. Extracted blobs have this ratio between minInertiaRatio (inclusive) and maxInertiaRatio (exclusive). - **By convexity**. Extracted blobs have convexity (area / area of blob convex hull) between minConvexity (inclusive) and maxConvexity (exclusive). Default values of parameters are tuned to extract dark circular blobs. */ class CV_EXPORTS_W SimpleBlobDetector : public Feature2D { public: struct CV_EXPORTS_W_SIMPLE Params { CV_WRAP Params(); CV_PROP_RW float thresholdStep; CV_PROP_RW float minThreshold; CV_PROP_RW float maxThreshold; CV_PROP_RW size_t minRepeatability; CV_PROP_RW float minDistBetweenBlobs; CV_PROP_RW bool filterByColor; CV_PROP_RW uchar blobColor; CV_PROP_RW bool filterByArea; CV_PROP_RW float minArea, maxArea; CV_PROP_RW bool filterByCircularity; CV_PROP_RW float minCircularity, maxCircularity; CV_PROP_RW bool filterByInertia; CV_PROP_RW float minInertiaRatio, maxInertiaRatio; CV_PROP_RW bool filterByConvexity; CV_PROP_RW float minConvexity, maxConvexity; void read( const FileNode& fn ); void write( FileStorage& fs ) const; }; CV_WRAP static Ptr create(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params()); }; //! @} features2d_main //! @addtogroup features2d_main //! @{ /** @brief Class implementing the KAZE keypoint detector and descriptor extractor, described in @cite ABD12 . @note AKAZE descriptor can only be used with KAZE or AKAZE keypoints .. [ABD12] KAZE Features. Pablo F. Alcantarilla, Adrien Bartoli and Andrew J. Davison. In European Conference on Computer Vision (ECCV), Fiorenze, Italy, October 2012. */ class CV_EXPORTS_W KAZE : public Feature2D { public: enum { DIFF_PM_G1 = 0, DIFF_PM_G2 = 1, DIFF_WEICKERT = 2, DIFF_CHARBONNIER = 3 }; /** @brief The KAZE constructor @param extended Set to enable extraction of extended (128-byte) descriptor. @param upright Set to enable use of upright descriptors (non rotation-invariant). @param threshold Detector response threshold to accept point @param nOctaves Maximum octave evolution of the image @param nOctaveLayers Default number of sublevels per scale level @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or DIFF_CHARBONNIER */ CV_WRAP static Ptr create(bool extended=false, bool upright=false, float threshold = 0.001f, int nOctaves = 4, int nOctaveLayers = 4, int diffusivity = KAZE::DIFF_PM_G2); CV_WRAP virtual void setExtended(bool extended) = 0; CV_WRAP virtual bool getExtended() const = 0; CV_WRAP virtual void setUpright(bool upright) = 0; CV_WRAP virtual bool getUpright() const = 0; CV_WRAP virtual void setThreshold(double threshold) = 0; CV_WRAP virtual double getThreshold() const = 0; CV_WRAP virtual void setNOctaves(int octaves) = 0; CV_WRAP virtual int getNOctaves() const = 0; CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; CV_WRAP virtual int getNOctaveLayers() const = 0; CV_WRAP virtual void setDiffusivity(int diff) = 0; CV_WRAP virtual int getDiffusivity() const = 0; }; /** @brief Class implementing the AKAZE keypoint detector and descriptor extractor, described in @cite ANB13 . : @note AKAZE descriptors can only be used with KAZE or AKAZE keypoints. Try to avoid using *extract* and *detect* instead of *operator()* due to performance reasons. .. [ANB13] Fast Explicit Diffusion for Accelerated Features in Nonlinear Scale Spaces. Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. In British Machine Vision Conference (BMVC), Bristol, UK, September 2013. */ class CV_EXPORTS_W AKAZE : public Feature2D { public: // AKAZE descriptor type enum { DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation DESCRIPTOR_KAZE = 3, DESCRIPTOR_MLDB_UPRIGHT = 4, ///< Upright descriptors, not invariant to rotation DESCRIPTOR_MLDB = 5 }; /** @brief The AKAZE constructor @param descriptor_type Type of the extracted descriptor: DESCRIPTOR_KAZE, DESCRIPTOR_KAZE_UPRIGHT, DESCRIPTOR_MLDB or DESCRIPTOR_MLDB_UPRIGHT. @param descriptor_size Size of the descriptor in bits. 0 -\> Full size @param descriptor_channels Number of channels in the descriptor (1, 2, 3) @param threshold Detector response threshold to accept point @param nOctaves Maximum octave evolution of the image @param nOctaveLayers Default number of sublevels per scale level @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or DIFF_CHARBONNIER */ CV_WRAP static Ptr create(int descriptor_type=AKAZE::DESCRIPTOR_MLDB, int descriptor_size = 0, int descriptor_channels = 3, float threshold = 0.001f, int nOctaves = 4, int nOctaveLayers = 4, int diffusivity = KAZE::DIFF_PM_G2); CV_WRAP virtual void setDescriptorType(int dtype) = 0; CV_WRAP virtual int getDescriptorType() const = 0; CV_WRAP virtual void setDescriptorSize(int dsize) = 0; CV_WRAP virtual int getDescriptorSize() const = 0; CV_WRAP virtual void setDescriptorChannels(int dch) = 0; CV_WRAP virtual int getDescriptorChannels() const = 0; CV_WRAP virtual void setThreshold(double threshold) = 0; CV_WRAP virtual double getThreshold() const = 0; CV_WRAP virtual void setNOctaves(int octaves) = 0; CV_WRAP virtual int getNOctaves() const = 0; CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; CV_WRAP virtual int getNOctaveLayers() const = 0; CV_WRAP virtual void setDiffusivity(int diff) = 0; CV_WRAP virtual int getDiffusivity() const = 0; }; //! @} features2d_main /****************************************************************************************\ * Distance * \****************************************************************************************/ template struct CV_EXPORTS Accumulator { typedef T Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; /* * Squared Euclidean distance functor */ template struct CV_EXPORTS SL2 { enum { normType = NORM_L2SQR }; typedef T ValueType; typedef typename Accumulator::Type ResultType; ResultType operator()( const T* a, const T* b, int size ) const { return normL2Sqr(a, b, size); } }; /* * Euclidean distance functor */ template struct CV_EXPORTS L2 { enum { normType = NORM_L2 }; typedef T ValueType; typedef typename Accumulator::Type ResultType; ResultType operator()( const T* a, const T* b, int size ) const { return (ResultType)std::sqrt((double)normL2Sqr(a, b, size)); } }; /* * Manhattan distance (city block distance) functor */ template struct CV_EXPORTS L1 { enum { normType = NORM_L1 }; typedef T ValueType; typedef typename Accumulator::Type ResultType; ResultType operator()( const T* a, const T* b, int size ) const { return normL1(a, b, size); } }; /****************************************************************************************\ * DescriptorMatcher * \****************************************************************************************/ //! @addtogroup features2d_match //! @{ /** @brief Abstract base class for matching keypoint descriptors. It has two groups of match methods: for matching descriptors of an image with another image or with an image set. */ class CV_EXPORTS_W DescriptorMatcher : public Algorithm { public: virtual ~DescriptorMatcher(); /** @brief Adds descriptors to train a CPU(trainDescCollectionis) or GPU(utrainDescCollectionis) descriptor collection. If the collection is not empty, the new descriptors are added to existing train descriptors. @param descriptors Descriptors to add. Each descriptors[i] is a set of descriptors from the same train image. */ CV_WRAP virtual void add( InputArrayOfArrays descriptors ); /** @brief Returns a constant link to the train descriptor collection trainDescCollection . */ CV_WRAP const std::vector& getTrainDescriptors() const; /** @brief Clears the train descriptor collections. */ CV_WRAP virtual void clear(); /** @brief Returns true if there are no train descriptors in the both collections. */ CV_WRAP virtual bool empty() const; /** @brief Returns true if the descriptor matcher supports masking permissible matches. */ CV_WRAP virtual bool isMaskSupported() const = 0; /** @brief Trains a descriptor matcher Trains a descriptor matcher (for example, the flann index). In all methods to match, the method train() is run every time before matching. Some descriptor matchers (for example, BruteForceMatcher) have an empty implementation of this method. Other matchers really train their inner structures (for example, FlannBasedMatcher trains flann::Index ). */ CV_WRAP virtual void train(); /** @brief Finds the best match for each descriptor from a query set. @param queryDescriptors Query set of descriptors. @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors collection stored in the class object. @param matches Matches. If a query descriptor is masked out in mask , no match is added for this descriptor. So, matches size may be smaller than the query descriptors count. @param mask Mask specifying permissible matches between an input query and train matrices of descriptors. In the first variant of this method, the train descriptors are passed as an input argument. In the second variant of the method, train descriptors collection that was set by DescriptorMatcher::add is used. Optional mask (or masks) can be passed to specify which query and training descriptors can be matched. Namely, queryDescriptors[i] can be matched with trainDescriptors[j] only if mask.at\(i,j) is non-zero. */ CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors, CV_OUT std::vector& matches, InputArray mask=noArray() ) const; /** @brief Finds the k best matches for each descriptor from a query set. @param queryDescriptors Query set of descriptors. @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors collection stored in the class object. @param mask Mask specifying permissible matches between an input query and train matrices of descriptors. @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. @param k Count of best matches found per each query descriptor or less if a query descriptor has less than k possible matches in total. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, the matches vector does not contain matches for fully masked-out query descriptors. These extended variants of DescriptorMatcher::match methods find several best matches for each query descriptor. The matches are returned in the distance increasing order. See DescriptorMatcher::match for the details about query and train descriptors. */ CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors, CV_OUT std::vector >& matches, int k, InputArray mask=noArray(), bool compactResult=false ) const; /** @brief For each query descriptor, finds the training descriptors not farther than the specified distance. @param queryDescriptors Query set of descriptors. @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors collection stored in the class object. @param matches Found matches. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, the matches vector does not contain matches for fully masked-out query descriptors. @param maxDistance Threshold for the distance between matched descriptors. Distance means here metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured in Pixels)! @param mask Mask specifying permissible matches between an input query and train matrices of descriptors. For each query descriptor, the methods find such training descriptors that the distance between the query descriptor and the training descriptor is equal or smaller than maxDistance. Found matches are returned in the distance increasing order. */ void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors, std::vector >& matches, float maxDistance, InputArray mask=noArray(), bool compactResult=false ) const; /** @overload @param queryDescriptors Query set of descriptors. @param matches Matches. If a query descriptor is masked out in mask , no match is added for this descriptor. So, matches size may be smaller than the query descriptors count. @param masks Set of masks. Each masks[i] specifies permissible matches between the input query descriptors and stored train descriptors from the i-th image trainDescCollection[i]. */ CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector& matches, InputArrayOfArrays masks=noArray() ); /** @overload @param queryDescriptors Query set of descriptors. @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. @param k Count of best matches found per each query descriptor or less if a query descriptor has less than k possible matches in total. @param masks Set of masks. Each masks[i] specifies permissible matches between the input query descriptors and stored train descriptors from the i-th image trainDescCollection[i]. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, the matches vector does not contain matches for fully masked-out query descriptors. */ CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, int k, InputArrayOfArrays masks=noArray(), bool compactResult=false ); /** @overload @param queryDescriptors Query set of descriptors. @param matches Found matches. @param maxDistance Threshold for the distance between matched descriptors. Distance means here metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured in Pixels)! @param masks Set of masks. Each masks[i] specifies permissible matches between the input query descriptors and stored train descriptors from the i-th image trainDescCollection[i]. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, the matches vector does not contain matches for fully masked-out query descriptors. */ void radiusMatch( InputArray queryDescriptors, std::vector >& matches, float maxDistance, InputArrayOfArrays masks=noArray(), bool compactResult=false ); // Reads matcher object from a file node virtual void read( const FileNode& ); // Writes matcher object to a file storage virtual void write( FileStorage& ) const; /** @brief Clones the matcher. @param emptyTrainData If emptyTrainData is false, the method creates a deep copy of the object, that is, copies both parameters and train data. If emptyTrainData is true, the method creates an object copy with the current parameters but with empty train data. */ virtual Ptr clone( bool emptyTrainData=false ) const = 0; /** @brief Creates a descriptor matcher of a given type with the default parameters (using default constructor). @param descriptorMatcherType Descriptor matcher type. Now the following matcher types are supported: - `BruteForce` (it uses L2 ) - `BruteForce-L1` - `BruteForce-Hamming` - `BruteForce-Hamming(2)` - `FlannBased` */ CV_WRAP static Ptr create( const String& descriptorMatcherType ); protected: /** * Class to work with descriptors from several images as with one merged matrix. * It is used e.g. in FlannBasedMatcher. */ class CV_EXPORTS DescriptorCollection { public: DescriptorCollection(); DescriptorCollection( const DescriptorCollection& collection ); virtual ~DescriptorCollection(); // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here. void set( const std::vector& descriptors ); virtual void clear(); const Mat& getDescriptors() const; const Mat getDescriptor( int imgIdx, int localDescIdx ) const; const Mat getDescriptor( int globalDescIdx ) const; void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const; int size() const; protected: Mat mergedDescriptors; std::vector startIdxs; }; //! In fact the matching is implemented only by the following two methods. These methods suppose //! that the class object has been trained already. Public match methods call these methods //! after calling train(). virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx ); static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx ); static Mat clone_op( Mat m ) { return m.clone(); } void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const; //! Collection of descriptors from train images. std::vector trainDescCollection; std::vector utrainDescCollection; }; /** @brief Brute-force descriptor matcher. For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. This descriptor matcher supports masking permissible matches of descriptor sets. */ class CV_EXPORTS_W BFMatcher : public DescriptorMatcher { public: /** @brief Brute-force matcher constructor. @param normType One of NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2. L1 and L2 norms are preferable choices for SIFT and SURF descriptors, NORM_HAMMING should be used with ORB, BRISK and BRIEF, NORM_HAMMING2 should be used with ORB when WTA_K==3 or 4 (see ORB::ORB constructor description). @param crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent pairs. Such technique usually produces best results with minimal number of outliers when there are enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper. */ CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false ); virtual ~BFMatcher() {} virtual bool isMaskSupported() const { return true; } virtual Ptr clone( bool emptyTrainData=false ) const; protected: virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, InputArrayOfArrays masks=noArray(), bool compactResult=false ); virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, InputArrayOfArrays masks=noArray(), bool compactResult=false ); int normType; bool crossCheck; }; /** @brief Flann-based descriptor matcher. This matcher trains flann::Index_ on a train descriptor collection and calls its nearest search methods to find the best matches. So, this matcher may be faster when matching a large train collection than the brute force matcher. FlannBasedMatcher does not support masking permissible matches of descriptor sets because flann::Index does not support this. : */ class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher { public: CV_WRAP FlannBasedMatcher( const Ptr& indexParams=makePtr(), const Ptr& searchParams=makePtr() ); virtual void add( InputArrayOfArrays descriptors ); virtual void clear(); // Reads matcher object from a file node virtual void read( const FileNode& ); // Writes matcher object to a file storage virtual void write( FileStorage& ) const; virtual void train(); virtual bool isMaskSupported() const; virtual Ptr clone( bool emptyTrainData=false ) const; protected: static void convertToDMatches( const DescriptorCollection& descriptors, const Mat& indices, const Mat& distances, std::vector >& matches ); virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, InputArrayOfArrays masks=noArray(), bool compactResult=false ); virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, InputArrayOfArrays masks=noArray(), bool compactResult=false ); Ptr indexParams; Ptr searchParams; Ptr flannIndex; DescriptorCollection mergedDescriptors; int addedDescCount; }; //! @} features2d_match /****************************************************************************************\ * Drawing functions * \****************************************************************************************/ //! @addtogroup features2d_draw //! @{ struct CV_EXPORTS DrawMatchesFlags { enum{ DEFAULT = 0, //!< Output image matrix will be created (Mat::create), //!< i.e. existing memory of output image may be reused. //!< Two source image, matches and single keypoints will be drawn. //!< For each keypoint only the center point will be drawn (without //!< the circle around keypoint with keypoint size and orientation). DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create). //!< Matches will be drawn on existing content of output image. NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn. DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and //!< orientation will be drawn. }; }; /** @brief Draws keypoints. @param image Source image. @param keypoints Keypoints from the source image. @param outImage Output image. Its content depends on the flags value defining what is drawn in the output image. See possible flags bit values below. @param color Color of keypoints. @param flags Flags setting drawing features. Possible flags bit values are defined by DrawMatchesFlags. See details above in drawMatches . @note For Python API, flags are modified as cv2.DRAW_MATCHES_FLAGS_DEFAULT, cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv2.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG, cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS */ CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector& keypoints, InputOutputArray outImage, const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT ); /** @brief Draws the found matches of keypoints from two images. @param img1 First source image. @param keypoints1 Keypoints from the first source image. @param img2 Second source image. @param keypoints2 Keypoints from the second source image. @param matches1to2 Matches from the first image to the second one, which means that keypoints1[i] has a corresponding point in keypoints2[matches[i]] . @param outImg Output image. Its content depends on the flags value defining what is drawn in the output image. See possible flags bit values below. @param matchColor Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1) , the color is generated randomly. @param singlePointColor Color of single keypoints (circles), which means that keypoints do not have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly. @param matchesMask Mask determining which matches are drawn. If the mask is empty, all matches are drawn. @param flags Flags setting drawing features. Possible flags bit values are defined by DrawMatchesFlags. This function draws matches of keypoints from two images in the output image. Match is a line connecting two keypoints (circles). See cv::DrawMatchesFlags. */ CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, InputArray img2, const std::vector& keypoints2, const std::vector& matches1to2, InputOutputArray outImg, const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), const std::vector& matchesMask=std::vector(), int flags=DrawMatchesFlags::DEFAULT ); /** @overload */ CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector& keypoints1, InputArray img2, const std::vector& keypoints2, const std::vector >& matches1to2, InputOutputArray outImg, const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), const std::vector >& matchesMask=std::vector >(), int flags=DrawMatchesFlags::DEFAULT ); //! @} features2d_draw /****************************************************************************************\ * Functions to evaluate the feature detectors and [generic] descriptor extractors * \****************************************************************************************/ CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2, std::vector* keypoints1, std::vector* keypoints2, float& repeatability, int& correspCount, const Ptr& fdetector=Ptr() ); CV_EXPORTS void computeRecallPrecisionCurve( const std::vector >& matches1to2, const std::vector >& correctMatches1to2Mask, std::vector& recallPrecisionCurve ); CV_EXPORTS float getRecall( const std::vector& recallPrecisionCurve, float l_precision ); CV_EXPORTS int getNearestPoint( const std::vector& recallPrecisionCurve, float l_precision ); /****************************************************************************************\ * Bag of visual words * \****************************************************************************************/ //! @addtogroup features2d_category //! @{ /** @brief Abstract base class for training the *bag of visual words* vocabulary from a set of descriptors. For details, see, for example, *Visual Categorization with Bags of Keypoints* by Gabriella Csurka, Christopher R. Dance, Lixin Fan, Jutta Willamowski, Cedric Bray, 2004. : */ class CV_EXPORTS_W BOWTrainer { public: BOWTrainer(); virtual ~BOWTrainer(); /** @brief Adds descriptors to a training set. @param descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a descriptor. The training set is clustered using clustermethod to construct the vocabulary. */ CV_WRAP void add( const Mat& descriptors ); /** @brief Returns a training set of descriptors. */ CV_WRAP const std::vector& getDescriptors() const; /** @brief Returns the count of all descriptors stored in the training set. */ CV_WRAP int descriptorsCount() const; CV_WRAP virtual void clear(); /** @overload */ CV_WRAP virtual Mat cluster() const = 0; /** @brief Clusters train descriptors. @param descriptors Descriptors to cluster. Each row of the descriptors matrix is a descriptor. Descriptors are not added to the inner train descriptor set. The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first variant of the method, train descriptors stored in the object are clustered. In the second variant, input descriptors are clustered. */ CV_WRAP virtual Mat cluster( const Mat& descriptors ) const = 0; protected: std::vector descriptors; int size; }; /** @brief kmeans -based class to train visual vocabulary using the *bag of visual words* approach. : */ class CV_EXPORTS_W BOWKMeansTrainer : public BOWTrainer { public: /** @brief The constructor. @see cv::kmeans */ CV_WRAP BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), int attempts=3, int flags=KMEANS_PP_CENTERS ); virtual ~BOWKMeansTrainer(); // Returns trained vocabulary (i.e. cluster centers). CV_WRAP virtual Mat cluster() const; CV_WRAP virtual Mat cluster( const Mat& descriptors ) const; protected: int clusterCount; TermCriteria termcrit; int attempts; int flags; }; /** @brief Class to compute an image descriptor using the *bag of visual words*. Such a computation consists of the following steps: 1. Compute descriptors for a given image and its keypoints set. 2. Find the nearest visual words from the vocabulary for each keypoint descriptor. 3. Compute the bag-of-words image descriptor as is a normalized histogram of vocabulary words encountered in the image. The i-th bin of the histogram is a frequency of i-th word of the vocabulary in the given image. */ class CV_EXPORTS_W BOWImgDescriptorExtractor { public: /** @brief The constructor. @param dextractor Descriptor extractor that is used to compute descriptors for an input image and its keypoints. @param dmatcher Descriptor matcher that is used to find the nearest word of the trained vocabulary for each keypoint descriptor of the image. */ CV_WRAP BOWImgDescriptorExtractor( const Ptr& dextractor, const Ptr& dmatcher ); /** @overload */ BOWImgDescriptorExtractor( const Ptr& dmatcher ); virtual ~BOWImgDescriptorExtractor(); /** @brief Sets a visual vocabulary. @param vocabulary Vocabulary (can be trained using the inheritor of BOWTrainer ). Each row of the vocabulary is a visual word (cluster center). */ CV_WRAP void setVocabulary( const Mat& vocabulary ); /** @brief Returns the set vocabulary. */ CV_WRAP const Mat& getVocabulary() const; /** @brief Computes an image descriptor using the set visual vocabulary. @param image Image, for which the descriptor is computed. @param keypoints Keypoints detected in the input image. @param imgDescriptor Computed output image descriptor. @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) returned if it is non-zero. @param descriptors Descriptors of the image keypoints that are returned if they are non-zero. */ void compute( InputArray image, std::vector& keypoints, OutputArray imgDescriptor, std::vector >* pointIdxsOfClusters=0, Mat* descriptors=0 ); /** @overload @param keypointDescriptors Computed descriptors to match with vocabulary. @param imgDescriptor Computed output image descriptor. @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) returned if it is non-zero. */ void compute( InputArray keypointDescriptors, OutputArray imgDescriptor, std::vector >* pointIdxsOfClusters=0 ); // compute() is not constant because DescriptorMatcher::match is not constant CV_WRAP_AS(compute) void compute2( const Mat& image, std::vector& keypoints, CV_OUT Mat& imgDescriptor ) { compute(image,keypoints,imgDescriptor); } /** @brief Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0. */ CV_WRAP int descriptorSize() const; /** @brief Returns an image descriptor type. */ CV_WRAP int descriptorType() const; protected: Mat vocabulary; Ptr dextractor; Ptr dmatcher; }; //! @} features2d_category //! @} features2d } /* namespace cv */ #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/all_indices.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_ALL_INDICES_H_ #define OPENCV_FLANN_ALL_INDICES_H_ #include "general.h" #include "nn_index.h" #include "kdtree_index.h" #include "kdtree_single_index.h" #include "kmeans_index.h" #include "composite_index.h" #include "linear_index.h" #include "hierarchical_clustering_index.h" #include "lsh_index.h" #include "autotuned_index.h" namespace cvflann { template struct index_creator { static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) { flann_algorithm_t index_type = get_param(params, "algorithm"); NNIndex* nnIndex; switch (index_type) { case FLANN_INDEX_LINEAR: nnIndex = new LinearIndex(dataset, params, distance); break; case FLANN_INDEX_KDTREE_SINGLE: nnIndex = new KDTreeSingleIndex(dataset, params, distance); break; case FLANN_INDEX_KDTREE: nnIndex = new KDTreeIndex(dataset, params, distance); break; case FLANN_INDEX_KMEANS: nnIndex = new KMeansIndex(dataset, params, distance); break; case FLANN_INDEX_COMPOSITE: nnIndex = new CompositeIndex(dataset, params, distance); break; case FLANN_INDEX_AUTOTUNED: nnIndex = new AutotunedIndex(dataset, params, distance); break; case FLANN_INDEX_HIERARCHICAL: nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); break; case FLANN_INDEX_LSH: nnIndex = new LshIndex(dataset, params, distance); break; default: throw FLANNException("Unknown index type"); } return nnIndex; } }; template struct index_creator { static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) { flann_algorithm_t index_type = get_param(params, "algorithm"); NNIndex* nnIndex; switch (index_type) { case FLANN_INDEX_LINEAR: nnIndex = new LinearIndex(dataset, params, distance); break; case FLANN_INDEX_KMEANS: nnIndex = new KMeansIndex(dataset, params, distance); break; case FLANN_INDEX_HIERARCHICAL: nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); break; case FLANN_INDEX_LSH: nnIndex = new LshIndex(dataset, params, distance); break; default: throw FLANNException("Unknown index type"); } return nnIndex; } }; template struct index_creator { static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) { flann_algorithm_t index_type = get_param(params, "algorithm"); NNIndex* nnIndex; switch (index_type) { case FLANN_INDEX_LINEAR: nnIndex = new LinearIndex(dataset, params, distance); break; case FLANN_INDEX_HIERARCHICAL: nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); break; case FLANN_INDEX_LSH: nnIndex = new LshIndex(dataset, params, distance); break; default: throw FLANNException("Unknown index type"); } return nnIndex; } }; template NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance) { return index_creator::create(dataset, params,distance); } } #endif /* OPENCV_FLANN_ALL_INDICES_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/allocator.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_ALLOCATOR_H_ #define OPENCV_FLANN_ALLOCATOR_H_ #include #include namespace cvflann { /** * Allocates (using C's malloc) a generic type T. * * Params: * count = number of instances to allocate. * Returns: pointer (of type T*) to memory buffer */ template T* allocate(size_t count = 1) { T* mem = (T*) ::malloc(sizeof(T)*count); return mem; } /** * Pooled storage allocator * * The following routines allow for the efficient allocation of storage in * small chunks from a specified pool. Rather than allowing each structure * to be freed individually, an entire pool of storage is freed at once. * This method has two advantages over just using malloc() and free(). First, * it is far more efficient for allocating small objects, as there is * no overhead for remembering all the information needed to free each * object or consolidating fragmented memory. Second, the decision about * how long to keep an object is made at the time of allocation, and there * is no need to track down all the objects to free them. * */ const size_t WORDSIZE=16; const size_t BLOCKSIZE=8192; class PooledAllocator { /* We maintain memory alignment to word boundaries by requiring that all allocations be in multiples of the machine wordsize. */ /* Size of machine word in bytes. Must be power of 2. */ /* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */ int remaining; /* Number of bytes left in current block of storage. */ void* base; /* Pointer to base of current block of storage. */ void* loc; /* Current location in block to next allocate memory. */ int blocksize; public: int usedMemory; int wastedMemory; /** Default constructor. Initializes a new pool. */ PooledAllocator(int blockSize = BLOCKSIZE) { blocksize = blockSize; remaining = 0; base = NULL; usedMemory = 0; wastedMemory = 0; } /** * Destructor. Frees all the memory allocated in this pool. */ ~PooledAllocator() { void* prev; while (base != NULL) { prev = *((void**) base); /* Get pointer to prev block. */ ::free(base); base = prev; } } /** * Returns a pointer to a piece of new memory of the given size in bytes * allocated from the pool. */ void* allocateMemory(int size) { int blockSize; /* Round size up to a multiple of wordsize. The following expression only works for WORDSIZE that is a power of 2, by masking last bits of incremented size to zero. */ size = (size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); /* Check whether a new block must be allocated. Note that the first word of a block is reserved for a pointer to the previous block. */ if (size > remaining) { wastedMemory += remaining; /* Allocate new storage. */ blockSize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE; // use the standard C malloc to allocate memory void* m = ::malloc(blockSize); if (!m) { fprintf(stderr,"Failed to allocate memory.\n"); return NULL; } /* Fill first word of new block with pointer to previous block. */ ((void**) m)[0] = base; base = m; int shift = 0; //int shift = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); remaining = blockSize - sizeof(void*) - shift; loc = ((char*)m + sizeof(void*) + shift); } void* rloc = loc; loc = (char*)loc + size; remaining -= size; usedMemory += size; return rloc; } /** * Allocates (using this pool) a generic type T. * * Params: * count = number of instances to allocate. * Returns: pointer (of type T*) to memory buffer */ template T* allocate(size_t count = 1) { T* mem = (T*) this->allocateMemory((int)(sizeof(T)*count)); return mem; } }; } #endif //OPENCV_FLANN_ALLOCATOR_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/any.h ================================================ #ifndef OPENCV_FLANN_ANY_H_ #define OPENCV_FLANN_ANY_H_ /* * (C) Copyright Christopher Diggins 2005-2011 * (C) Copyright Pablo Aguilar 2005 * (C) Copyright Kevlin Henney 2001 * * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt * * Adapted for FLANN by Marius Muja */ #include "defines.h" #include #include #include namespace cvflann { namespace anyimpl { struct bad_any_cast { }; struct empty_any { }; inline std::ostream& operator <<(std::ostream& out, const empty_any&) { out << "[empty_any]"; return out; } struct base_any_policy { virtual void static_delete(void** x) = 0; virtual void copy_from_value(void const* src, void** dest) = 0; virtual void clone(void* const* src, void** dest) = 0; virtual void move(void* const* src, void** dest) = 0; virtual void* get_value(void** src) = 0; virtual const void* get_value(void* const * src) = 0; virtual ::size_t get_size() = 0; virtual const std::type_info& type() = 0; virtual void print(std::ostream& out, void* const* src) = 0; virtual ~base_any_policy() {} }; template struct typed_base_any_policy : base_any_policy { virtual ::size_t get_size() { return sizeof(T); } virtual const std::type_info& type() { return typeid(T); } }; template struct small_any_policy : typed_base_any_policy { virtual void static_delete(void**) { } virtual void copy_from_value(void const* src, void** dest) { new (dest) T(* reinterpret_cast(src)); } virtual void clone(void* const* src, void** dest) { *dest = *src; } virtual void move(void* const* src, void** dest) { *dest = *src; } virtual void* get_value(void** src) { return reinterpret_cast(src); } virtual const void* get_value(void* const * src) { return reinterpret_cast(src); } virtual void print(std::ostream& out, void* const* src) { out << *reinterpret_cast(src); } }; template struct big_any_policy : typed_base_any_policy { virtual void static_delete(void** x) { if (* x) delete (* reinterpret_cast(x)); *x = NULL; } virtual void copy_from_value(void const* src, void** dest) { *dest = new T(*reinterpret_cast(src)); } virtual void clone(void* const* src, void** dest) { *dest = new T(**reinterpret_cast(src)); } virtual void move(void* const* src, void** dest) { (*reinterpret_cast(dest))->~T(); **reinterpret_cast(dest) = **reinterpret_cast(src); } virtual void* get_value(void** src) { return *src; } virtual const void* get_value(void* const * src) { return *src; } virtual void print(std::ostream& out, void* const* src) { out << *reinterpret_cast(*src); } }; template<> inline void big_any_policy::print(std::ostream& out, void* const* src) { out << int(*reinterpret_cast(*src)); } template<> inline void big_any_policy::print(std::ostream& out, void* const* src) { out << int(*reinterpret_cast(*src)); } template<> inline void big_any_policy::print(std::ostream& out, void* const* src) { out << (*reinterpret_cast(*src)).c_str(); } template struct choose_policy { typedef big_any_policy type; }; template struct choose_policy { typedef small_any_policy type; }; struct any; /// Choosing the policy for an any type is illegal, but should never happen. /// This is designed to throw a compiler error. template<> struct choose_policy { typedef void type; }; /// Specializations for small types. #define SMALL_POLICY(TYPE) \ template<> \ struct choose_policy { typedef small_any_policy type; \ } SMALL_POLICY(signed char); SMALL_POLICY(unsigned char); SMALL_POLICY(signed short); SMALL_POLICY(unsigned short); SMALL_POLICY(signed int); SMALL_POLICY(unsigned int); SMALL_POLICY(signed long); SMALL_POLICY(unsigned long); SMALL_POLICY(float); SMALL_POLICY(bool); #undef SMALL_POLICY template class SinglePolicy { SinglePolicy(); SinglePolicy(const SinglePolicy& other); SinglePolicy& operator=(const SinglePolicy& other); public: static base_any_policy* get_policy(); private: static typename choose_policy::type policy; }; template typename choose_policy::type SinglePolicy::policy; /// This function will return a different policy for each type. template inline base_any_policy* SinglePolicy::get_policy() { return &policy; } } // namespace anyimpl struct any { private: // fields anyimpl::base_any_policy* policy; void* object; public: /// Initializing constructor. template any(const T& x) : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) { assign(x); } /// Empty constructor. any() : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) { } /// Special initializing constructor for string literals. any(const char* x) : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) { assign(x); } /// Copy constructor. any(const any& x) : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) { assign(x); } /// Destructor. ~any() { policy->static_delete(&object); } /// Assignment function from another any. any& assign(const any& x) { reset(); policy = x.policy; policy->clone(&x.object, &object); return *this; } /// Assignment function. template any& assign(const T& x) { reset(); policy = anyimpl::SinglePolicy::get_policy(); policy->copy_from_value(&x, &object); return *this; } /// Assignment operator. template any& operator=(const T& x) { return assign(x); } /// Assignment operator, specialed for literal strings. /// They have types like const char [6] which don't work as expected. any& operator=(const char* x) { return assign(x); } /// Utility functions any& swap(any& x) { std::swap(policy, x.policy); std::swap(object, x.object); return *this; } /// Cast operator. You can only cast to the original type. template T& cast() { if (policy->type() != typeid(T)) throw anyimpl::bad_any_cast(); T* r = reinterpret_cast(policy->get_value(&object)); return *r; } /// Cast operator. You can only cast to the original type. template const T& cast() const { if (policy->type() != typeid(T)) throw anyimpl::bad_any_cast(); const T* r = reinterpret_cast(policy->get_value(&object)); return *r; } /// Returns true if the any contains no value. bool empty() const { return policy->type() == typeid(anyimpl::empty_any); } /// Frees any allocated memory, and sets the value to NULL. void reset() { policy->static_delete(&object); policy = anyimpl::SinglePolicy::get_policy(); } /// Returns true if the two types are the same. bool compatible(const any& x) const { return policy->type() == x.policy->type(); } /// Returns if the type is compatible with the policy template bool has_type() { return policy->type() == typeid(T); } const std::type_info& type() const { return policy->type(); } friend std::ostream& operator <<(std::ostream& out, const any& any_val); }; inline std::ostream& operator <<(std::ostream& out, const any& any_val) { any_val.policy->print(out,&any_val.object); return out; } } #endif // OPENCV_FLANN_ANY_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/autotuned_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_AUTOTUNED_INDEX_H_ #define OPENCV_FLANN_AUTOTUNED_INDEX_H_ #include "general.h" #include "nn_index.h" #include "ground_truth.h" #include "index_testing.h" #include "sampling.h" #include "kdtree_index.h" #include "kdtree_single_index.h" #include "kmeans_index.h" #include "composite_index.h" #include "linear_index.h" #include "logger.h" namespace cvflann { template NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance); struct AutotunedIndexParams : public IndexParams { AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1) { (*this)["algorithm"] = FLANN_INDEX_AUTOTUNED; // precision desired (used for autotuning, -1 otherwise) (*this)["target_precision"] = target_precision; // build tree time weighting factor (*this)["build_weight"] = build_weight; // index memory weighting factor (*this)["memory_weight"] = memory_weight; // what fraction of the dataset to use for autotuning (*this)["sample_fraction"] = sample_fraction; } }; template class AutotunedIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; AutotunedIndex(const Matrix& inputData, const IndexParams& params = AutotunedIndexParams(), Distance d = Distance()) : dataset_(inputData), distance_(d) { target_precision_ = get_param(params, "target_precision",0.8f); build_weight_ = get_param(params,"build_weight", 0.01f); memory_weight_ = get_param(params, "memory_weight", 0.0f); sample_fraction_ = get_param(params,"sample_fraction", 0.1f); bestIndex_ = NULL; } AutotunedIndex(const AutotunedIndex&); AutotunedIndex& operator=(const AutotunedIndex&); virtual ~AutotunedIndex() { if (bestIndex_ != NULL) { delete bestIndex_; bestIndex_ = NULL; } } /** * Method responsible with building the index. */ virtual void buildIndex() { std::ostringstream stream; bestParams_ = estimateBuildParams(); print_params(bestParams_, stream); Logger::info("----------------------------------------------------\n"); Logger::info("Autotuned parameters:\n"); Logger::info("%s", stream.str().c_str()); Logger::info("----------------------------------------------------\n"); bestIndex_ = create_index_by_type(dataset_, bestParams_, distance_); bestIndex_->buildIndex(); speedup_ = estimateSearchParams(bestSearchParams_); stream.str(std::string()); print_params(bestSearchParams_, stream); Logger::info("----------------------------------------------------\n"); Logger::info("Search parameters:\n"); Logger::info("%s", stream.str().c_str()); Logger::info("----------------------------------------------------\n"); } /** * Saves the index to a stream */ virtual void saveIndex(FILE* stream) { save_value(stream, (int)bestIndex_->getType()); bestIndex_->saveIndex(stream); save_value(stream, get_param(bestSearchParams_, "checks")); } /** * Loads the index from a stream */ virtual void loadIndex(FILE* stream) { int index_type; load_value(stream, index_type); IndexParams params; params["algorithm"] = (flann_algorithm_t)index_type; bestIndex_ = create_index_by_type(dataset_, params, distance_); bestIndex_->loadIndex(stream); int checks; load_value(stream, checks); bestSearchParams_["checks"] = checks; } /** * Method that searches for nearest-neighbors */ virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) { int checks = get_param(searchParams,"checks",FLANN_CHECKS_AUTOTUNED); if (checks == FLANN_CHECKS_AUTOTUNED) { bestIndex_->findNeighbors(result, vec, bestSearchParams_); } else { bestIndex_->findNeighbors(result, vec, searchParams); } } IndexParams getParameters() const { return bestIndex_->getParameters(); } SearchParams getSearchParameters() const { return bestSearchParams_; } float getSpeedup() const { return speedup_; } /** * Number of features in this index. */ virtual size_t size() const { return bestIndex_->size(); } /** * The length of each vector in this index. */ virtual size_t veclen() const { return bestIndex_->veclen(); } /** * The amount of memory (in bytes) this index uses. */ virtual int usedMemory() const { return bestIndex_->usedMemory(); } /** * Algorithm name */ virtual flann_algorithm_t getType() const { return FLANN_INDEX_AUTOTUNED; } private: struct CostData { float searchTimeCost; float buildTimeCost; float memoryCost; float totalCost; IndexParams params; }; void evaluate_kmeans(CostData& cost) { StartStopTimer t; int checks; const int nn = 1; Logger::info("KMeansTree using params: max_iterations=%d, branching=%d\n", get_param(cost.params,"iterations"), get_param(cost.params,"branching")); KMeansIndex kmeans(sampledDataset_, cost.params, distance_); // measure index build time t.start(); kmeans.buildIndex(); t.stop(); float buildTime = (float)t.value; // measure search time float searchTime = test_index_precision(kmeans, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); cost.memoryCost = (kmeans.usedMemory() + datasetMemory) / datasetMemory; cost.searchTimeCost = searchTime; cost.buildTimeCost = buildTime; Logger::info("KMeansTree buildTime=%g, searchTime=%g, build_weight=%g\n", buildTime, searchTime, build_weight_); } void evaluate_kdtree(CostData& cost) { StartStopTimer t; int checks; const int nn = 1; Logger::info("KDTree using params: trees=%d\n", get_param(cost.params,"trees")); KDTreeIndex kdtree(sampledDataset_, cost.params, distance_); t.start(); kdtree.buildIndex(); t.stop(); float buildTime = (float)t.value; //measure search time float searchTime = test_index_precision(kdtree, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); cost.memoryCost = (kdtree.usedMemory() + datasetMemory) / datasetMemory; cost.searchTimeCost = searchTime; cost.buildTimeCost = buildTime; Logger::info("KDTree buildTime=%g, searchTime=%g\n", buildTime, searchTime); } // struct KMeansSimpleDownhillFunctor { // // Autotune& autotuner; // KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} // // float operator()(int* params) { // // float maxFloat = numeric_limits::max(); // // if (params[0]<2) return maxFloat; // if (params[1]<0) return maxFloat; // // CostData c; // c.params["algorithm"] = KMEANS; // c.params["centers-init"] = CENTERS_RANDOM; // c.params["branching"] = params[0]; // c.params["max-iterations"] = params[1]; // // autotuner.evaluate_kmeans(c); // // return c.timeCost; // // } // }; // // struct KDTreeSimpleDownhillFunctor { // // Autotune& autotuner; // KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} // // float operator()(int* params) { // float maxFloat = numeric_limits::max(); // // if (params[0]<1) return maxFloat; // // CostData c; // c.params["algorithm"] = KDTREE; // c.params["trees"] = params[0]; // // autotuner.evaluate_kdtree(c); // // return c.timeCost; // // } // }; void optimizeKMeans(std::vector& costs) { Logger::info("KMEANS, Step 1: Exploring parameter space\n"); // explore kmeans parameters space using combinations of the parameters below int maxIterations[] = { 1, 5, 10, 15 }; int branchingFactors[] = { 16, 32, 64, 128, 256 }; int kmeansParamSpaceSize = FLANN_ARRAY_LEN(maxIterations) * FLANN_ARRAY_LEN(branchingFactors); costs.reserve(costs.size() + kmeansParamSpaceSize); // evaluate kmeans for all parameter combinations for (size_t i = 0; i < FLANN_ARRAY_LEN(maxIterations); ++i) { for (size_t j = 0; j < FLANN_ARRAY_LEN(branchingFactors); ++j) { CostData cost; cost.params["algorithm"] = FLANN_INDEX_KMEANS; cost.params["centers_init"] = FLANN_CENTERS_RANDOM; cost.params["iterations"] = maxIterations[i]; cost.params["branching"] = branchingFactors[j]; evaluate_kmeans(cost); costs.push_back(cost); } } // Logger::info("KMEANS, Step 2: simplex-downhill optimization\n"); // // const int n = 2; // // choose initial simplex points as the best parameters so far // int kmeansNMPoints[n*(n+1)]; // float kmeansVals[n+1]; // for (int i=0;i& costs) { Logger::info("KD-TREE, Step 1: Exploring parameter space\n"); // explore kd-tree parameters space using the parameters below int testTrees[] = { 1, 4, 8, 16, 32 }; // evaluate kdtree for all parameter combinations for (size_t i = 0; i < FLANN_ARRAY_LEN(testTrees); ++i) { CostData cost; cost.params["algorithm"] = FLANN_INDEX_KDTREE; cost.params["trees"] = testTrees[i]; evaluate_kdtree(cost); costs.push_back(cost); } // Logger::info("KD-TREE, Step 2: simplex-downhill optimization\n"); // // const int n = 1; // // choose initial simplex points as the best parameters so far // int kdtreeNMPoints[n*(n+1)]; // float kdtreeVals[n+1]; // for (int i=0;i costs; int sampleSize = int(sample_fraction_ * dataset_.rows); int testSampleSize = std::min(sampleSize / 10, 1000); Logger::info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d, target precision: %g\n", dataset_.rows, sampleSize, testSampleSize, target_precision_); // For a very small dataset, it makes no sense to build any fancy index, just // use linear search if (testSampleSize < 10) { Logger::info("Choosing linear, dataset too small\n"); return LinearIndexParams(); } // We use a fraction of the original dataset to speedup the autotune algorithm sampledDataset_ = random_sample(dataset_, sampleSize); // We use a cross-validation approach, first we sample a testset from the dataset testDataset_ = random_sample(sampledDataset_, testSampleSize, true); // We compute the ground truth using linear search Logger::info("Computing ground truth... \n"); gt_matches_ = Matrix(new int[testDataset_.rows], testDataset_.rows, 1); StartStopTimer t; t.start(); compute_ground_truth(sampledDataset_, testDataset_, gt_matches_, 0, distance_); t.stop(); CostData linear_cost; linear_cost.searchTimeCost = (float)t.value; linear_cost.buildTimeCost = 0; linear_cost.memoryCost = 0; linear_cost.params["algorithm"] = FLANN_INDEX_LINEAR; costs.push_back(linear_cost); // Start parameter autotune process Logger::info("Autotuning parameters...\n"); optimizeKMeans(costs); optimizeKDTree(costs); float bestTimeCost = costs[0].searchTimeCost; for (size_t i = 0; i < costs.size(); ++i) { float timeCost = costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost; if (timeCost < bestTimeCost) { bestTimeCost = timeCost; } } float bestCost = costs[0].searchTimeCost / bestTimeCost; IndexParams bestParams = costs[0].params; if (bestTimeCost > 0) { for (size_t i = 0; i < costs.size(); ++i) { float crtCost = (costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost) / bestTimeCost + memory_weight_ * costs[i].memoryCost; if (crtCost < bestCost) { bestCost = crtCost; bestParams = costs[i].params; } } } delete[] gt_matches_.data; delete[] testDataset_.data; delete[] sampledDataset_.data; return bestParams; } /** * Estimates the search time parameters needed to get the desired precision. * Precondition: the index is built * Postcondition: the searchParams will have the optimum params set, also the speedup obtained over linear search. */ float estimateSearchParams(SearchParams& searchParams) { const int nn = 1; const size_t SAMPLE_COUNT = 1000; assert(bestIndex_ != NULL); // must have a valid index float speedup = 0; int samples = (int)std::min(dataset_.rows / 10, SAMPLE_COUNT); if (samples > 0) { Matrix testDataset = random_sample(dataset_, samples); Logger::info("Computing ground truth\n"); // we need to compute the ground truth first Matrix gt_matches(new int[testDataset.rows], testDataset.rows, 1); StartStopTimer t; t.start(); compute_ground_truth(dataset_, testDataset, gt_matches, 1, distance_); t.stop(); float linear = (float)t.value; int checks; Logger::info("Estimating number of checks\n"); float searchTime; float cb_index; if (bestIndex_->getType() == FLANN_INDEX_KMEANS) { Logger::info("KMeans algorithm, estimating cluster border factor\n"); KMeansIndex* kmeans = (KMeansIndex*)bestIndex_; float bestSearchTime = -1; float best_cb_index = -1; int best_checks = -1; for (cb_index = 0; cb_index < 1.1f; cb_index += 0.2f) { kmeans->set_cb_index(cb_index); searchTime = test_index_precision(*kmeans, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); if ((searchTime < bestSearchTime) || (bestSearchTime == -1)) { bestSearchTime = searchTime; best_cb_index = cb_index; best_checks = checks; } } searchTime = bestSearchTime; cb_index = best_cb_index; checks = best_checks; kmeans->set_cb_index(best_cb_index); Logger::info("Optimum cb_index: %g\n", cb_index); bestParams_["cb_index"] = cb_index; } else { searchTime = test_index_precision(*bestIndex_, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); } Logger::info("Required number of checks: %d \n", checks); searchParams["checks"] = checks; speedup = linear / searchTime; delete[] gt_matches.data; delete[] testDataset.data; } return speedup; } private: NNIndex* bestIndex_; IndexParams bestParams_; SearchParams bestSearchParams_; Matrix sampledDataset_; Matrix testDataset_; Matrix gt_matches_; float speedup_; /** * The dataset used by this index */ const Matrix dataset_; /** * Index parameters */ float target_precision_; float build_weight_; float memory_weight_; float sample_fraction_; Distance distance_; }; } #endif /* OPENCV_FLANN_AUTOTUNED_INDEX_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/composite_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_COMPOSITE_INDEX_H_ #define OPENCV_FLANN_COMPOSITE_INDEX_H_ #include "general.h" #include "nn_index.h" #include "kdtree_index.h" #include "kmeans_index.h" namespace cvflann { /** * Index parameters for the CompositeIndex. */ struct CompositeIndexParams : public IndexParams { CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 ) { (*this)["algorithm"] = FLANN_INDEX_KMEANS; // number of randomized trees to use (for kdtree) (*this)["trees"] = trees; // branching factor (*this)["branching"] = branching; // max iterations to perform in one kmeans clustering (kmeans tree) (*this)["iterations"] = iterations; // algorithm used for picking the initial cluster centers for kmeans tree (*this)["centers_init"] = centers_init; // cluster boundary index. Used when searching the kmeans tree (*this)["cb_index"] = cb_index; } }; /** * This index builds a kd-tree index and a k-means index and performs nearest * neighbour search both indexes. This gives a slight boost in search performance * as some of the neighbours that are missed by one index are found by the other. */ template class CompositeIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; /** * Index constructor * @param inputData dataset containing the points to index * @param params Index parameters * @param d Distance functor * @return */ CompositeIndex(const Matrix& inputData, const IndexParams& params = CompositeIndexParams(), Distance d = Distance()) : index_params_(params) { kdtree_index_ = new KDTreeIndex(inputData, params, d); kmeans_index_ = new KMeansIndex(inputData, params, d); } CompositeIndex(const CompositeIndex&); CompositeIndex& operator=(const CompositeIndex&); virtual ~CompositeIndex() { delete kdtree_index_; delete kmeans_index_; } /** * @return The index type */ flann_algorithm_t getType() const { return FLANN_INDEX_COMPOSITE; } /** * @return Size of the index */ size_t size() const { return kdtree_index_->size(); } /** * \returns The dimensionality of the features in this index. */ size_t veclen() const { return kdtree_index_->veclen(); } /** * \returns The amount of memory (in bytes) used by the index. */ int usedMemory() const { return kmeans_index_->usedMemory() + kdtree_index_->usedMemory(); } /** * \brief Builds the index */ void buildIndex() { Logger::info("Building kmeans tree...\n"); kmeans_index_->buildIndex(); Logger::info("Building kdtree tree...\n"); kdtree_index_->buildIndex(); } /** * \brief Saves the index to a stream * \param stream The stream to save the index to */ void saveIndex(FILE* stream) { kmeans_index_->saveIndex(stream); kdtree_index_->saveIndex(stream); } /** * \brief Loads the index from a stream * \param stream The stream from which the index is loaded */ void loadIndex(FILE* stream) { kmeans_index_->loadIndex(stream); kdtree_index_->loadIndex(stream); } /** * \returns The index parameters */ IndexParams getParameters() const { return index_params_; } /** * \brief Method that searches for nearest-neighbours */ void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) { kmeans_index_->findNeighbors(result, vec, searchParams); kdtree_index_->findNeighbors(result, vec, searchParams); } private: /** The k-means index */ KMeansIndex* kmeans_index_; /** The kd-tree index */ KDTreeIndex* kdtree_index_; /** The index parameters */ const IndexParams index_params_; }; } #endif //OPENCV_FLANN_COMPOSITE_INDEX_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/config.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_CONFIG_H_ #define OPENCV_FLANN_CONFIG_H_ #ifdef FLANN_VERSION_ #undef FLANN_VERSION_ #endif #define FLANN_VERSION_ "1.6.10" #endif /* OPENCV_FLANN_CONFIG_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/defines.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_DEFINES_H_ #define OPENCV_FLANN_DEFINES_H_ #include "config.h" #ifdef FLANN_EXPORT #undef FLANN_EXPORT #endif #ifdef WIN32 /* win32 dll export/import directives */ #ifdef FLANN_EXPORTS #define FLANN_EXPORT __declspec(dllexport) #elif defined(FLANN_STATIC) #define FLANN_EXPORT #else #define FLANN_EXPORT __declspec(dllimport) #endif #else /* unix needs nothing */ #define FLANN_EXPORT #endif #ifdef FLANN_DEPRECATED #undef FLANN_DEPRECATED #endif #ifdef __GNUC__ #define FLANN_DEPRECATED __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define FLANN_DEPRECATED __declspec(deprecated) #else #pragma message("WARNING: You need to implement FLANN_DEPRECATED for this compiler") #define FLANN_DEPRECATED #endif #undef FLANN_PLATFORM_32_BIT #undef FLANN_PLATFORM_64_BIT #if defined __amd64__ || defined __x86_64__ || defined _WIN64 || defined _M_X64 #define FLANN_PLATFORM_64_BIT #else #define FLANN_PLATFORM_32_BIT #endif #undef FLANN_ARRAY_LEN #define FLANN_ARRAY_LEN(a) (sizeof(a)/sizeof(a[0])) namespace cvflann { /* Nearest neighbour index algorithms */ enum flann_algorithm_t { FLANN_INDEX_LINEAR = 0, FLANN_INDEX_KDTREE = 1, FLANN_INDEX_KMEANS = 2, FLANN_INDEX_COMPOSITE = 3, FLANN_INDEX_KDTREE_SINGLE = 4, FLANN_INDEX_HIERARCHICAL = 5, FLANN_INDEX_LSH = 6, FLANN_INDEX_SAVED = 254, FLANN_INDEX_AUTOTUNED = 255, // deprecated constants, should use the FLANN_INDEX_* ones instead LINEAR = 0, KDTREE = 1, KMEANS = 2, COMPOSITE = 3, KDTREE_SINGLE = 4, SAVED = 254, AUTOTUNED = 255 }; enum flann_centers_init_t { FLANN_CENTERS_RANDOM = 0, FLANN_CENTERS_GONZALES = 1, FLANN_CENTERS_KMEANSPP = 2, FLANN_CENTERS_GROUPWISE = 3, // deprecated constants, should use the FLANN_CENTERS_* ones instead CENTERS_RANDOM = 0, CENTERS_GONZALES = 1, CENTERS_KMEANSPP = 2 }; enum flann_log_level_t { FLANN_LOG_NONE = 0, FLANN_LOG_FATAL = 1, FLANN_LOG_ERROR = 2, FLANN_LOG_WARN = 3, FLANN_LOG_INFO = 4 }; enum flann_distance_t { FLANN_DIST_EUCLIDEAN = 1, FLANN_DIST_L2 = 1, FLANN_DIST_MANHATTAN = 2, FLANN_DIST_L1 = 2, FLANN_DIST_MINKOWSKI = 3, FLANN_DIST_MAX = 4, FLANN_DIST_HIST_INTERSECT = 5, FLANN_DIST_HELLINGER = 6, FLANN_DIST_CHI_SQUARE = 7, FLANN_DIST_CS = 7, FLANN_DIST_KULLBACK_LEIBLER = 8, FLANN_DIST_KL = 8, FLANN_DIST_HAMMING = 9, // deprecated constants, should use the FLANN_DIST_* ones instead EUCLIDEAN = 1, MANHATTAN = 2, MINKOWSKI = 3, MAX_DIST = 4, HIST_INTERSECT = 5, HELLINGER = 6, CS = 7, KL = 8, KULLBACK_LEIBLER = 8 }; enum flann_datatype_t { FLANN_INT8 = 0, FLANN_INT16 = 1, FLANN_INT32 = 2, FLANN_INT64 = 3, FLANN_UINT8 = 4, FLANN_UINT16 = 5, FLANN_UINT32 = 6, FLANN_UINT64 = 7, FLANN_FLOAT32 = 8, FLANN_FLOAT64 = 9 }; enum { FLANN_CHECKS_UNLIMITED = -1, FLANN_CHECKS_AUTOTUNED = -2 }; } #endif /* OPENCV_FLANN_DEFINES_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/dist.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_DIST_H_ #define OPENCV_FLANN_DIST_H_ #include #include #include #ifdef _MSC_VER typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #else #include #endif #include "defines.h" #if (defined WIN32 || defined _WIN32) && defined(_M_ARM) # include #endif #ifdef __ARM_NEON__ # include "arm_neon.h" #endif namespace cvflann { template inline T abs(T x) { return (x<0) ? -x : x; } template<> inline int abs(int x) { return ::abs(x); } template<> inline float abs(float x) { return fabsf(x); } template<> inline double abs(double x) { return fabs(x); } template struct Accumulator { typedef T Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; #undef True #undef False class True { }; class False { }; /** * Squared Euclidean distance functor. * * This is the simpler, unrolled version. This is preferable for * very low dimensionality data (eg 3D points) */ template struct L2_Simple { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const { ResultType result = ResultType(); ResultType diff; for(size_t i = 0; i < size; ++i ) { diff = *a++ - *b++; result += diff*diff; } return result; } template inline ResultType accum_dist(const U& a, const V& b, int) const { return (a-b)*(a-b); } }; /** * Squared Euclidean distance functor, optimized version */ template struct L2 { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; /** * Compute the squared Euclidean distance between two vectors. * * This is highly optimised, with loop unrolling, as it is one * of the most expensive inner loops. * * The computation of squared root at the end is omitted for * efficiency. */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const { ResultType result = ResultType(); ResultType diff0, diff1, diff2, diff3; Iterator1 last = a + size; Iterator1 lastgroup = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { diff0 = (ResultType)(a[0] - b[0]); diff1 = (ResultType)(a[1] - b[1]); diff2 = (ResultType)(a[2] - b[2]); diff3 = (ResultType)(a[3] - b[3]); result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; a += 4; b += 4; if ((worst_dist>0)&&(result>worst_dist)) { return result; } } /* Process last 0-3 pixels. Not needed for standard vector lengths. */ while (a < last) { diff0 = (ResultType)(*a++ - *b++); result += diff0 * diff0; } return result; } /** * Partial euclidean distance, using just one dimension. This is used by the * kd-tree when computing partial distances while traversing the tree. * * Squared root is omitted for efficiency. */ template inline ResultType accum_dist(const U& a, const V& b, int) const { return (a-b)*(a-b); } }; /* * Manhattan distance functor, optimized version */ template struct L1 { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; /** * Compute the Manhattan (L_1) distance between two vectors. * * This is highly optimised, with loop unrolling, as it is one * of the most expensive inner loops. */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const { ResultType result = ResultType(); ResultType diff0, diff1, diff2, diff3; Iterator1 last = a + size; Iterator1 lastgroup = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { diff0 = (ResultType)abs(a[0] - b[0]); diff1 = (ResultType)abs(a[1] - b[1]); diff2 = (ResultType)abs(a[2] - b[2]); diff3 = (ResultType)abs(a[3] - b[3]); result += diff0 + diff1 + diff2 + diff3; a += 4; b += 4; if ((worst_dist>0)&&(result>worst_dist)) { return result; } } /* Process last 0-3 pixels. Not needed for standard vector lengths. */ while (a < last) { diff0 = (ResultType)abs(*a++ - *b++); result += diff0; } return result; } /** * Partial distance, used by the kd-tree. */ template inline ResultType accum_dist(const U& a, const V& b, int) const { return abs(a-b); } }; template struct MinkowskiDistance { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; int order; MinkowskiDistance(int order_) : order(order_) {} /** * Compute the Minkowsky (L_p) distance between two vectors. * * This is highly optimised, with loop unrolling, as it is one * of the most expensive inner loops. * * The computation of squared root at the end is omitted for * efficiency. */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const { ResultType result = ResultType(); ResultType diff0, diff1, diff2, diff3; Iterator1 last = a + size; Iterator1 lastgroup = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { diff0 = (ResultType)abs(a[0] - b[0]); diff1 = (ResultType)abs(a[1] - b[1]); diff2 = (ResultType)abs(a[2] - b[2]); diff3 = (ResultType)abs(a[3] - b[3]); result += pow(diff0,order) + pow(diff1,order) + pow(diff2,order) + pow(diff3,order); a += 4; b += 4; if ((worst_dist>0)&&(result>worst_dist)) { return result; } } /* Process last 0-3 pixels. Not needed for standard vector lengths. */ while (a < last) { diff0 = (ResultType)abs(*a++ - *b++); result += pow(diff0,order); } return result; } /** * Partial distance, used by the kd-tree. */ template inline ResultType accum_dist(const U& a, const V& b, int) const { return pow(static_cast(abs(a-b)),order); } }; template struct MaxDistance { typedef False is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; /** * Compute the max distance (L_infinity) between two vectors. * * This distance is not a valid kdtree distance, it's not dimensionwise additive. */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const { ResultType result = ResultType(); ResultType diff0, diff1, diff2, diff3; Iterator1 last = a + size; Iterator1 lastgroup = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { diff0 = abs(a[0] - b[0]); diff1 = abs(a[1] - b[1]); diff2 = abs(a[2] - b[2]); diff3 = abs(a[3] - b[3]); if (diff0>result) {result = diff0; } if (diff1>result) {result = diff1; } if (diff2>result) {result = diff2; } if (diff3>result) {result = diff3; } a += 4; b += 4; if ((worst_dist>0)&&(result>worst_dist)) { return result; } } /* Process last 0-3 pixels. Not needed for standard vector lengths. */ while (a < last) { diff0 = abs(*a++ - *b++); result = (diff0>result) ? diff0 : result; } return result; } /* This distance functor is not dimension-wise additive, which * makes it an invalid kd-tree distance, not implementing the accum_dist method */ }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor * bit count of A exclusive XOR'ed with B */ struct HammingLUT { typedef False is_kdtree_distance; typedef False is_vector_space_distance; typedef unsigned char ElementType; typedef int ResultType; /** this will count the bits in a ^ b */ ResultType operator()(const unsigned char* a, const unsigned char* b, size_t size) const { static const uchar popCountTable[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 }; ResultType result = 0; for (size_t i = 0; i < size; i++) { result += popCountTable[a[i] ^ b[i]]; } return result; } }; /** * Hamming distance functor (pop count between two binary vectors, i.e. xor them and count the number of bits set) * That code was taken from brief.cpp in OpenCV */ template struct Hamming { typedef False is_kdtree_distance; typedef False is_vector_space_distance; typedef T ElementType; typedef int ResultType; template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const { ResultType result = 0; #ifdef __ARM_NEON__ { uint32x4_t bits = vmovq_n_u32(0); for (size_t i = 0; i < size; i += 16) { uint8x16_t A_vec = vld1q_u8 (a + i); uint8x16_t B_vec = vld1q_u8 (b + i); uint8x16_t AxorB = veorq_u8 (A_vec, B_vec); uint8x16_t bitsSet = vcntq_u8 (AxorB); uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); bits = vaddq_u32(bits, bitSet4); } uint64x2_t bitSet2 = vpaddlq_u32 (bits); result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); } #elif __GNUC__ { //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) typedef unsigned long long pop_t; const size_t modulo = size % sizeof(pop_t); const pop_t* a2 = reinterpret_cast (a); const pop_t* b2 = reinterpret_cast (b); const pop_t* a2_end = a2 + (size / sizeof(pop_t)); for (; a2 != a2_end; ++a2, ++b2) result += __builtin_popcountll((*a2) ^ (*b2)); if (modulo) { //in the case where size is not dividable by sizeof(size_t) //need to mask off the bits at the end pop_t a_final = 0, b_final = 0; memcpy(&a_final, a2, modulo); memcpy(&b_final, b2, modulo); result += __builtin_popcountll(a_final ^ b_final); } } #else // NO NEON and NOT GNUC typedef unsigned long long pop_t; HammingLUT lut; result = lut(reinterpret_cast (a), reinterpret_cast (b), size * sizeof(pop_t)); #endif return result; } }; template struct Hamming2 { typedef False is_kdtree_distance; typedef False is_vector_space_distance; typedef T ElementType; typedef int ResultType; /** This is popcount_3() from: * http://en.wikipedia.org/wiki/Hamming_weight */ unsigned int popcnt32(uint32_t n) const { n -= ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return (((n + (n >> 4))& 0xF0F0F0F)* 0x1010101) >> 24; } #ifdef FLANN_PLATFORM_64_BIT unsigned int popcnt64(uint64_t n) const { n -= ((n >> 1) & 0x5555555555555555); n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; } #endif template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const { #ifdef FLANN_PLATFORM_64_BIT const uint64_t* pa = reinterpret_cast(a); const uint64_t* pb = reinterpret_cast(b); ResultType result = 0; size /= (sizeof(uint64_t)/sizeof(unsigned char)); for(size_t i = 0; i < size; ++i ) { result += popcnt64(*pa ^ *pb); ++pa; ++pb; } #else const uint32_t* pa = reinterpret_cast(a); const uint32_t* pb = reinterpret_cast(b); ResultType result = 0; size /= (sizeof(uint32_t)/sizeof(unsigned char)); for(size_t i = 0; i < size; ++i ) { result += popcnt32(*pa ^ *pb); ++pa; ++pb; } #endif return result; } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template struct HistIntersectionDistance { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; /** * Compute the histogram intersection distance */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const { ResultType result = ResultType(); ResultType min0, min1, min2, min3; Iterator1 last = a + size; Iterator1 lastgroup = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { min0 = (ResultType)(a[0] < b[0] ? a[0] : b[0]); min1 = (ResultType)(a[1] < b[1] ? a[1] : b[1]); min2 = (ResultType)(a[2] < b[2] ? a[2] : b[2]); min3 = (ResultType)(a[3] < b[3] ? a[3] : b[3]); result += min0 + min1 + min2 + min3; a += 4; b += 4; if ((worst_dist>0)&&(result>worst_dist)) { return result; } } /* Process last 0-3 pixels. Not needed for standard vector lengths. */ while (a < last) { min0 = (ResultType)(*a < *b ? *a : *b); result += min0; ++a; ++b; } return result; } /** * Partial distance, used by the kd-tree. */ template inline ResultType accum_dist(const U& a, const V& b, int) const { return a struct HellingerDistance { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; /** * Compute the Hellinger distance */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const { ResultType result = ResultType(); ResultType diff0, diff1, diff2, diff3; Iterator1 last = a + size; Iterator1 lastgroup = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { diff0 = sqrt(static_cast(a[0])) - sqrt(static_cast(b[0])); diff1 = sqrt(static_cast(a[1])) - sqrt(static_cast(b[1])); diff2 = sqrt(static_cast(a[2])) - sqrt(static_cast(b[2])); diff3 = sqrt(static_cast(a[3])) - sqrt(static_cast(b[3])); result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; a += 4; b += 4; } while (a < last) { diff0 = sqrt(static_cast(*a++)) - sqrt(static_cast(*b++)); result += diff0 * diff0; } return result; } /** * Partial distance, used by the kd-tree. */ template inline ResultType accum_dist(const U& a, const V& b, int) const { ResultType diff = sqrt(static_cast(a)) - sqrt(static_cast(b)); return diff * diff; } }; template struct ChiSquareDistance { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; /** * Compute the chi-square distance */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const { ResultType result = ResultType(); ResultType sum, diff; Iterator1 last = a + size; while (a < last) { sum = (ResultType)(*a + *b); if (sum>0) { diff = (ResultType)(*a - *b); result += diff*diff/sum; } ++a; ++b; if ((worst_dist>0)&&(result>worst_dist)) { return result; } } return result; } /** * Partial distance, used by the kd-tree. */ template inline ResultType accum_dist(const U& a, const V& b, int) const { ResultType result = ResultType(); ResultType sum, diff; sum = (ResultType)(a+b); if (sum>0) { diff = (ResultType)(a-b); result = diff*diff/sum; } return result; } }; template struct KL_Divergence { typedef True is_kdtree_distance; typedef True is_vector_space_distance; typedef T ElementType; typedef typename Accumulator::Type ResultType; /** * Compute the Kullback–Leibler divergence */ template ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const { ResultType result = ResultType(); Iterator1 last = a + size; while (a < last) { if (* b != 0) { ResultType ratio = (ResultType)(*a / *b); if (ratio>0) { result += *a * log(ratio); } } ++a; ++b; if ((worst_dist>0)&&(result>worst_dist)) { return result; } } return result; } /** * Partial distance, used by the kd-tree. */ template inline ResultType accum_dist(const U& a, const V& b, int) const { ResultType result = ResultType(); if( *b != 0 ) { ResultType ratio = (ResultType)(a / b); if (ratio>0) { result = a * log(ratio); } } return result; } }; /* * This is a "zero iterator". It basically behaves like a zero filled * array to all algorithms that use arrays as iterators (STL style). * It's useful when there's a need to compute the distance between feature * and origin it and allows for better compiler optimisation than using a * zero-filled array. */ template struct ZeroIterator { T operator*() { return 0; } T operator[](int) { return 0; } const ZeroIterator& operator ++() { return *this; } ZeroIterator operator ++(int) { return *this; } ZeroIterator& operator+=(int) { return *this; } }; /* * Depending on processed distances, some of them are already squared (e.g. L2) * and some are not (e.g.Hamming). In KMeans++ for instance we want to be sure * we are working on ^2 distances, thus following templates to ensure that. */ template struct squareDistance { typedef typename Distance::ResultType ResultType; ResultType operator()( ResultType dist ) { return dist*dist; } }; template struct squareDistance, ElementType> { typedef typename L2_Simple::ResultType ResultType; ResultType operator()( ResultType dist ) { return dist; } }; template struct squareDistance, ElementType> { typedef typename L2::ResultType ResultType; ResultType operator()( ResultType dist ) { return dist; } }; template struct squareDistance, ElementType> { typedef typename MinkowskiDistance::ResultType ResultType; ResultType operator()( ResultType dist ) { return dist; } }; template struct squareDistance, ElementType> { typedef typename HellingerDistance::ResultType ResultType; ResultType operator()( ResultType dist ) { return dist; } }; template struct squareDistance, ElementType> { typedef typename ChiSquareDistance::ResultType ResultType; ResultType operator()( ResultType dist ) { return dist; } }; template typename Distance::ResultType ensureSquareDistance( typename Distance::ResultType dist ) { typedef typename Distance::ElementType ElementType; squareDistance dummy; return dummy( dist ); } /* * ...and a template to ensure the user that he will process the normal distance, * and not squared distance, without loosing processing time calling sqrt(ensureSquareDistance) * that will result in doing actually sqrt(dist*dist) for L1 distance for instance. */ template struct simpleDistance { typedef typename Distance::ResultType ResultType; ResultType operator()( ResultType dist ) { return dist; } }; template struct simpleDistance, ElementType> { typedef typename L2_Simple::ResultType ResultType; ResultType operator()( ResultType dist ) { return sqrt(dist); } }; template struct simpleDistance, ElementType> { typedef typename L2::ResultType ResultType; ResultType operator()( ResultType dist ) { return sqrt(dist); } }; template struct simpleDistance, ElementType> { typedef typename MinkowskiDistance::ResultType ResultType; ResultType operator()( ResultType dist ) { return sqrt(dist); } }; template struct simpleDistance, ElementType> { typedef typename HellingerDistance::ResultType ResultType; ResultType operator()( ResultType dist ) { return sqrt(dist); } }; template struct simpleDistance, ElementType> { typedef typename ChiSquareDistance::ResultType ResultType; ResultType operator()( ResultType dist ) { return sqrt(dist); } }; template typename Distance::ResultType ensureSimpleDistance( typename Distance::ResultType dist ) { typedef typename Distance::ElementType ElementType; simpleDistance dummy; return dummy( dist ); } } #endif //OPENCV_FLANN_DIST_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/dummy.h ================================================ #ifndef OPENCV_FLANN_DUMMY_H_ #define OPENCV_FLANN_DUMMY_H_ namespace cvflann { #if (defined WIN32 || defined _WIN32 || defined WINCE) && defined CVAPI_EXPORTS __declspec(dllexport) #endif void dummyfunc(); } #endif /* OPENCV_FLANN_DUMMY_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/dynamic_bitset.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ /*********************************************************************** * Author: Vincent Rabaud *************************************************************************/ #ifndef OPENCV_FLANN_DYNAMIC_BITSET_H_ #define OPENCV_FLANN_DYNAMIC_BITSET_H_ #ifndef FLANN_USE_BOOST # define FLANN_USE_BOOST 0 #endif //#define FLANN_USE_BOOST 1 #if FLANN_USE_BOOST #include typedef boost::dynamic_bitset<> DynamicBitset; #else #include #include "dist.h" namespace cvflann { /** Class re-implementing the boost version of it * This helps not depending on boost, it also does not do the bound checks * and has a way to reset a block for speed */ class DynamicBitset { public: /** default constructor */ DynamicBitset() { } /** only constructor we use in our code * @param sz the size of the bitset (in bits) */ DynamicBitset(size_t sz) { resize(sz); reset(); } /** Sets all the bits to 0 */ void clear() { std::fill(bitset_.begin(), bitset_.end(), 0); } /** @brief checks if the bitset is empty * @return true if the bitset is empty */ bool empty() const { return bitset_.empty(); } /** set all the bits to 0 */ void reset() { std::fill(bitset_.begin(), bitset_.end(), 0); } /** @brief set one bit to 0 * @param index */ void reset(size_t index) { bitset_[index / cell_bit_size_] &= ~(size_t(1) << (index % cell_bit_size_)); } /** @brief sets a specific bit to 0, and more bits too * This function is useful when resetting a given set of bits so that the * whole bitset ends up being 0: if that's the case, we don't care about setting * other bits to 0 * @param index */ void reset_block(size_t index) { bitset_[index / cell_bit_size_] = 0; } /** resize the bitset so that it contains at least sz bits * @param sz */ void resize(size_t sz) { size_ = sz; bitset_.resize(sz / cell_bit_size_ + 1); } /** set a bit to true * @param index the index of the bit to set to 1 */ void set(size_t index) { bitset_[index / cell_bit_size_] |= size_t(1) << (index % cell_bit_size_); } /** gives the number of contained bits */ size_t size() const { return size_; } /** check if a bit is set * @param index the index of the bit to check * @return true if the bit is set */ bool test(size_t index) const { return (bitset_[index / cell_bit_size_] & (size_t(1) << (index % cell_bit_size_))) != 0; } private: std::vector bitset_; size_t size_; static const unsigned int cell_bit_size_ = CHAR_BIT * sizeof(size_t); }; } // namespace cvflann #endif #endif // OPENCV_FLANN_DYNAMIC_BITSET_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/flann.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/flann.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/flann_base.hpp ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_BASE_HPP_ #define OPENCV_FLANN_BASE_HPP_ #include #include #include #include "general.h" #include "matrix.h" #include "params.h" #include "saving.h" #include "all_indices.h" namespace cvflann { /** * Sets the log level used for all flann functions * @param level Verbosity level */ inline void log_verbosity(int level) { if (level >= 0) { Logger::setLevel(level); } } /** * (Deprecated) Index parameters for creating a saved index. */ struct SavedIndexParams : public IndexParams { SavedIndexParams(cv::String filename) { (* this)["algorithm"] = FLANN_INDEX_SAVED; (*this)["filename"] = filename; } }; template NNIndex* load_saved_index(const Matrix& dataset, const cv::String& filename, Distance distance) { typedef typename Distance::ElementType ElementType; FILE* fin = fopen(filename.c_str(), "rb"); if (fin == NULL) { return NULL; } IndexHeader header = load_header(fin); if (header.data_type != Datatype::type()) { throw FLANNException("Datatype of saved index is different than of the one to be created."); } if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) { throw FLANNException("The index saved belongs to a different dataset"); } IndexParams params; params["algorithm"] = header.index_type; NNIndex* nnIndex = create_index_by_type(dataset, params, distance); nnIndex->loadIndex(fin); fclose(fin); return nnIndex; } template class Index : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; Index(const Matrix& features, const IndexParams& params, Distance distance = Distance() ) : index_params_(params) { flann_algorithm_t index_type = get_param(params,"algorithm"); loaded_ = false; if (index_type == FLANN_INDEX_SAVED) { nnIndex_ = load_saved_index(features, get_param(params,"filename"), distance); loaded_ = true; } else { nnIndex_ = create_index_by_type(features, params, distance); } } ~Index() { delete nnIndex_; } /** * Builds the index. */ void buildIndex() { if (!loaded_) { nnIndex_->buildIndex(); } } void save(cv::String filename) { FILE* fout = fopen(filename.c_str(), "wb"); if (fout == NULL) { throw FLANNException("Cannot open file"); } save_header(fout, *nnIndex_); saveIndex(fout); fclose(fout); } /** * \brief Saves the index to a stream * \param stream The stream to save the index to */ virtual void saveIndex(FILE* stream) { nnIndex_->saveIndex(stream); } /** * \brief Loads the index from a stream * \param stream The stream from which the index is loaded */ virtual void loadIndex(FILE* stream) { nnIndex_->loadIndex(stream); } /** * \returns number of features in this index. */ size_t veclen() const { return nnIndex_->veclen(); } /** * \returns The dimensionality of the features in this index. */ size_t size() const { return nnIndex_->size(); } /** * \returns The index type (kdtree, kmeans,...) */ flann_algorithm_t getType() const { return nnIndex_->getType(); } /** * \returns The amount of memory (in bytes) used by the index. */ virtual int usedMemory() const { return nnIndex_->usedMemory(); } /** * \returns The index parameters */ IndexParams getParameters() const { return nnIndex_->getParameters(); } /** * \brief Perform k-nearest neighbor search * \param[in] queries The query points for which to find the nearest neighbors * \param[out] indices The indices of the nearest neighbors found * \param[out] dists Distances to the nearest neighbors found * \param[in] knn Number of nearest neighbors to return * \param[in] params Search parameters */ void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) { nnIndex_->knnSearch(queries, indices, dists, knn, params); } /** * \brief Perform radius search * \param[in] query The query point * \param[out] indices The indinces of the neighbors found within the given radius * \param[out] dists The distances to the nearest neighbors found * \param[in] radius The radius used for search * \param[in] params Search parameters * \returns Number of neighbors found */ int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) { return nnIndex_->radiusSearch(query, indices, dists, radius, params); } /** * \brief Method that searches for nearest-neighbours */ void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) { nnIndex_->findNeighbors(result, vec, searchParams); } /** * \brief Returns actual index */ FLANN_DEPRECATED NNIndex* getIndex() { return nnIndex_; } /** * \brief Returns index parameters. * \deprecated use getParameters() instead. */ FLANN_DEPRECATED const IndexParams* getIndexParameters() { return &index_params_; } private: /** Pointer to actual index class */ NNIndex* nnIndex_; /** Indices if the index was loaded from a file */ bool loaded_; /** Parameters passed to the index */ IndexParams index_params_; }; /** * Performs a hierarchical clustering of the points passed as argument and then takes a cut in the * the clustering tree to return a flat clustering. * @param[in] points Points to be clustered * @param centers The computed cluster centres. Matrix should be preallocated and centers.rows is the * number of clusters requested. * @param params Clustering parameters (The same as for cvflann::KMeansIndex) * @param d Distance to be used for clustering (eg: cvflann::L2) * @return number of clusters computed (can be different than clusters.rows and is the highest number * of the form (branching-1)*K+1 smaller than clusters.rows). */ template int hierarchicalClustering(const Matrix& points, Matrix& centers, const KMeansIndexParams& params, Distance d = Distance()) { KMeansIndex kmeans(points, params, d); kmeans.buildIndex(); int clusterNum = kmeans.getClusterCenters(centers); return clusterNum; } } #endif /* OPENCV_FLANN_BASE_HPP_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/general.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_GENERAL_H_ #define OPENCV_FLANN_GENERAL_H_ #include "opencv2/core.hpp" namespace cvflann { class FLANNException : public cv::Exception { public: FLANNException(const char* message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } FLANNException(const cv::String& message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } }; } #endif /* OPENCV_FLANN_GENERAL_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/ground_truth.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_GROUND_TRUTH_H_ #define OPENCV_FLANN_GROUND_TRUTH_H_ #include "dist.h" #include "matrix.h" namespace cvflann { template void find_nearest(const Matrix& dataset, typename Distance::ElementType* query, int* matches, int nn, int skip = 0, Distance distance = Distance()) { typedef typename Distance::ResultType DistanceType; int n = nn + skip; std::vector match(n); std::vector dists(n); dists[0] = distance(dataset[0], query, dataset.cols); match[0] = 0; int dcnt = 1; for (size_t i=1; i=1 && dists[j] void compute_ground_truth(const Matrix& dataset, const Matrix& testset, Matrix& matches, int skip=0, Distance d = Distance()) { for (size_t i=0; i(dataset, testset[i], matches[i], (int)matches.cols, skip, d); } } } #endif //OPENCV_FLANN_GROUND_TRUTH_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/hdf5.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_HDF5_H_ #define OPENCV_FLANN_HDF5_H_ #include #include "matrix.h" namespace cvflann { namespace { template hid_t get_hdf5_type() { throw FLANNException("Unsupported type for IO operations"); } template<> hid_t get_hdf5_type() { return H5T_NATIVE_CHAR; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_UCHAR; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_SHORT; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_USHORT; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_INT; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_UINT; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_LONG; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_ULONG; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_FLOAT; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_DOUBLE; } } #define CHECK_ERROR(x,y) if ((x)<0) throw FLANNException((y)); template void save_to_file(const cvflann::Matrix& dataset, const String& filename, const String& name) { #if H5Eset_auto_vers == 2 H5Eset_auto( H5E_DEFAULT, NULL, NULL ); #else H5Eset_auto( NULL, NULL ); #endif herr_t status; hid_t file_id; file_id = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); if (file_id < 0) { file_id = H5Fcreate(filename.c_str(), H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT); } CHECK_ERROR(file_id,"Error creating hdf5 file."); hsize_t dimsf[2]; // dataset dimensions dimsf[0] = dataset.rows; dimsf[1] = dataset.cols; hid_t space_id = H5Screate_simple(2, dimsf, NULL); hid_t memspace_id = H5Screate_simple(2, dimsf, NULL); hid_t dataset_id; #if H5Dcreate_vers == 2 dataset_id = H5Dcreate2(file_id, name.c_str(), get_hdf5_type(), space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate(file_id, name.c_str(), get_hdf5_type(), space_id, H5P_DEFAULT); #endif if (dataset_id<0) { #if H5Dopen_vers == 2 dataset_id = H5Dopen2(file_id, name.c_str(), H5P_DEFAULT); #else dataset_id = H5Dopen(file_id, name.c_str()); #endif } CHECK_ERROR(dataset_id,"Error creating or opening dataset in file."); status = H5Dwrite(dataset_id, get_hdf5_type(), memspace_id, space_id, H5P_DEFAULT, dataset.data ); CHECK_ERROR(status, "Error writing to dataset"); H5Sclose(memspace_id); H5Sclose(space_id); H5Dclose(dataset_id); H5Fclose(file_id); } template void load_from_file(cvflann::Matrix& dataset, const String& filename, const String& name) { herr_t status; hid_t file_id = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); CHECK_ERROR(file_id,"Error opening hdf5 file."); hid_t dataset_id; #if H5Dopen_vers == 2 dataset_id = H5Dopen2(file_id, name.c_str(), H5P_DEFAULT); #else dataset_id = H5Dopen(file_id, name.c_str()); #endif CHECK_ERROR(dataset_id,"Error opening dataset in file."); hid_t space_id = H5Dget_space(dataset_id); hsize_t dims_out[2]; H5Sget_simple_extent_dims(space_id, dims_out, NULL); dataset = cvflann::Matrix(new T[dims_out[0]*dims_out[1]], dims_out[0], dims_out[1]); status = H5Dread(dataset_id, get_hdf5_type(), H5S_ALL, H5S_ALL, H5P_DEFAULT, dataset[0]); CHECK_ERROR(status, "Error reading dataset"); H5Sclose(space_id); H5Dclose(dataset_id); H5Fclose(file_id); } #ifdef HAVE_MPI namespace mpi { /** * Loads a the hyperslice corresponding to this processor from a hdf5 file. * @param flann_dataset Dataset where the data is loaded * @param filename HDF5 file name * @param name Name of dataset inside file */ template void load_from_file(cvflann::Matrix& dataset, const String& filename, const String& name) { MPI_Comm comm = MPI_COMM_WORLD; MPI_Info info = MPI_INFO_NULL; int mpi_size, mpi_rank; MPI_Comm_size(comm, &mpi_size); MPI_Comm_rank(comm, &mpi_rank); herr_t status; hid_t plist_id = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_mpio(plist_id, comm, info); hid_t file_id = H5Fopen(filename.c_str(), H5F_ACC_RDWR, plist_id); CHECK_ERROR(file_id,"Error opening hdf5 file."); H5Pclose(plist_id); hid_t dataset_id; #if H5Dopen_vers == 2 dataset_id = H5Dopen2(file_id, name.c_str(), H5P_DEFAULT); #else dataset_id = H5Dopen(file_id, name.c_str()); #endif CHECK_ERROR(dataset_id,"Error opening dataset in file."); hid_t space_id = H5Dget_space(dataset_id); hsize_t dims[2]; H5Sget_simple_extent_dims(space_id, dims, NULL); hsize_t count[2]; hsize_t offset[2]; hsize_t item_cnt = dims[0]/mpi_size+(dims[0]%mpi_size==0 ? 0 : 1); hsize_t cnt = (mpi_rank(), memspace_id, space_id, plist_id, dataset.data); CHECK_ERROR(status, "Error reading dataset"); H5Pclose(plist_id); H5Sclose(space_id); H5Sclose(memspace_id); H5Dclose(dataset_id); H5Fclose(file_id); } } #endif // HAVE_MPI } // namespace cvflann::mpi #endif /* OPENCV_FLANN_HDF5_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/heap.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_HEAP_H_ #define OPENCV_FLANN_HEAP_H_ #include #include namespace cvflann { /** * Priority Queue Implementation * * The priority queue is implemented with a heap. A heap is a complete * (full) binary tree in which each parent is less than both of its * children, but the order of the children is unspecified. */ template class Heap { /** * Storage array for the heap. * Type T must be comparable. */ std::vector heap; int length; /** * Number of element in the heap */ int count; public: /** * Constructor. * * Params: * sz = heap size */ Heap(int sz) { length = sz; heap.reserve(length); count = 0; } /** * * Returns: heap size */ int size() { return count; } /** * Tests if the heap is empty * * Returns: true is heap empty, false otherwise */ bool empty() { return size()==0; } /** * Clears the heap. */ void clear() { heap.clear(); count = 0; } struct CompareT { bool operator()(const T& t_1, const T& t_2) const { return t_2 < t_1; } }; /** * Insert a new element in the heap. * * We select the next empty leaf node, and then keep moving any larger * parents down until the right location is found to store this element. * * Params: * value = the new element to be inserted in the heap */ void insert(T value) { /* If heap is full, then return without adding this element. */ if (count == length) { return; } heap.push_back(value); static CompareT compareT; std::push_heap(heap.begin(), heap.end(), compareT); ++count; } /** * Returns the node of minimum value from the heap (top of the heap). * * Params: * value = out parameter used to return the min element * Returns: false if heap empty */ bool popMin(T& value) { if (count == 0) { return false; } value = heap[0]; static CompareT compareT; std::pop_heap(heap.begin(), heap.end(), compareT); heap.pop_back(); --count; return true; /* Return old last node. */ } }; } #endif //OPENCV_FLANN_HEAP_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/hierarchical_clustering_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ #define OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ #include #include #include #include #include #include "general.h" #include "nn_index.h" #include "dist.h" #include "matrix.h" #include "result_set.h" #include "heap.h" #include "allocator.h" #include "random.h" #include "saving.h" namespace cvflann { struct HierarchicalClusteringIndexParams : public IndexParams { HierarchicalClusteringIndexParams(int branching = 32, flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, int trees = 4, int leaf_size = 100) { (*this)["algorithm"] = FLANN_INDEX_HIERARCHICAL; // The branching factor used in the hierarchical clustering (*this)["branching"] = branching; // Algorithm used for picking the initial cluster centers (*this)["centers_init"] = centers_init; // number of parallel trees to build (*this)["trees"] = trees; // maximum leaf size (*this)["leaf_size"] = leaf_size; } }; /** * Hierarchical index * * Contains a tree constructed through a hierarchical clustering * and other information for indexing a set of points for nearest-neighbour matching. */ template class HierarchicalClusteringIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; private: typedef void (HierarchicalClusteringIndex::* centersAlgFunction)(int, int*, int, int*, int&); /** * The function used for choosing the cluster centers. */ centersAlgFunction chooseCenters; /** * Chooses the initial centers in the k-means clustering in a random manner. * * Params: * k = number of centers * vecs = the dataset of points * indices = indices in the dataset * indices_length = length of indices vector * */ void chooseCentersRandom(int k, int* dsindices, int indices_length, int* centers, int& centers_length) { UniqueRandom r(indices_length); int index; for (index=0; index=0 && rnd < n); centers[0] = dsindices[rnd]; int index; for (index=1; indexbest_val) { best_val = dist; best_index = j; } } if (best_index!=-1) { centers[index] = dsindices[best_index]; } else { break; } } centers_length = index; } /** * Chooses the initial centers in the k-means using the algorithm * proposed in the KMeans++ paper: * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding * * Implementation of this function was converted from the one provided in Arthur's code. * * Params: * k = number of centers * vecs = the dataset of points * indices = indices in the dataset * Returns: */ void chooseCentersKMeanspp(int k, int* dsindices, int indices_length, int* centers, int& centers_length) { int n = indices_length; double currentPot = 0; DistanceType* closestDistSq = new DistanceType[n]; // Choose one random center and set the closestDistSq values int index = rand_int(n); assert(index >=0 && index < n); centers[0] = dsindices[index]; // Computing distance^2 will have the advantage of even higher probability further to pick new centers // far from previous centers (and this complies to "k-means++: the advantages of careful seeding" article) for (int i = 0; i < n; i++) { closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); currentPot += closestDistSq[i]; } const int numLocalTries = 1; // Choose each center int centerCount; for (centerCount = 1; centerCount < k; centerCount++) { // Repeat several trials double bestNewPot = -1; int bestNewIndex = 0; for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { // Choose our center - have to be slightly careful to return a valid answer even accounting // for possible rounding errors double randVal = rand_double(currentPot); for (index = 0; index < n-1; index++) { if (randVal <= closestDistSq[index]) break; else randVal -= closestDistSq[index]; } // Compute the new potential double newPot = 0; for (int i = 0; i < n; i++) { DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); } // Store the best result if ((bestNewPot < 0)||(newPot < bestNewPot)) { bestNewPot = newPot; bestNewIndex = index; } } // Add the appropriate center centers[centerCount] = dsindices[bestNewIndex]; currentPot = bestNewPot; for (int i = 0; i < n; i++) { DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols); closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); } } centers_length = centerCount; delete[] closestDistSq; } /** * Chooses the initial centers in a way inspired by Gonzales (by Pierre-Emmanuel Viel): * select the first point of the list as a candidate, then parse the points list. If another * point is further than current candidate from the other centers, test if it is a good center * of a local aggregation. If it is, replace current candidate by this point. And so on... * * Used with KMeansIndex that computes centers coordinates by averaging positions of clusters points, * this doesn't make a real difference with previous methods. But used with HierarchicalClusteringIndex * class that pick centers among existing points instead of computing the barycenters, there is a real * improvement. * * Params: * k = number of centers * vecs = the dataset of points * indices = indices in the dataset * Returns: */ void GroupWiseCenterChooser(int k, int* dsindices, int indices_length, int* centers, int& centers_length) { const float kSpeedUpFactor = 1.3f; int n = indices_length; DistanceType* closestDistSq = new DistanceType[n]; // Choose one random center and set the closestDistSq values int index = rand_int(n); assert(index >=0 && index < n); centers[0] = dsindices[index]; for (int i = 0; i < n; i++) { closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); } // Choose each center int centerCount; for (centerCount = 1; centerCount < k; centerCount++) { // Repeat several trials double bestNewPot = -1; int bestNewIndex = 0; DistanceType furthest = 0; for (index = 0; index < n; index++) { // We will test only the potential of the points further than current candidate if( closestDistSq[index] > kSpeedUpFactor * (float)furthest ) { // Compute the new potential double newPot = 0; for (int i = 0; i < n; i++) { newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols) , closestDistSq[i] ); } // Store the best result if ((bestNewPot < 0)||(newPot <= bestNewPot)) { bestNewPot = newPot; bestNewIndex = index; furthest = closestDistSq[index]; } } } // Add the appropriate center centers[centerCount] = dsindices[bestNewIndex]; for (int i = 0; i < n; i++) { closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols) , closestDistSq[i] ); } } centers_length = centerCount; delete[] closestDistSq; } public: /** * Index constructor * * Params: * inputData = dataset with the input features * params = parameters passed to the hierarchical k-means algorithm */ HierarchicalClusteringIndex(const Matrix& inputData, const IndexParams& index_params = HierarchicalClusteringIndexParams(), Distance d = Distance()) : dataset(inputData), params(index_params), root(NULL), indices(NULL), distance(d) { memoryCounter = 0; size_ = dataset.rows; veclen_ = dataset.cols; branching_ = get_param(params,"branching",32); centers_init_ = get_param(params,"centers_init", FLANN_CENTERS_RANDOM); trees_ = get_param(params,"trees",4); leaf_size_ = get_param(params,"leaf_size",100); if (centers_init_==FLANN_CENTERS_RANDOM) { chooseCenters = &HierarchicalClusteringIndex::chooseCentersRandom; } else if (centers_init_==FLANN_CENTERS_GONZALES) { chooseCenters = &HierarchicalClusteringIndex::chooseCentersGonzales; } else if (centers_init_==FLANN_CENTERS_KMEANSPP) { chooseCenters = &HierarchicalClusteringIndex::chooseCentersKMeanspp; } else if (centers_init_==FLANN_CENTERS_GROUPWISE) { chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser; } else { throw FLANNException("Unknown algorithm for choosing initial centers."); } trees_ = get_param(params,"trees",4); root = new NodePtr[trees_]; indices = new int*[trees_]; for (int i=0; i(); computeClustering(root[i], indices[i], (int)size_, branching_,0); } } flann_algorithm_t getType() const { return FLANN_INDEX_HIERARCHICAL; } void saveIndex(FILE* stream) { save_value(stream, branching_); save_value(stream, trees_); save_value(stream, centers_init_); save_value(stream, leaf_size_); save_value(stream, memoryCounter); for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) { int maxChecks = get_param(searchParams,"checks",32); // Priority queue storing intermediate branches in the best-bin-first search Heap* heap = new Heap((int)size_); std::vector checked(size_,false); int checks = 0; for (int i=0; ipopMin(branch) && (checks BranchSt; void save_tree(FILE* stream, NodePtr node, int num) { save_value(stream, *node); if (node->childs==NULL) { int indices_offset = (int)(node->indices - indices[num]); save_value(stream, indices_offset); } else { for(int i=0; ichilds[i], num); } } } void load_tree(FILE* stream, NodePtr& node, int num) { node = pool.allocate(); load_value(stream, *node); if (node->childs==NULL) { int indices_offset; load_value(stream, indices_offset); node->indices = indices[num] + indices_offset; } else { node->childs = pool.allocate(branching_); for(int i=0; ichilds[i], num); } } } void computeLabels(int* dsindices, int indices_length, int* centers, int centers_length, int* labels, DistanceType& cost) { cost = 0; for (int i=0; inew_dist) { labels[i] = j; dist = new_dist; } } cost += dist; } } /** * The method responsible with actually doing the recursive hierarchical * clustering * * Params: * node = the node to cluster * indices = indices of the points belonging to the current node * branching = the branching factor to use in the clustering * * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) */ void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level) { node->size = indices_length; node->level = level; if (indices_length < leaf_size_) { // leaf node node->indices = dsindices; std::sort(node->indices,node->indices+indices_length); node->childs = NULL; return; } std::vector centers(branching); std::vector labels(indices_length); int centers_length; (this->*chooseCenters)(branching, dsindices, indices_length, ¢ers[0], centers_length); if (centers_lengthindices = dsindices; std::sort(node->indices,node->indices+indices_length); node->childs = NULL; return; } // assign points to clusters DistanceType cost; computeLabels(dsindices, indices_length, ¢ers[0], centers_length, &labels[0], cost); node->childs = pool.allocate(branching); int start = 0; int end = start; for (int i=0; ichilds[i] = pool.allocate(); node->childs[i]->pivot = centers[i]; node->childs[i]->indices = NULL; computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1); start=end; } } /** * Performs one descent in the hierarchical k-means tree. The branches not * visited are stored in a priority queue. * * Params: * node = node to explore * result = container for the k-nearest neighbors found * vec = query points * checks = how many points in the dataset have been checked so far * maxChecks = maximum dataset points to checks */ void findNN(NodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, Heap* heap, std::vector& checked) { if (node->childs==NULL) { if (checks>=maxChecks) { if (result.full()) return; } for (int i=0; isize; ++i) { int index = node->indices[i]; if (!checked[index]) { DistanceType dist = distance(dataset[index], vec, veclen_); result.addPoint(dist, index); checked[index] = true; ++checks; } } } else { DistanceType* domain_distances = new DistanceType[branching_]; int best_index = 0; domain_distances[best_index] = distance(vec, dataset[node->childs[best_index]->pivot], veclen_); for (int i=1; ichilds[i]->pivot], veclen_); if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); } } delete[] domain_distances; findNN(node->childs[best_index],result,vec, checks, maxChecks, heap, checked); } } private: /** * The dataset used by this index */ const Matrix dataset; /** * Parameters used by this index */ IndexParams params; /** * Number of features in the dataset. */ size_t size_; /** * Length of each feature. */ size_t veclen_; /** * The root node in the tree. */ NodePtr* root; /** * Array of indices to vectors in the dataset. */ int** indices; /** * The distance */ Distance distance; /** * Pooled memory allocator. * * Using a pooled memory allocator is more efficient * than allocating memory directly when there is a large * number small of memory allocations. */ PooledAllocator pool; /** * Memory occupied by the index. */ int memoryCounter; /** index parameters */ int branching_; int trees_; flann_centers_init_t centers_init_; int leaf_size_; }; } #endif /* OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/index_testing.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_INDEX_TESTING_H_ #define OPENCV_FLANN_INDEX_TESTING_H_ #include #include #include #include "matrix.h" #include "nn_index.h" #include "result_set.h" #include "logger.h" #include "timer.h" namespace cvflann { inline int countCorrectMatches(int* neighbors, int* groundTruth, int n) { int count = 0; for (int i=0; i typename Distance::ResultType computeDistanceRaport(const Matrix& inputData, typename Distance::ElementType* target, int* neighbors, int* groundTruth, int veclen, int n, const Distance& distance) { typedef typename Distance::ResultType DistanceType; DistanceType ret = 0; for (int i=0; i float search_with_ground_truth(NNIndex& index, const Matrix& inputData, const Matrix& testData, const Matrix& matches, int nn, int checks, float& time, typename Distance::ResultType& dist, const Distance& distance, int skipMatches) { typedef typename Distance::ResultType DistanceType; if (matches.cols resultSet(nn+skipMatches); SearchParams searchParams(checks); std::vector indices(nn+skipMatches); std::vector dists(nn+skipMatches); int* neighbors = &indices[skipMatches]; int correct = 0; DistanceType distR = 0; StartStopTimer t; int repeats = 0; while (t.value<0.2) { repeats++; t.start(); correct = 0; distR = 0; for (size_t i = 0; i < testData.rows; i++) { resultSet.init(&indices[0], &dists[0]); index.findNeighbors(resultSet, testData[i], searchParams); correct += countCorrectMatches(neighbors,matches[i], nn); distR += computeDistanceRaport(inputData, testData[i], neighbors, matches[i], (int)testData.cols, nn, distance); } t.stop(); } time = float(t.value/repeats); float precicion = (float)correct/(nn*testData.rows); dist = distR/(testData.rows*nn); Logger::info("%8d %10.4g %10.5g %10.5g %10.5g\n", checks, precicion, time, 1000.0 * time / testData.rows, dist); return precicion; } template float test_index_checks(NNIndex& index, const Matrix& inputData, const Matrix& testData, const Matrix& matches, int checks, float& precision, const Distance& distance, int nn = 1, int skipMatches = 0) { typedef typename Distance::ResultType DistanceType; Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); Logger::info("---------------------------------------------------------\n"); float time = 0; DistanceType dist = 0; precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, distance, skipMatches); return time; } template float test_index_precision(NNIndex& index, const Matrix& inputData, const Matrix& testData, const Matrix& matches, float precision, int& checks, const Distance& distance, int nn = 1, int skipMatches = 0) { typedef typename Distance::ResultType DistanceType; const float SEARCH_EPS = 0.001f; Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); Logger::info("---------------------------------------------------------\n"); int c2 = 1; float p2; int c1 = 1; //float p1; float time; DistanceType dist; p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); if (p2>precision) { Logger::info("Got as close as I can\n"); checks = c2; return time; } while (p2SEARCH_EPS) { Logger::info("Start linear estimation\n"); // after we got to values in the vecinity of the desired precision // use linear approximation get a better estimation cx = (c1+c2)/2; realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); while (fabs(realPrecision-precision)>SEARCH_EPS) { if (realPrecision void test_index_precisions(NNIndex& index, const Matrix& inputData, const Matrix& testData, const Matrix& matches, float* precisions, int precisions_length, const Distance& distance, int nn = 1, int skipMatches = 0, float maxTime = 0) { typedef typename Distance::ResultType DistanceType; const float SEARCH_EPS = 0.001; // make sure precisions array is sorted std::sort(precisions, precisions+precisions_length); int pindex = 0; float precision = precisions[pindex]; Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); Logger::info("---------------------------------------------------------\n"); int c2 = 1; float p2; int c1 = 1; float p1; float time; DistanceType dist; p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); // if precision for 1 run down the tree is already // better then some of the requested precisions, then // skip those while (precisions[pindex] 0)&&(time > maxTime)&&(p2SEARCH_EPS) { Logger::info("Start linear estimation\n"); // after we got to values in the vecinity of the desired precision // use linear approximation get a better estimation cx = (c1+c2)/2; realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); while (fabs(realPrecision-precision)>SEARCH_EPS) { if (realPrecision #include #include #include #include "general.h" #include "nn_index.h" #include "dynamic_bitset.h" #include "matrix.h" #include "result_set.h" #include "heap.h" #include "allocator.h" #include "random.h" #include "saving.h" namespace cvflann { struct KDTreeIndexParams : public IndexParams { KDTreeIndexParams(int trees = 4) { (*this)["algorithm"] = FLANN_INDEX_KDTREE; (*this)["trees"] = trees; } }; /** * Randomized kd-tree index * * Contains the k-d trees and other information for indexing a set of points * for nearest-neighbor matching. */ template class KDTreeIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; /** * KDTree constructor * * Params: * inputData = dataset with the input features * params = parameters passed to the kdtree algorithm */ KDTreeIndex(const Matrix& inputData, const IndexParams& params = KDTreeIndexParams(), Distance d = Distance() ) : dataset_(inputData), index_params_(params), distance_(d) { size_ = dataset_.rows; veclen_ = dataset_.cols; trees_ = get_param(index_params_,"trees",4); tree_roots_ = new NodePtr[trees_]; // Create a permutable array of indices to the input vectors. vind_.resize(size_); for (size_t i = 0; i < size_; ++i) { vind_[i] = int(i); } mean_ = new DistanceType[veclen_]; var_ = new DistanceType[veclen_]; } KDTreeIndex(const KDTreeIndex&); KDTreeIndex& operator=(const KDTreeIndex&); /** * Standard destructor */ ~KDTreeIndex() { if (tree_roots_!=NULL) { delete[] tree_roots_; } delete[] mean_; delete[] var_; } /** * Builds the index */ void buildIndex() { /* Construct the randomized trees. */ for (int i = 0; i < trees_; i++) { /* Randomize the order of vectors to allow for unbiased sampling. */ std::random_shuffle(vind_.begin(), vind_.end()); tree_roots_[i] = divideTree(&vind_[0], int(size_) ); } } flann_algorithm_t getType() const { return FLANN_INDEX_KDTREE; } void saveIndex(FILE* stream) { save_value(stream, trees_); for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) { int maxChecks = get_param(searchParams,"checks", 32); float epsError = 1+get_param(searchParams,"eps",0.0f); if (maxChecks==FLANN_CHECKS_UNLIMITED) { getExactNeighbors(result, vec, epsError); } else { getNeighbors(result, vec, maxChecks, epsError); } } IndexParams getParameters() const { return index_params_; } private: /*--------------------- Internal Data Structures --------------------------*/ struct Node { /** * Dimension used for subdivision. */ int divfeat; /** * The values used for subdivision. */ DistanceType divval; /** * The child nodes. */ Node* child1, * child2; }; typedef Node* NodePtr; typedef BranchStruct BranchSt; typedef BranchSt* Branch; void save_tree(FILE* stream, NodePtr tree) { save_value(stream, *tree); if (tree->child1!=NULL) { save_tree(stream, tree->child1); } if (tree->child2!=NULL) { save_tree(stream, tree->child2); } } void load_tree(FILE* stream, NodePtr& tree) { tree = pool_.allocate(); load_value(stream, *tree); if (tree->child1!=NULL) { load_tree(stream, tree->child1); } if (tree->child2!=NULL) { load_tree(stream, tree->child2); } } /** * Create a tree node that subdivides the list of vecs from vind[first] * to vind[last]. The routine is called recursively on each sublist. * Place a pointer to this new tree node in the location pTree. * * Params: pTree = the new node to create * first = index of the first vector * last = index of the last vector */ NodePtr divideTree(int* ind, int count) { NodePtr node = pool_.allocate(); // allocate memory /* If too few exemplars remain, then make this a leaf node. */ if ( count == 1) { node->child1 = node->child2 = NULL; /* Mark as leaf node. */ node->divfeat = *ind; /* Store index of this vec. */ } else { int idx; int cutfeat; DistanceType cutval; meanSplit(ind, count, idx, cutfeat, cutval); node->divfeat = cutfeat; node->divval = cutval; node->child1 = divideTree(ind, idx); node->child2 = divideTree(ind+idx, count-idx); } return node; } /** * Choose which feature to use in order to subdivide this set of vectors. * Make a random choice among those with the highest variance, and use * its variance as the threshold value. */ void meanSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval) { memset(mean_,0,veclen_*sizeof(DistanceType)); memset(var_,0,veclen_*sizeof(DistanceType)); /* Compute mean values. Only the first SAMPLE_MEAN values need to be sampled to get a good estimate. */ int cnt = std::min((int)SAMPLE_MEAN+1, count); for (int j = 0; j < cnt; ++j) { ElementType* v = dataset_[ind[j]]; for (size_t k=0; kcount/2) index = lim1; else if (lim2 v[topind[num-1]])) { /* Put this element at end of topind. */ if (num < RAND_DIM) { topind[num++] = i; /* Add to list. */ } else { topind[num-1] = i; /* Replace last element. */ } /* Bubble end value down to right location by repeated swapping. */ int j = num - 1; while (j > 0 && v[topind[j]] > v[topind[j-1]]) { std::swap(topind[j], topind[j-1]); --j; } } } /* Select a random integer in range [0,num-1], and return that index. */ int rnd = rand_int(num); return (int)topind[rnd]; } /** * Subdivide the list of points by a plane perpendicular on axe corresponding * to the 'cutfeat' dimension at 'cutval' position. * * On return: * dataset[ind[0..lim1-1]][cutfeat]cutval */ void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) { /* Move vector indices for left subtree to front of list. */ int left = 0; int right = count-1; for (;; ) { while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; if (left>right) break; std::swap(ind[left], ind[right]); ++left; --right; } lim1 = left; right = count-1; for (;; ) { while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; if (left>right) break; std::swap(ind[left], ind[right]); ++left; --right; } lim2 = left; } /** * Performs an exact nearest neighbor search. The exact search performs a full * traversal of the tree. */ void getExactNeighbors(ResultSet& result, const ElementType* vec, float epsError) { // checkID -= 1; /* Set a different unique ID for each search. */ if (trees_ > 1) { fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search"); } if (trees_>0) { searchLevelExact(result, vec, tree_roots_[0], 0.0, epsError); } assert(result.full()); } /** * Performs the approximate nearest-neighbor search. The search is approximate * because the tree traversal is abandoned after a given number of descends in * the tree. */ void getNeighbors(ResultSet& result, const ElementType* vec, int maxCheck, float epsError) { int i; BranchSt branch; int checkCount = 0; Heap* heap = new Heap((int)size_); DynamicBitset checked(size_); /* Search once through each tree down to root. */ for (i = 0; i < trees_; ++i) { searchLevel(result, vec, tree_roots_[i], 0, checkCount, maxCheck, epsError, heap, checked); } /* Keep searching other branches from heap until finished. */ while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) { searchLevel(result, vec, branch.node, branch.mindist, checkCount, maxCheck, epsError, heap, checked); } delete heap; assert(result.full()); } /** * Search starting from a given node of the tree. Based on any mismatches at * higher levels, all exemplars below this level must have a distance of * at least "mindistsq". */ void searchLevel(ResultSet& result_set, const ElementType* vec, NodePtr node, DistanceType mindist, int& checkCount, int maxCheck, float epsError, Heap* heap, DynamicBitset& checked) { if (result_set.worstDist()child1 == NULL)&&(node->child2 == NULL)) { /* Do not check same node more than once when searching multiple trees. Once a vector is checked, we set its location in vind to the current checkID. */ int index = node->divfeat; if ( checked.test(index) || ((checkCount>=maxCheck)&& result_set.full()) ) return; checked.set(index); checkCount++; DistanceType dist = distance_(dataset_[index], vec, veclen_); result_set.addPoint(dist,index); return; } /* Which child branch should be taken first? */ ElementType val = vec[node->divfeat]; DistanceType diff = val - node->divval; NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; /* Create a branch record for the branch not taken. Add distance of this feature boundary (we don't attempt to correct for any use of this feature in a parent node, which is unlikely to happen and would have only a small effect). Don't bother adding more branches to heap after halfway point, as cost of adding exceeds their value. */ DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); // if (2 * checkCount < maxCheck || !result.full()) { if ((new_distsq*epsError < result_set.worstDist())|| !result_set.full()) { heap->insert( BranchSt(otherChild, new_distsq) ); } /* Call recursively to search next level down. */ searchLevel(result_set, vec, bestChild, mindist, checkCount, maxCheck, epsError, heap, checked); } /** * Performs an exact search in the tree starting from a node. */ void searchLevelExact(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindist, const float epsError) { /* If this is a leaf node, then do check and return. */ if ((node->child1 == NULL)&&(node->child2 == NULL)) { int index = node->divfeat; DistanceType dist = distance_(dataset_[index], vec, veclen_); result_set.addPoint(dist,index); return; } /* Which child branch should be taken first? */ ElementType val = vec[node->divfeat]; DistanceType diff = val - node->divval; NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; /* Create a branch record for the branch not taken. Add distance of this feature boundary (we don't attempt to correct for any use of this feature in a parent node, which is unlikely to happen and would have only a small effect). Don't bother adding more branches to heap after halfway point, as cost of adding exceeds their value. */ DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); /* Call recursively to search next level down. */ searchLevelExact(result_set, vec, bestChild, mindist, epsError); if (new_distsq*epsError<=result_set.worstDist()) { searchLevelExact(result_set, vec, otherChild, new_distsq, epsError); } } private: enum { /** * To improve efficiency, only SAMPLE_MEAN random values are used to * compute the mean and variance at each level when building a tree. * A value of 100 seems to perform as well as using all values. */ SAMPLE_MEAN = 100, /** * Top random dimensions to consider * * When creating random trees, the dimension on which to subdivide is * selected at random from among the top RAND_DIM dimensions with the * highest variance. A value of 5 works well. */ RAND_DIM=5 }; /** * Number of randomized trees that are used */ int trees_; /** * Array of indices to vectors in the dataset. */ std::vector vind_; /** * The dataset used by this index */ const Matrix dataset_; IndexParams index_params_; size_t size_; size_t veclen_; DistanceType* mean_; DistanceType* var_; /** * Array of k-d trees used to find neighbours. */ NodePtr* tree_roots_; /** * Pooled memory allocator. * * Using a pooled memory allocator is more efficient * than allocating memory directly when there is a large * number small of memory allocations. */ PooledAllocator pool_; Distance distance_; }; // class KDTreeForest } #endif //OPENCV_FLANN_KDTREE_INDEX_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/kdtree_single_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ #define OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ #include #include #include #include #include "general.h" #include "nn_index.h" #include "matrix.h" #include "result_set.h" #include "heap.h" #include "allocator.h" #include "random.h" #include "saving.h" namespace cvflann { struct KDTreeSingleIndexParams : public IndexParams { KDTreeSingleIndexParams(int leaf_max_size = 10, bool reorder = true, int dim = -1) { (*this)["algorithm"] = FLANN_INDEX_KDTREE_SINGLE; (*this)["leaf_max_size"] = leaf_max_size; (*this)["reorder"] = reorder; (*this)["dim"] = dim; } }; /** * Randomized kd-tree index * * Contains the k-d trees and other information for indexing a set of points * for nearest-neighbor matching. */ template class KDTreeSingleIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; /** * KDTree constructor * * Params: * inputData = dataset with the input features * params = parameters passed to the kdtree algorithm */ KDTreeSingleIndex(const Matrix& inputData, const IndexParams& params = KDTreeSingleIndexParams(), Distance d = Distance() ) : dataset_(inputData), index_params_(params), distance_(d) { size_ = dataset_.rows; dim_ = dataset_.cols; int dim_param = get_param(params,"dim",-1); if (dim_param>0) dim_ = dim_param; leaf_max_size_ = get_param(params,"leaf_max_size",10); reorder_ = get_param(params,"reorder",true); // Create a permutable array of indices to the input vectors. vind_.resize(size_); for (size_t i = 0; i < size_; i++) { vind_[i] = (int)i; } } KDTreeSingleIndex(const KDTreeSingleIndex&); KDTreeSingleIndex& operator=(const KDTreeSingleIndex&); /** * Standard destructor */ ~KDTreeSingleIndex() { if (reorder_) delete[] data_.data; } /** * Builds the index */ void buildIndex() { computeBoundingBox(root_bbox_); root_node_ = divideTree(0, (int)size_, root_bbox_ ); // construct the tree if (reorder_) { delete[] data_.data; data_ = cvflann::Matrix(new ElementType[size_*dim_], size_, dim_); for (size_t i=0; i& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) { assert(queries.cols == veclen()); assert(indices.rows >= queries.rows); assert(dists.rows >= queries.rows); assert(int(indices.cols) >= knn); assert(int(dists.cols) >= knn); KNNSimpleResultSet resultSet(knn); for (size_t i = 0; i < queries.rows; i++) { resultSet.init(indices[i], dists[i]); findNeighbors(resultSet, queries[i], params); } } IndexParams getParameters() const { return index_params_; } /** * Find set of nearest neighbors to vec. Their indices are stored inside * the result object. * * Params: * result = the result object in which the indices of the nearest-neighbors are stored * vec = the vector for which to search the nearest neighbors * maxCheck = the maximum number of restarts (in a best-bin-first manner) */ void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) { float epsError = 1+get_param(searchParams,"eps",0.0f); std::vector dists(dim_,0); DistanceType distsq = computeInitialDistances(vec, dists); searchLevel(result, vec, root_node_, distsq, dists, epsError); } private: /*--------------------- Internal Data Structures --------------------------*/ struct Node { /** * Indices of points in leaf node */ int left, right; /** * Dimension used for subdivision. */ int divfeat; /** * The values used for subdivision. */ DistanceType divlow, divhigh; /** * The child nodes. */ Node* child1, * child2; }; typedef Node* NodePtr; struct Interval { DistanceType low, high; }; typedef std::vector BoundingBox; typedef BranchStruct BranchSt; typedef BranchSt* Branch; void save_tree(FILE* stream, NodePtr tree) { save_value(stream, *tree); if (tree->child1!=NULL) { save_tree(stream, tree->child1); } if (tree->child2!=NULL) { save_tree(stream, tree->child2); } } void load_tree(FILE* stream, NodePtr& tree) { tree = pool_.allocate(); load_value(stream, *tree); if (tree->child1!=NULL) { load_tree(stream, tree->child1); } if (tree->child2!=NULL) { load_tree(stream, tree->child2); } } void computeBoundingBox(BoundingBox& bbox) { bbox.resize(dim_); for (size_t i=0; ibbox[i].high) bbox[i].high = (DistanceType)dataset_[k][i]; } } } /** * Create a tree node that subdivides the list of vecs from vind[first] * to vind[last]. The routine is called recursively on each sublist. * Place a pointer to this new tree node in the location pTree. * * Params: pTree = the new node to create * first = index of the first vector * last = index of the last vector */ NodePtr divideTree(int left, int right, BoundingBox& bbox) { NodePtr node = pool_.allocate(); // allocate memory /* If too few exemplars remain, then make this a leaf node. */ if ( (right-left) <= leaf_max_size_) { node->child1 = node->child2 = NULL; /* Mark as leaf node. */ node->left = left; node->right = right; // compute bounding-box of leaf points for (size_t i=0; idataset_[vind_[k]][i]) bbox[i].low=(DistanceType)dataset_[vind_[k]][i]; if (bbox[i].highdivfeat = cutfeat; BoundingBox left_bbox(bbox); left_bbox[cutfeat].high = cutval; node->child1 = divideTree(left, left+idx, left_bbox); BoundingBox right_bbox(bbox); right_bbox[cutfeat].low = cutval; node->child2 = divideTree(left+idx, right, right_bbox); node->divlow = left_bbox[cutfeat].high; node->divhigh = right_bbox[cutfeat].low; for (size_t i=0; imax_elem) max_elem = val; } } void middleSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox) { // find the largest span from the approximate bounding box ElementType max_span = bbox[0].high-bbox[0].low; cutfeat = 0; cutval = (bbox[0].high+bbox[0].low)/2; for (size_t i=1; imax_span) { max_span = span; cutfeat = i; cutval = (bbox[i].high+bbox[i].low)/2; } } // compute exact span on the found dimension ElementType min_elem, max_elem; computeMinMax(ind, count, cutfeat, min_elem, max_elem); cutval = (min_elem+max_elem)/2; max_span = max_elem - min_elem; // check if a dimension of a largest span exists size_t k = cutfeat; for (size_t i=0; imax_span) { computeMinMax(ind, count, i, min_elem, max_elem); span = max_elem - min_elem; if (span>max_span) { max_span = span; cutfeat = i; cutval = (min_elem+max_elem)/2; } } } int lim1, lim2; planeSplit(ind, count, cutfeat, cutval, lim1, lim2); if (lim1>count/2) index = lim1; else if (lim2max_span) { max_span = span; } } DistanceType max_spread = -1; cutfeat = 0; for (size_t i=0; i(DistanceType)((1-EPS)*max_span)) { ElementType min_elem, max_elem; computeMinMax(ind, count, cutfeat, min_elem, max_elem); DistanceType spread = (DistanceType)(max_elem-min_elem); if (spread>max_spread) { cutfeat = (int)i; max_spread = spread; } } } // split in the middle DistanceType split_val = (bbox[cutfeat].low+bbox[cutfeat].high)/2; ElementType min_elem, max_elem; computeMinMax(ind, count, cutfeat, min_elem, max_elem); if (split_valmax_elem) cutval = (DistanceType)max_elem; else cutval = split_val; int lim1, lim2; planeSplit(ind, count, cutfeat, cutval, lim1, lim2); if (lim1>count/2) index = lim1; else if (lim2cutval */ void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) { /* Move vector indices for left subtree to front of list. */ int left = 0; int right = count-1; for (;; ) { while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; if (left>right) break; std::swap(ind[left], ind[right]); ++left; --right; } /* If either list is empty, it means that all remaining features * are identical. Split in the middle to maintain a balanced tree. */ lim1 = left; right = count-1; for (;; ) { while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; if (left>right) break; std::swap(ind[left], ind[right]); ++left; --right; } lim2 = left; } DistanceType computeInitialDistances(const ElementType* vec, std::vector& dists) { DistanceType distsq = 0.0; for (size_t i = 0; i < dim_; ++i) { if (vec[i] < root_bbox_[i].low) { dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].low, (int)i); distsq += dists[i]; } if (vec[i] > root_bbox_[i].high) { dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].high, (int)i); distsq += dists[i]; } } return distsq; } /** * Performs an exact search in the tree starting from a node. */ void searchLevel(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq, std::vector& dists, const float epsError) { /* If this is a leaf node, then do check and return. */ if ((node->child1 == NULL)&&(node->child2 == NULL)) { DistanceType worst_dist = result_set.worstDist(); for (int i=node->left; iright; ++i) { int index = reorder_ ? i : vind_[i]; DistanceType dist = distance_(vec, data_[index], dim_, worst_dist); if (distdivfeat; ElementType val = vec[idx]; DistanceType diff1 = val - node->divlow; DistanceType diff2 = val - node->divhigh; NodePtr bestChild; NodePtr otherChild; DistanceType cut_dist; if ((diff1+diff2)<0) { bestChild = node->child1; otherChild = node->child2; cut_dist = distance_.accum_dist(val, node->divhigh, idx); } else { bestChild = node->child2; otherChild = node->child1; cut_dist = distance_.accum_dist( val, node->divlow, idx); } /* Call recursively to search next level down. */ searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); DistanceType dst = dists[idx]; mindistsq = mindistsq + cut_dist - dst; dists[idx] = cut_dist; if (mindistsq*epsError<=result_set.worstDist()) { searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); } dists[idx] = dst; } private: /** * The dataset used by this index */ const Matrix dataset_; IndexParams index_params_; int leaf_max_size_; bool reorder_; /** * Array of indices to vectors in the dataset. */ std::vector vind_; Matrix data_; size_t size_; size_t dim_; /** * Array of k-d trees used to find neighbours. */ NodePtr root_node_; BoundingBox root_bbox_; /** * Pooled memory allocator. * * Using a pooled memory allocator is more efficient * than allocating memory directly when there is a large * number small of memory allocations. */ PooledAllocator pool_; Distance distance_; }; // class KDTree } #endif //OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/kmeans_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_KMEANS_INDEX_H_ #define OPENCV_FLANN_KMEANS_INDEX_H_ #include #include #include #include #include #include "general.h" #include "nn_index.h" #include "dist.h" #include "matrix.h" #include "result_set.h" #include "heap.h" #include "allocator.h" #include "random.h" #include "saving.h" #include "logger.h" namespace cvflann { struct KMeansIndexParams : public IndexParams { KMeansIndexParams(int branching = 32, int iterations = 11, flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 ) { (*this)["algorithm"] = FLANN_INDEX_KMEANS; // branching factor (*this)["branching"] = branching; // max iterations to perform in one kmeans clustering (kmeans tree) (*this)["iterations"] = iterations; // algorithm used for picking the initial cluster centers for kmeans tree (*this)["centers_init"] = centers_init; // cluster boundary index. Used when searching the kmeans tree (*this)["cb_index"] = cb_index; } }; /** * Hierarchical kmeans index * * Contains a tree constructed through a hierarchical kmeans clustering * and other information for indexing a set of points for nearest-neighbour matching. */ template class KMeansIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&); /** * The function used for choosing the cluster centers. */ centersAlgFunction chooseCenters; /** * Chooses the initial centers in the k-means clustering in a random manner. * * Params: * k = number of centers * vecs = the dataset of points * indices = indices in the dataset * indices_length = length of indices vector * */ void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length) { UniqueRandom r(indices_length); int index; for (index=0; index=0 && rnd < n); centers[0] = indices[rnd]; int index; for (index=1; indexbest_val) { best_val = dist; best_index = j; } } if (best_index!=-1) { centers[index] = indices[best_index]; } else { break; } } centers_length = index; } /** * Chooses the initial centers in the k-means using the algorithm * proposed in the KMeans++ paper: * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding * * Implementation of this function was converted from the one provided in Arthur's code. * * Params: * k = number of centers * vecs = the dataset of points * indices = indices in the dataset * Returns: */ void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length) { int n = indices_length; double currentPot = 0; DistanceType* closestDistSq = new DistanceType[n]; // Choose one random center and set the closestDistSq values int index = rand_int(n); assert(index >=0 && index < n); centers[0] = indices[index]; for (int i = 0; i < n; i++) { closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); currentPot += closestDistSq[i]; } const int numLocalTries = 1; // Choose each center int centerCount; for (centerCount = 1; centerCount < k; centerCount++) { // Repeat several trials double bestNewPot = -1; int bestNewIndex = -1; for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { // Choose our center - have to be slightly careful to return a valid answer even accounting // for possible rounding errors double randVal = rand_double(currentPot); for (index = 0; index < n-1; index++) { if (randVal <= closestDistSq[index]) break; else randVal -= closestDistSq[index]; } // Compute the new potential double newPot = 0; for (int i = 0; i < n; i++) { DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); } // Store the best result if ((bestNewPot < 0)||(newPot < bestNewPot)) { bestNewPot = newPot; bestNewIndex = index; } } // Add the appropriate center centers[centerCount] = indices[bestNewIndex]; currentPot = bestNewPot; for (int i = 0; i < n; i++) { DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols); closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); } } centers_length = centerCount; delete[] closestDistSq; } public: flann_algorithm_t getType() const { return FLANN_INDEX_KMEANS; } class KMeansDistanceComputer : public cv::ParallelLoopBody { public: KMeansDistanceComputer(Distance _distance, const Matrix& _dataset, const int _branching, const int* _indices, const Matrix& _dcenters, const size_t _veclen, int* _count, int* _belongs_to, std::vector& _radiuses, bool& _converged, cv::Mutex& _mtx) : distance(_distance) , dataset(_dataset) , branching(_branching) , indices(_indices) , dcenters(_dcenters) , veclen(_veclen) , count(_count) , belongs_to(_belongs_to) , radiuses(_radiuses) , converged(_converged) , mtx(_mtx) { } void operator()(const cv::Range& range) const { const int begin = range.start; const int end = range.end; for( int i = begin; inew_sq_dist) { new_centroid = j; sq_dist = new_sq_dist; } } if (sq_dist > radiuses[new_centroid]) { radiuses[new_centroid] = sq_dist; } if (new_centroid != belongs_to[i]) { count[belongs_to[i]]--; count[new_centroid]++; belongs_to[i] = new_centroid; mtx.lock(); converged = false; mtx.unlock(); } } } private: Distance distance; const Matrix& dataset; const int branching; const int* indices; const Matrix& dcenters; const size_t veclen; int* count; int* belongs_to; std::vector& radiuses; bool& converged; cv::Mutex& mtx; KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; } }; /** * Index constructor * * Params: * inputData = dataset with the input features * params = parameters passed to the hierarchical k-means algorithm */ KMeansIndex(const Matrix& inputData, const IndexParams& params = KMeansIndexParams(), Distance d = Distance()) : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d) { memoryCounter_ = 0; size_ = dataset_.rows; veclen_ = dataset_.cols; branching_ = get_param(params,"branching",32); iterations_ = get_param(params,"iterations",11); if (iterations_<0) { iterations_ = (std::numeric_limits::max)(); } centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM); if (centers_init_==FLANN_CENTERS_RANDOM) { chooseCenters = &KMeansIndex::chooseCentersRandom; } else if (centers_init_==FLANN_CENTERS_GONZALES) { chooseCenters = &KMeansIndex::chooseCentersGonzales; } else if (centers_init_==FLANN_CENTERS_KMEANSPP) { chooseCenters = &KMeansIndex::chooseCentersKMeanspp; } else { throw FLANNException("Unknown algorithm for choosing initial centers."); } cb_index_ = 0.4f; } KMeansIndex(const KMeansIndex&); KMeansIndex& operator=(const KMeansIndex&); /** * Index destructor. * * Release the memory used by the index. */ virtual ~KMeansIndex() { if (root_ != NULL) { free_centers(root_); } if (indices_!=NULL) { delete[] indices_; } } /** * Returns size of index. */ size_t size() const { return size_; } /** * Returns the length of an index feature. */ size_t veclen() const { return veclen_; } void set_cb_index( float index) { cb_index_ = index; } /** * Computes the inde memory usage * Returns: memory used by the index */ int usedMemory() const { return pool_.usedMemory+pool_.wastedMemory+memoryCounter_; } /** * Builds the index */ void buildIndex() { if (branching_<2) { throw FLANNException("Branching factor must be at least 2"); } indices_ = new int[size_]; for (size_t i=0; i(); std::memset(root_, 0, sizeof(KMeansNode)); computeNodeStatistics(root_, indices_, (int)size_); computeClustering(root_, indices_, (int)size_, branching_,0); } void saveIndex(FILE* stream) { save_value(stream, branching_); save_value(stream, iterations_); save_value(stream, memoryCounter_); save_value(stream, cb_index_); save_value(stream, *indices_, (int)size_); save_tree(stream, root_); } void loadIndex(FILE* stream) { load_value(stream, branching_); load_value(stream, iterations_); load_value(stream, memoryCounter_); load_value(stream, cb_index_); if (indices_!=NULL) { delete[] indices_; } indices_ = new int[size_]; load_value(stream, *indices_, size_); if (root_!=NULL) { free_centers(root_); } load_tree(stream, root_); index_params_["algorithm"] = getType(); index_params_["branching"] = branching_; index_params_["iterations"] = iterations_; index_params_["centers_init"] = centers_init_; index_params_["cb_index"] = cb_index_; } /** * Find set of nearest neighbors to vec. Their indices are stored inside * the result object. * * Params: * result = the result object in which the indices of the nearest-neighbors are stored * vec = the vector for which to search the nearest neighbors * searchParams = parameters that influence the search algorithm (checks, cb_index) */ void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) { int maxChecks = get_param(searchParams,"checks",32); if (maxChecks==FLANN_CHECKS_UNLIMITED) { findExactNN(root_, result, vec); } else { // Priority queue storing intermediate branches in the best-bin-first search Heap* heap = new Heap((int)size_); int checks = 0; findNN(root_, result, vec, checks, maxChecks, heap); BranchSt branch; while (heap->popMin(branch) && (checks& centers) { int numClusters = centers.rows; if (numClusters<1) { throw FLANNException("Number of clusters must be at least 1"); } DistanceType variance; KMeansNodePtr* clusters = new KMeansNodePtr[numClusters]; int clusterCount = getMinVarianceClusters(root_, clusters, numClusters, variance); Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount); for (int i=0; ipivot; for (size_t j=0; j BranchSt; void save_tree(FILE* stream, KMeansNodePtr node) { save_value(stream, *node); save_value(stream, *(node->pivot), (int)veclen_); if (node->childs==NULL) { int indices_offset = (int)(node->indices - indices_); save_value(stream, indices_offset); } else { for(int i=0; ichilds[i]); } } } void load_tree(FILE* stream, KMeansNodePtr& node) { node = pool_.allocate(); load_value(stream, *node); node->pivot = new DistanceType[veclen_]; load_value(stream, *(node->pivot), (int)veclen_); if (node->childs==NULL) { int indices_offset; load_value(stream, indices_offset); node->indices = indices_ + indices_offset; } else { node->childs = pool_.allocate(branching_); for(int i=0; ichilds[i]); } } } /** * Helper function */ void free_centers(KMeansNodePtr node) { delete[] node->pivot; if (node->childs!=NULL) { for (int k=0; kchilds[k]); } } } /** * Computes the statistics of a node (mean, radius, variance). * * Params: * node = the node to use * indices = the indices of the points belonging to the node */ void computeNodeStatistics(KMeansNodePtr node, int* indices, int indices_length) { DistanceType radius = 0; DistanceType variance = 0; DistanceType* mean = new DistanceType[veclen_]; memoryCounter_ += int(veclen_*sizeof(DistanceType)); memset(mean,0,veclen_*sizeof(DistanceType)); for (size_t i=0; i(), veclen_); } for (size_t j=0; j(), veclen_); DistanceType tmp = 0; for (int i=0; iradius) { radius = tmp; } } node->variance = variance; node->radius = radius; node->pivot = mean; } /** * The method responsible with actually doing the recursive hierarchical * clustering * * Params: * node = the node to cluster * indices = indices of the points belonging to the current node * branching = the branching factor to use in the clustering * * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) */ void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level) { node->size = indices_length; node->level = level; if (indices_length < branching) { node->indices = indices; std::sort(node->indices,node->indices+indices_length); node->childs = NULL; return; } cv::AutoBuffer centers_idx_buf(branching); int* centers_idx = (int*)centers_idx_buf; int centers_length; (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length); if (centers_lengthindices = indices; std::sort(node->indices,node->indices+indices_length); node->childs = NULL; return; } cv::AutoBuffer dcenters_buf(branching*veclen_); Matrix dcenters((double*)dcenters_buf,branching,veclen_); for (int i=0; i radiuses(branching); cv::AutoBuffer count_buf(branching); int* count = (int*)count_buf; for (int i=0; i belongs_to_buf(indices_length); int* belongs_to = (int*)belongs_to_buf; for (int i=0; inew_sq_dist) { belongs_to[i] = j; sq_dist = new_sq_dist; } } if (sq_dist>radiuses[belongs_to[i]]) { radiuses[belongs_to[i]] = sq_dist; } count[belongs_to[i]]++; } bool converged = false; int iteration = 0; while (!converged && iterationchilds = pool_.allocate(branching); int start = 0; int end = start; for (int c=0; c(), veclen_); variance += d; mean_radius += sqrt(d); std::swap(indices[i],indices[end]); std::swap(belongs_to[i],belongs_to[end]); end++; } } variance /= s; mean_radius /= s; variance -= distance_(centers[c], ZeroIterator(), veclen_); node->childs[c] = pool_.allocate(); std::memset(node->childs[c], 0, sizeof(KMeansNode)); node->childs[c]->radius = radiuses[c]; node->childs[c]->pivot = centers[c]; node->childs[c]->variance = variance; node->childs[c]->mean_radius = mean_radius; computeClustering(node->childs[c],indices+start, end-start, branching, level+1); start=end; } } /** * Performs one descent in the hierarchical k-means tree. The branches not * visited are stored in a priority queue. * * Params: * node = node to explore * result = container for the k-nearest neighbors found * vec = query points * checks = how many points in the dataset have been checked so far * maxChecks = maximum dataset points to checks */ void findNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, Heap* heap) { // Ignore those clusters that are too far away { DistanceType bsq = distance_(vec, node->pivot, veclen_); DistanceType rsq = node->radius; DistanceType wsq = result.worstDist(); DistanceType val = bsq-rsq-wsq; DistanceType val2 = val*val-4*rsq*wsq; //if (val>0) { if ((val>0)&&(val2>0)) { return; } } if (node->childs==NULL) { if (checks>=maxChecks) { if (result.full()) return; } checks += node->size; for (int i=0; isize; ++i) { int index = node->indices[i]; DistanceType dist = distance_(dataset_[index], vec, veclen_); result.addPoint(dist, index); } } else { DistanceType* domain_distances = new DistanceType[branching_]; int closest_center = exploreNodeBranches(node, vec, domain_distances, heap); delete[] domain_distances; findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap); } } /** * Helper function that computes the nearest childs of a node to a given query point. * Params: * node = the node * q = the query point * distances = array with the distances to each child node. * Returns: */ int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, Heap* heap) { int best_index = 0; domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_); for (int i=1; ichilds[i]->pivot, veclen_); if (domain_distances[i]childs[best_index]->pivot; for (int i=0; ichilds[i]->variance; // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q); // if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); } } return best_index; } /** * Function the performs exact nearest neighbor search by traversing the entire tree. */ void findExactNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec) { // Ignore those clusters that are too far away { DistanceType bsq = distance_(vec, node->pivot, veclen_); DistanceType rsq = node->radius; DistanceType wsq = result.worstDist(); DistanceType val = bsq-rsq-wsq; DistanceType val2 = val*val-4*rsq*wsq; // if (val>0) { if ((val>0)&&(val2>0)) { return; } } if (node->childs==NULL) { for (int i=0; isize; ++i) { int index = node->indices[i]; DistanceType dist = distance_(dataset_[index], vec, veclen_); result.addPoint(dist, index); } } else { int* sort_indices = new int[branching_]; getCenterOrdering(node, vec, sort_indices); for (int i=0; ichilds[sort_indices[i]],result,vec); } delete[] sort_indices; } } /** * Helper function. * * I computes the order in which to traverse the child nodes of a particular node. */ void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices) { DistanceType* domain_distances = new DistanceType[branching_]; for (int i=0; ichilds[i]->pivot, veclen_); int j=0; while (domain_distances[j]j; --k) { domain_distances[k] = domain_distances[k-1]; sort_indices[k] = sort_indices[k-1]; } domain_distances[j] = dist; sort_indices[j] = i; } delete[] domain_distances; } /** * Method that computes the squared distance from the query point q * from inside region with center c to the border between this * region and the region with center p */ DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q) { DistanceType sum = 0; DistanceType sum2 = 0; for (int i=0; ivariance*root->size; while (clusterCount::max)(); int splitIndex = -1; for (int i=0; ichilds != NULL) { DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size; for (int j=0; jchilds[j]->variance*clusters[i]->childs[j]->size; } if (variance clusters_length) break; meanVariance = minVariance; // split node KMeansNodePtr toSplit = clusters[splitIndex]; clusters[splitIndex] = toSplit->childs[0]; for (int i=1; ichilds[i]; } } varianceValue = meanVariance/root->size; return clusterCount; } private: /** The branching factor used in the hierarchical k-means clustering */ int branching_; /** Maximum number of iterations to use when performing k-means clustering */ int iterations_; /** Algorithm for choosing the cluster centers */ flann_centers_init_t centers_init_; /** * Cluster border index. This is used in the tree search phase when determining * the closest cluster to explore next. A zero value takes into account only * the cluster centres, a value greater then zero also take into account the size * of the cluster. */ float cb_index_; /** * The dataset used by this index */ const Matrix dataset_; /** Index parameters */ IndexParams index_params_; /** * Number of features in the dataset. */ size_t size_; /** * Length of each feature. */ size_t veclen_; /** * The root node in the tree. */ KMeansNodePtr root_; /** * Array of indices to vectors in the dataset. */ int* indices_; /** * The distance */ Distance distance_; /** * Pooled memory allocator. */ PooledAllocator pool_; /** * Memory occupied by the index. */ int memoryCounter_; }; } #endif //OPENCV_FLANN_KMEANS_INDEX_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/linear_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_LINEAR_INDEX_H_ #define OPENCV_FLANN_LINEAR_INDEX_H_ #include "general.h" #include "nn_index.h" namespace cvflann { struct LinearIndexParams : public IndexParams { LinearIndexParams() { (* this)["algorithm"] = FLANN_INDEX_LINEAR; } }; template class LinearIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; LinearIndex(const Matrix& inputData, const IndexParams& params = LinearIndexParams(), Distance d = Distance()) : dataset_(inputData), index_params_(params), distance_(d) { } LinearIndex(const LinearIndex&); LinearIndex& operator=(const LinearIndex&); flann_algorithm_t getType() const { return FLANN_INDEX_LINEAR; } size_t size() const { return dataset_.rows; } size_t veclen() const { return dataset_.cols; } int usedMemory() const { return 0; } void buildIndex() { /* nothing to do here for linear search */ } void saveIndex(FILE*) { /* nothing to do here for linear search */ } void loadIndex(FILE*) { /* nothing to do here for linear search */ index_params_["algorithm"] = getType(); } void findNeighbors(ResultSet& resultSet, const ElementType* vec, const SearchParams& /*searchParams*/) { ElementType* data = dataset_.data; for (size_t i = 0; i < dataset_.rows; ++i, data += dataset_.cols) { DistanceType dist = distance_(data, vec, dataset_.cols); resultSet.addPoint(dist, (int)i); } } IndexParams getParameters() const { return index_params_; } private: /** The dataset */ const Matrix dataset_; /** Index parameters */ IndexParams index_params_; /** Index distance */ Distance distance_; }; } #endif // OPENCV_FLANN_LINEAR_INDEX_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/logger.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_LOGGER_H #define OPENCV_FLANN_LOGGER_H #include #include #include "defines.h" namespace cvflann { class Logger { Logger() : stream(stdout), logLevel(FLANN_LOG_WARN) {} ~Logger() { if ((stream!=NULL)&&(stream!=stdout)) { fclose(stream); } } static Logger& instance() { static Logger logger; return logger; } void _setDestination(const char* name) { if (name==NULL) { stream = stdout; } else { stream = fopen(name,"w"); if (stream == NULL) { stream = stdout; } } } int _log(int level, const char* fmt, va_list arglist) { if (level > logLevel ) return -1; int ret = vfprintf(stream, fmt, arglist); return ret; } public: /** * Sets the logging level. All messages with lower priority will be ignored. * @param level Logging level */ static void setLevel(int level) { instance().logLevel = level; } /** * Sets the logging destination * @param name Filename or NULL for console */ static void setDestination(const char* name) { instance()._setDestination(name); } /** * Print log message * @param level Log level * @param fmt Message format * @return */ static int log(int level, const char* fmt, ...) { va_list arglist; va_start(arglist, fmt); int ret = instance()._log(level,fmt,arglist); va_end(arglist); return ret; } #define LOG_METHOD(NAME,LEVEL) \ static int NAME(const char* fmt, ...) \ { \ va_list ap; \ va_start(ap, fmt); \ int ret = instance()._log(LEVEL, fmt, ap); \ va_end(ap); \ return ret; \ } LOG_METHOD(fatal, FLANN_LOG_FATAL) LOG_METHOD(error, FLANN_LOG_ERROR) LOG_METHOD(warn, FLANN_LOG_WARN) LOG_METHOD(info, FLANN_LOG_INFO) private: FILE* stream; int logLevel; }; } #endif //OPENCV_FLANN_LOGGER_H ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/lsh_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ /*********************************************************************** * Author: Vincent Rabaud *************************************************************************/ #ifndef OPENCV_FLANN_LSH_INDEX_H_ #define OPENCV_FLANN_LSH_INDEX_H_ #include #include #include #include #include #include "general.h" #include "nn_index.h" #include "matrix.h" #include "result_set.h" #include "heap.h" #include "lsh_table.h" #include "allocator.h" #include "random.h" #include "saving.h" namespace cvflann { struct LshIndexParams : public IndexParams { LshIndexParams(unsigned int table_number = 12, unsigned int key_size = 20, unsigned int multi_probe_level = 2) { (* this)["algorithm"] = FLANN_INDEX_LSH; // The number of hash tables to use (*this)["table_number"] = table_number; // The length of the key in the hash tables (*this)["key_size"] = key_size; // Number of levels to use in multi-probe (0 for standard LSH) (*this)["multi_probe_level"] = multi_probe_level; } }; /** * Randomized kd-tree index * * Contains the k-d trees and other information for indexing a set of points * for nearest-neighbor matching. */ template class LshIndex : public NNIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; /** Constructor * @param input_data dataset with the input features * @param params parameters passed to the LSH algorithm * @param d the distance used */ LshIndex(const Matrix& input_data, const IndexParams& params = LshIndexParams(), Distance d = Distance()) : dataset_(input_data), index_params_(params), distance_(d) { // cv::flann::IndexParams sets integer params as 'int', so it is used with get_param // in place of 'unsigned int' table_number_ = (unsigned int)get_param(index_params_,"table_number",12); key_size_ = (unsigned int)get_param(index_params_,"key_size",20); multi_probe_level_ = (unsigned int)get_param(index_params_,"multi_probe_level",2); feature_size_ = (unsigned)dataset_.cols; fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); } LshIndex(const LshIndex&); LshIndex& operator=(const LshIndex&); /** * Builds the index */ void buildIndex() { tables_.resize(table_number_); for (unsigned int i = 0; i < table_number_; ++i) { lsh::LshTable& table = tables_[i]; table = lsh::LshTable(feature_size_, key_size_); // Add the features to the table table.add(dataset_); } } flann_algorithm_t getType() const { return FLANN_INDEX_LSH; } void saveIndex(FILE* stream) { save_value(stream,table_number_); save_value(stream,key_size_); save_value(stream,multi_probe_level_); save_value(stream, dataset_); } void loadIndex(FILE* stream) { load_value(stream, table_number_); load_value(stream, key_size_); load_value(stream, multi_probe_level_); load_value(stream, dataset_); // Building the index is so fast we can afford not storing it buildIndex(); index_params_["algorithm"] = getType(); index_params_["table_number"] = table_number_; index_params_["key_size"] = key_size_; index_params_["multi_probe_level"] = multi_probe_level_; } /** * Returns size of index. */ size_t size() const { return dataset_.rows; } /** * Returns the length of an index feature. */ size_t veclen() const { return feature_size_; } /** * Computes the index memory usage * Returns: memory used by the index */ int usedMemory() const { return (int)(dataset_.rows * sizeof(int)); } IndexParams getParameters() const { return index_params_; } /** * \brief Perform k-nearest neighbor search * \param[in] queries The query points for which to find the nearest neighbors * \param[out] indices The indices of the nearest neighbors found * \param[out] dists Distances to the nearest neighbors found * \param[in] knn Number of nearest neighbors to return * \param[in] params Search parameters */ virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) { assert(queries.cols == veclen()); assert(indices.rows >= queries.rows); assert(dists.rows >= queries.rows); assert(int(indices.cols) >= knn); assert(int(dists.cols) >= knn); KNNUniqueResultSet resultSet(knn); for (size_t i = 0; i < queries.rows; i++) { resultSet.clear(); std::fill_n(indices[i], knn, -1); std::fill_n(dists[i], knn, std::numeric_limits::max()); findNeighbors(resultSet, queries[i], params); if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); else resultSet.copy(indices[i], dists[i], knn); } } /** * Find set of nearest neighbors to vec. Their indices are stored inside * the result object. * * Params: * result = the result object in which the indices of the nearest-neighbors are stored * vec = the vector for which to search the nearest neighbors * maxCheck = the maximum number of restarts (in a best-bin-first manner) */ void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& /*searchParams*/) { getNeighbors(vec, result); } private: /** Defines the comparator on score and index */ typedef std::pair ScoreIndexPair; struct SortScoreIndexPairOnSecond { bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const { return left.second < right.second; } }; /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH * @param key the key we build neighbors from * @param lowest_index the lowest index of the bit set * @param level the multi-probe level we are at * @param xor_masks all the xor mask */ void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, std::vector& xor_masks) { xor_masks.push_back(key); if (level == 0) return; for (int index = lowest_index - 1; index >= 0; --index) { // Create a new key lsh::BucketKey new_key = key | (1 << index); fill_xor_mask(new_key, index, level - 1, xor_masks); } } /** Performs the approximate nearest-neighbor search. * @param vec the feature to analyze * @param do_radius flag indicating if we check the radius too * @param radius the radius if it is a radius search * @param do_k flag indicating if we limit the number of nn * @param k_nn the number of nearest neighbors * @param checked_average used for debugging */ void getNeighbors(const ElementType* vec, bool /*do_radius*/, float radius, bool do_k, unsigned int k_nn, float& /*checked_average*/) { static std::vector score_index_heap; if (do_k) { unsigned int worst_score = std::numeric_limits::max(); typename std::vector >::const_iterator table = tables_.begin(); typename std::vector >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector::const_iterator xor_mask = xor_masks_.begin(); std::vector::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector::const_iterator training_index = bucket->begin(); std::vector::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); if (hamming_distance < worst_score) { // Insert the new element score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); std::push_heap(score_index_heap.begin(), score_index_heap.end()); if (score_index_heap.size() > (unsigned int)k_nn) { // Remove the highest distance value as we have too many elements std::pop_heap(score_index_heap.begin(), score_index_heap.end()); score_index_heap.pop_back(); // Keep track of the worst score worst_score = score_index_heap.front().first; } } } } } } else { typename std::vector >::const_iterator table = tables_.begin(); typename std::vector >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector::const_iterator xor_mask = xor_masks_.begin(); std::vector::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector::const_iterator training_index = bucket->begin(); std::vector::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { // Compute the Hamming distance hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); } } } } } /** Performs the approximate nearest-neighbor search. * This is a slower version than the above as it uses the ResultSet * @param vec the feature to analyze */ void getNeighbors(const ElementType* vec, ResultSet& result) { typename std::vector >::const_iterator table = tables_.begin(); typename std::vector >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector::const_iterator xor_mask = xor_masks_.begin(); std::vector::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey((lsh::BucketKey)sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector::const_iterator training_index = bucket->begin(); std::vector::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { // Compute the Hamming distance hamming_distance = distance_(vec, dataset_[*training_index], (int)dataset_.cols); result.addPoint(hamming_distance, *training_index); } } } } /** The different hash tables */ std::vector > tables_; /** The data the LSH tables where built from */ Matrix dataset_; /** The size of the features (as ElementType[]) */ unsigned int feature_size_; IndexParams index_params_; /** table number */ unsigned int table_number_; /** key size */ unsigned int key_size_; /** How far should we look for neighbors in multi-probe LSH */ unsigned int multi_probe_level_; /** The XOR masks to apply to a key to get the neighboring buckets */ std::vector xor_masks_; Distance distance_; }; } #endif //OPENCV_FLANN_LSH_INDEX_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/lsh_table.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ /*********************************************************************** * Author: Vincent Rabaud *************************************************************************/ #ifndef OPENCV_FLANN_LSH_TABLE_H_ #define OPENCV_FLANN_LSH_TABLE_H_ #include #include #include #include // TODO as soon as we use C++0x, use the code in USE_UNORDERED_MAP #ifdef __GXX_EXPERIMENTAL_CXX0X__ # define USE_UNORDERED_MAP 1 #else # define USE_UNORDERED_MAP 0 #endif #if USE_UNORDERED_MAP #include #else #include #endif #include #include #include "dynamic_bitset.h" #include "matrix.h" namespace cvflann { namespace lsh { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** What is stored in an LSH bucket */ typedef uint32_t FeatureIndex; /** The id from which we can get a bucket back in an LSH table */ typedef unsigned int BucketKey; /** A bucket in an LSH table */ typedef std::vector Bucket; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** POD for stats about an LSH table */ struct LshStats { std::vector bucket_sizes_; size_t n_buckets_; size_t bucket_size_mean_; size_t bucket_size_median_; size_t bucket_size_min_; size_t bucket_size_max_; size_t bucket_size_std_dev; /** Each contained vector contains three value: beginning/end for interval, number of elements in the bin */ std::vector > size_histogram_; }; /** Overload the << operator for LshStats * @param out the streams * @param stats the stats to display * @return the streams */ inline std::ostream& operator <<(std::ostream& out, const LshStats& stats) { int w = 20; out << "Lsh Table Stats:\n" << std::setw(w) << std::setiosflags(std::ios::right) << "N buckets : " << stats.n_buckets_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "mean size : " << std::setiosflags(std::ios::left) << stats.bucket_size_mean_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "median size : " << stats.bucket_size_median_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "min size : " << std::setiosflags(std::ios::left) << stats.bucket_size_min_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "max size : " << std::setiosflags(std::ios::left) << stats.bucket_size_max_; // Display the histogram out << std::endl << std::setw(w) << std::setiosflags(std::ios::right) << "histogram : " << std::setiosflags(std::ios::left); for (std::vector >::const_iterator iterator = stats.size_histogram_.begin(), end = stats.size_histogram_.end(); iterator != end; ++iterator) out << (*iterator)[0] << "-" << (*iterator)[1] << ": " << (*iterator)[2] << ", "; return out; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Lsh hash table. As its key is a sub-feature, and as usually * the size of it is pretty small, we keep it as a continuous memory array. * The value is an index in the corpus of features (we keep it as an unsigned * int for pure memory reasons, it could be a size_t) */ template class LshTable { public: /** A container of all the feature indices. Optimized for space */ #if USE_UNORDERED_MAP typedef std::unordered_map BucketsSpace; #else typedef std::map BucketsSpace; #endif /** A container of all the feature indices. Optimized for speed */ typedef std::vector BucketsSpeed; /** Default constructor */ LshTable() { } /** Default constructor * Create the mask and allocate the memory * @param feature_size is the size of the feature (considered as a ElementType[]) * @param key_size is the number of bits that are turned on in the feature */ LshTable(unsigned int feature_size, unsigned int key_size) { (void)feature_size; (void)key_size; std::cerr << "LSH is not implemented for that type" << std::endl; assert(0); } /** Add a feature to the table * @param value the value to store for that feature * @param feature the feature itself */ void add(unsigned int value, const ElementType* feature) { // Add the value to the corresponding bucket BucketKey key = (lsh::BucketKey)getKey(feature); switch (speed_level_) { case kArray: // That means we get the buckets from an array buckets_speed_[key].push_back(value); break; case kBitsetHash: // That means we can check the bitset for the presence of a key key_bitset_.set(key); buckets_space_[key].push_back(value); break; case kHash: { // That means we have to check for the hash table for the presence of a key buckets_space_[key].push_back(value); break; } } } /** Add a set of features to the table * @param dataset the values to store */ void add(Matrix dataset) { #if USE_UNORDERED_MAP buckets_space_.rehash((buckets_space_.size() + dataset.rows) * 1.2); #endif // Add the features to the table for (unsigned int i = 0; i < dataset.rows; ++i) add(i, dataset[i]); // Now that the table is full, optimize it for speed/space optimize(); } /** Get a bucket given the key * @param key * @return */ inline const Bucket* getBucketFromKey(BucketKey key) const { // Generate other buckets switch (speed_level_) { case kArray: // That means we get the buckets from an array return &buckets_speed_[key]; break; case kBitsetHash: // That means we can check the bitset for the presence of a key if (key_bitset_.test(key)) return &buckets_space_.find(key)->second; else return 0; break; case kHash: { // That means we have to check for the hash table for the presence of a key BucketsSpace::const_iterator bucket_it, bucket_end = buckets_space_.end(); bucket_it = buckets_space_.find(key); // Stop here if that bucket does not exist if (bucket_it == bucket_end) return 0; else return &bucket_it->second; break; } } return 0; } /** Compute the sub-signature of a feature */ size_t getKey(const ElementType* /*feature*/) const { std::cerr << "LSH is not implemented for that type" << std::endl; assert(0); return 1; } /** Get statistics about the table * @return */ LshStats getStats() const; private: /** defines the speed fo the implementation * kArray uses a vector for storing data * kBitsetHash uses a hash map but checks for the validity of a key with a bitset * kHash uses a hash map only */ enum SpeedLevel { kArray, kBitsetHash, kHash }; /** Initialize some variables */ void initialize(size_t key_size) { const size_t key_size_lower_bound = 1; //a value (size_t(1) << key_size) must fit the size_t type so key_size has to be strictly less than size of size_t const size_t key_size_upper_bound = std::min(sizeof(BucketKey) * CHAR_BIT + 1, sizeof(size_t) * CHAR_BIT); if (key_size < key_size_lower_bound || key_size >= key_size_upper_bound) { CV_Error(cv::Error::StsBadArg, cv::format("Invalid key_size (=%d). Valid values for your system are %d <= key_size < %d.", (int)key_size, (int)key_size_lower_bound, (int)key_size_upper_bound)); } speed_level_ = kHash; key_size_ = (unsigned)key_size; } /** Optimize the table for speed/space */ void optimize() { // If we are already using the fast storage, no need to do anything if (speed_level_ == kArray) return; // Use an array if it will be more than half full if (buckets_space_.size() > ((size_t(1) << key_size_) / 2)) { speed_level_ = kArray; // Fill the array version of it buckets_speed_.resize(size_t(1) << key_size_); for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) buckets_speed_[key_bucket->first] = key_bucket->second; // Empty the hash table buckets_space_.clear(); return; } // If the bitset is going to use less than 10% of the RAM of the hash map (at least 1 size_t for the key and two // for the vector) or less than 512MB (key_size_ <= 30) if (((std::max(buckets_space_.size(), buckets_speed_.size()) * CHAR_BIT * 3 * sizeof(BucketKey)) / 10 >= (size_t(1) << key_size_)) || (key_size_ <= 32)) { speed_level_ = kBitsetHash; key_bitset_.resize(size_t(1) << key_size_); key_bitset_.reset(); // Try with the BucketsSpace for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) key_bitset_.set(key_bucket->first); } else { speed_level_ = kHash; key_bitset_.clear(); } } /** The vector of all the buckets if they are held for speed */ BucketsSpeed buckets_speed_; /** The hash table of all the buckets in case we cannot use the speed version */ BucketsSpace buckets_space_; /** What is used to store the data */ SpeedLevel speed_level_; /** If the subkey is small enough, it will keep track of which subkeys are set through that bitset * That is just a speedup so that we don't look in the hash table (which can be mush slower that checking a bitset) */ DynamicBitset key_bitset_; /** The size of the sub-signature in bits */ unsigned int key_size_; // Members only used for the unsigned char specialization /** The mask to apply to a feature to get the hash key * Only used in the unsigned char case */ std::vector mask_; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Specialization for unsigned char template<> inline LshTable::LshTable(unsigned int feature_size, unsigned int subsignature_size) { initialize(subsignature_size); // Allocate the mask mask_ = std::vector((size_t)ceil((float)(feature_size * sizeof(char)) / (float)sizeof(size_t)), 0); // A bit brutal but fast to code std::vector indices(feature_size * CHAR_BIT); for (size_t i = 0; i < feature_size * CHAR_BIT; ++i) indices[i] = i; std::random_shuffle(indices.begin(), indices.end()); // Generate a random set of order of subsignature_size_ bits for (unsigned int i = 0; i < key_size_; ++i) { size_t index = indices[i]; // Set that bit in the mask size_t divisor = CHAR_BIT * sizeof(size_t); size_t idx = index / divisor; //pick the right size_t index mask_[idx] |= size_t(1) << (index % divisor); //use modulo to find the bit offset } // Set to 1 if you want to display the mask for debug #if 0 { size_t bcount = 0; BOOST_FOREACH(size_t mask_block, mask_){ out << std::setw(sizeof(size_t) * CHAR_BIT / 4) << std::setfill('0') << std::hex << mask_block << std::endl; bcount += __builtin_popcountll(mask_block); } out << "bit count : " << std::dec << bcount << std::endl; out << "mask size : " << mask_.size() << std::endl; return out; } #endif } /** Return the Subsignature of a feature * @param feature the feature to analyze */ template<> inline size_t LshTable::getKey(const unsigned char* feature) const { // no need to check if T is dividable by sizeof(size_t) like in the Hamming // distance computation as we have a mask const size_t* feature_block_ptr = reinterpret_cast ((const void*)feature); // Figure out the subsignature of the feature // Given the feature ABCDEF, and the mask 001011, the output will be // 000CEF size_t subsignature = 0; size_t bit_index = 1; for (std::vector::const_iterator pmask_block = mask_.begin(); pmask_block != mask_.end(); ++pmask_block) { // get the mask and signature blocks size_t feature_block = *feature_block_ptr; size_t mask_block = *pmask_block; while (mask_block) { // Get the lowest set bit in the mask block size_t lowest_bit = mask_block & (-(ptrdiff_t)mask_block); // Add it to the current subsignature if necessary subsignature += (feature_block & lowest_bit) ? bit_index : 0; // Reset the bit in the mask block mask_block ^= lowest_bit; // increment the bit index for the subsignature bit_index <<= 1; } // Check the next feature block ++feature_block_ptr; } return subsignature; } template<> inline LshStats LshTable::getStats() const { LshStats stats; stats.bucket_size_mean_ = 0; if ((buckets_speed_.empty()) && (buckets_space_.empty())) { stats.n_buckets_ = 0; stats.bucket_size_median_ = 0; stats.bucket_size_min_ = 0; stats.bucket_size_max_ = 0; return stats; } if (!buckets_speed_.empty()) { for (BucketsSpeed::const_iterator pbucket = buckets_speed_.begin(); pbucket != buckets_speed_.end(); ++pbucket) { stats.bucket_sizes_.push_back((lsh::FeatureIndex)pbucket->size()); stats.bucket_size_mean_ += pbucket->size(); } stats.bucket_size_mean_ /= buckets_speed_.size(); stats.n_buckets_ = buckets_speed_.size(); } else { for (BucketsSpace::const_iterator x = buckets_space_.begin(); x != buckets_space_.end(); ++x) { stats.bucket_sizes_.push_back((lsh::FeatureIndex)x->second.size()); stats.bucket_size_mean_ += x->second.size(); } stats.bucket_size_mean_ /= buckets_space_.size(); stats.n_buckets_ = buckets_space_.size(); } std::sort(stats.bucket_sizes_.begin(), stats.bucket_sizes_.end()); // BOOST_FOREACH(int size, stats.bucket_sizes_) // std::cout << size << " "; // std::cout << std::endl; stats.bucket_size_median_ = stats.bucket_sizes_[stats.bucket_sizes_.size() / 2]; stats.bucket_size_min_ = stats.bucket_sizes_.front(); stats.bucket_size_max_ = stats.bucket_sizes_.back(); // TODO compute mean and std /*float mean, stddev; stats.bucket_size_mean_ = mean; stats.bucket_size_std_dev = stddev;*/ // Include a histogram of the buckets unsigned int bin_start = 0; unsigned int bin_end = 20; bool is_new_bin = true; for (std::vector::iterator iterator = stats.bucket_sizes_.begin(), end = stats.bucket_sizes_.end(); iterator != end; ) if (*iterator < bin_end) { if (is_new_bin) { stats.size_histogram_.push_back(std::vector(3, 0)); stats.size_histogram_.back()[0] = bin_start; stats.size_histogram_.back()[1] = bin_end - 1; is_new_bin = false; } ++stats.size_histogram_.back()[2]; ++iterator; } else { bin_start += 20; bin_end += 20; is_new_bin = true; } return stats; } // End the two namespaces } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif /* OPENCV_FLANN_LSH_TABLE_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/matrix.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_DATASET_H_ #define OPENCV_FLANN_DATASET_H_ #include #include "general.h" namespace cvflann { /** * Class that implements a simple rectangular matrix stored in a memory buffer and * provides convenient matrix-like access using the [] operators. */ template class Matrix { public: typedef T type; size_t rows; size_t cols; size_t stride; T* data; Matrix() : rows(0), cols(0), stride(0), data(NULL) { } Matrix(T* data_, size_t rows_, size_t cols_, size_t stride_ = 0) : rows(rows_), cols(cols_), stride(stride_), data(data_) { if (stride==0) stride = cols; } /** * Convenience function for deallocating the storage data. */ FLANN_DEPRECATED void free() { fprintf(stderr, "The cvflann::Matrix::free() method is deprecated " "and it does not do any memory deallocation any more. You are" "responsible for deallocating the matrix memory (by doing" "'delete[] matrix.data' for example)"); } /** * Operator that return a (pointer to a) row of the data. */ T* operator[](size_t index) const { return data+index*stride; } }; class UntypedMatrix { public: size_t rows; size_t cols; void* data; flann_datatype_t type; UntypedMatrix(void* data_, long rows_, long cols_) : rows(rows_), cols(cols_), data(data_) { } ~UntypedMatrix() { } template Matrix as() { return Matrix((T*)data, rows, cols); } }; } #endif //OPENCV_FLANN_DATASET_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/miniflann.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef _OPENCV_MINIFLANN_HPP_ #define _OPENCV_MINIFLANN_HPP_ #include "opencv2/core.hpp" #include "opencv2/flann/defines.h" namespace cv { namespace flann { struct CV_EXPORTS IndexParams { IndexParams(); ~IndexParams(); String getString(const String& key, const String& defaultVal=String()) const; int getInt(const String& key, int defaultVal=-1) const; double getDouble(const String& key, double defaultVal=-1) const; void setString(const String& key, const String& value); void setInt(const String& key, int value); void setDouble(const String& key, double value); void setFloat(const String& key, float value); void setBool(const String& key, bool value); void setAlgorithm(int value); void getAll(std::vector& names, std::vector& types, std::vector& strValues, std::vector& numValues) const; void* params; }; struct CV_EXPORTS KDTreeIndexParams : public IndexParams { KDTreeIndexParams(int trees=4); }; struct CV_EXPORTS LinearIndexParams : public IndexParams { LinearIndexParams(); }; struct CV_EXPORTS CompositeIndexParams : public IndexParams { CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); }; struct CV_EXPORTS AutotunedIndexParams : public IndexParams { AutotunedIndexParams(float target_precision = 0.8f, float build_weight = 0.01f, float memory_weight = 0, float sample_fraction = 0.1f); }; struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams { HierarchicalClusteringIndexParams(int branching = 32, cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, int trees = 4, int leaf_size = 100 ); }; struct CV_EXPORTS KMeansIndexParams : public IndexParams { KMeansIndexParams(int branching = 32, int iterations = 11, cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); }; struct CV_EXPORTS LshIndexParams : public IndexParams { LshIndexParams(int table_number, int key_size, int multi_probe_level); }; struct CV_EXPORTS SavedIndexParams : public IndexParams { SavedIndexParams(const String& filename); }; struct CV_EXPORTS SearchParams : public IndexParams { SearchParams( int checks = 32, float eps = 0, bool sorted = true ); }; class CV_EXPORTS_W Index { public: CV_WRAP Index(); CV_WRAP Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); virtual ~Index(); CV_WRAP virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices, OutputArray dists, int knn, const SearchParams& params=SearchParams()); CV_WRAP virtual int radiusSearch(InputArray query, OutputArray indices, OutputArray dists, double radius, int maxResults, const SearchParams& params=SearchParams()); CV_WRAP virtual void save(const String& filename) const; CV_WRAP virtual bool load(InputArray features, const String& filename); CV_WRAP virtual void release(); CV_WRAP cvflann::flann_distance_t getDistance() const; CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const; protected: cvflann::flann_distance_t distType; cvflann::flann_algorithm_t algo; int featureType; void* index; }; } } // namespace cv::flann #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/nn_index.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_NNINDEX_H #define OPENCV_FLANN_NNINDEX_H #include "general.h" #include "matrix.h" #include "result_set.h" #include "params.h" namespace cvflann { /** * Nearest-neighbour index base class */ template class NNIndex { typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; public: virtual ~NNIndex() {} /** * \brief Builds the index */ virtual void buildIndex() = 0; /** * \brief Perform k-nearest neighbor search * \param[in] queries The query points for which to find the nearest neighbors * \param[out] indices The indices of the nearest neighbors found * \param[out] dists Distances to the nearest neighbors found * \param[in] knn Number of nearest neighbors to return * \param[in] params Search parameters */ virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) { assert(queries.cols == veclen()); assert(indices.rows >= queries.rows); assert(dists.rows >= queries.rows); assert(int(indices.cols) >= knn); assert(int(dists.cols) >= knn); #if 0 KNNResultSet resultSet(knn); for (size_t i = 0; i < queries.rows; i++) { resultSet.init(indices[i], dists[i]); findNeighbors(resultSet, queries[i], params); } #else KNNUniqueResultSet resultSet(knn); for (size_t i = 0; i < queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); else resultSet.copy(indices[i], dists[i], knn); } #endif } /** * \brief Perform radius search * \param[in] query The query point * \param[out] indices The indinces of the neighbors found within the given radius * \param[out] dists The distances to the nearest neighbors found * \param[in] radius The radius used for search * \param[in] params Search parameters * \returns Number of neighbors found */ virtual int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) { if (query.rows != 1) { fprintf(stderr, "I can only search one feature at a time for range search\n"); return -1; } assert(query.cols == veclen()); assert(indices.cols == dists.cols); int n = 0; int* indices_ptr = NULL; DistanceType* dists_ptr = NULL; if (indices.cols > 0) { n = (int)indices.cols; indices_ptr = indices[0]; dists_ptr = dists[0]; } RadiusUniqueResultSet resultSet((DistanceType)radius); resultSet.clear(); findNeighbors(resultSet, query[0], params); if (n>0) { if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices_ptr, dists_ptr, n); else resultSet.copy(indices_ptr, dists_ptr, n); } return (int)resultSet.size(); } /** * \brief Saves the index to a stream * \param stream The stream to save the index to */ virtual void saveIndex(FILE* stream) = 0; /** * \brief Loads the index from a stream * \param stream The stream from which the index is loaded */ virtual void loadIndex(FILE* stream) = 0; /** * \returns number of features in this index. */ virtual size_t size() const = 0; /** * \returns The dimensionality of the features in this index. */ virtual size_t veclen() const = 0; /** * \returns The amount of memory (in bytes) used by the index. */ virtual int usedMemory() const = 0; /** * \returns The index type (kdtree, kmeans,...) */ virtual flann_algorithm_t getType() const = 0; /** * \returns The index parameters */ virtual IndexParams getParameters() const = 0; /** * \brief Method that searches for nearest-neighbours */ virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) = 0; }; } #endif //OPENCV_FLANN_NNINDEX_H ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/object_factory.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_OBJECT_FACTORY_H_ #define OPENCV_FLANN_OBJECT_FACTORY_H_ #include namespace cvflann { class CreatorNotFound { }; template class ObjectFactory { typedef ObjectFactory ThisClass; typedef std::map ObjectRegistry; // singleton class, private constructor ObjectFactory() {} public: bool subscribe(UniqueIdType id, ObjectCreator creator) { if (object_registry.find(id) != object_registry.end()) return false; object_registry[id] = creator; return true; } bool unregister(UniqueIdType id) { return object_registry.erase(id) == 1; } ObjectCreator create(UniqueIdType id) { typename ObjectRegistry::const_iterator iter = object_registry.find(id); if (iter == object_registry.end()) { throw CreatorNotFound(); } return iter->second; } static ThisClass& instance() { static ThisClass the_factory; return the_factory; } private: ObjectRegistry object_registry; }; } #endif /* OPENCV_FLANN_OBJECT_FACTORY_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/params.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_PARAMS_H_ #define OPENCV_FLANN_PARAMS_H_ #include "any.h" #include "general.h" #include #include namespace cvflann { typedef std::map IndexParams; struct SearchParams : public IndexParams { SearchParams(int checks = 32, float eps = 0, bool sorted = true ) { // how many leafs to visit when searching for neighbours (-1 for unlimited) (*this)["checks"] = checks; // search for eps-approximate neighbours (default: 0) (*this)["eps"] = eps; // only for radius search, require neighbours sorted by distance (default: true) (*this)["sorted"] = sorted; } }; template T get_param(const IndexParams& params, cv::String name, const T& default_value) { IndexParams::const_iterator it = params.find(name); if (it != params.end()) { return it->second.cast(); } else { return default_value; } } template T get_param(const IndexParams& params, cv::String name) { IndexParams::const_iterator it = params.find(name); if (it != params.end()) { return it->second.cast(); } else { throw FLANNException(cv::String("Missing parameter '")+name+cv::String("' in the parameters given")); } } inline void print_params(const IndexParams& params, std::ostream& stream) { IndexParams::const_iterator it; for(it=params.begin(); it!=params.end(); ++it) { stream << it->first << " : " << it->second << std::endl; } } inline void print_params(const IndexParams& params) { print_params(params, std::cout); } } #endif /* OPENCV_FLANN_PARAMS_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/random.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_RANDOM_H #define OPENCV_FLANN_RANDOM_H #include #include #include #include "general.h" namespace cvflann { /** * Seeds the random number generator * @param seed Random seed */ inline void seed_random(unsigned int seed) { srand(seed); } /* * Generates a random double value. */ /** * Generates a random double value. * @param high Upper limit * @param low Lower limit * @return Random double value */ inline double rand_double(double high = 1.0, double low = 0) { return low + ((high-low) * (std::rand() / (RAND_MAX + 1.0))); } /** * Generates a random integer value. * @param high Upper limit * @param low Lower limit * @return Random integer value */ inline int rand_int(int high = RAND_MAX, int low = 0) { return low + (int) ( double(high-low) * (std::rand() / (RAND_MAX + 1.0))); } /** * Random number generator that returns a distinct number from * the [0,n) interval each time. */ class UniqueRandom { std::vector vals_; int size_; int counter_; public: /** * Constructor. * @param n Size of the interval from which to generate * @return */ UniqueRandom(int n) { init(n); } /** * Initializes the number generator. * @param n the size of the interval from which to generate random numbers. */ void init(int n) { // create and initialize an array of size n vals_.resize(n); size_ = n; for (int i = 0; i < size_; ++i) vals_[i] = i; // shuffle the elements in the array std::random_shuffle(vals_.begin(), vals_.end()); counter_ = 0; } /** * Return a distinct random integer in greater or equal to 0 and less * than 'n' on each call. It should be called maximum 'n' times. * Returns: a random integer */ int next() { if (counter_ == size_) { return -1; } else { return vals_[counter_++]; } } }; } #endif //OPENCV_FLANN_RANDOM_H ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/result_set.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_RESULTSET_H #define OPENCV_FLANN_RESULTSET_H #include #include #include #include #include #include namespace cvflann { /* This record represents a branch point when finding neighbors in the tree. It contains a record of the minimum distance to the query point, as well as the node at which the search resumes. */ template struct BranchStruct { T node; /* Tree node at which search resumes */ DistanceType mindist; /* Minimum distance to query for all nodes below. */ BranchStruct() {} BranchStruct(const T& aNode, DistanceType dist) : node(aNode), mindist(dist) {} bool operator<(const BranchStruct& rhs) const { return mindist class ResultSet { public: virtual ~ResultSet() {} virtual bool full() const = 0; virtual void addPoint(DistanceType dist, int index) = 0; virtual DistanceType worstDist() const = 0; }; /** * KNNSimpleResultSet does not ensure that the element it holds are unique. * Is used in those cases where the nearest neighbour algorithm used does not * attempt to insert the same element multiple times. */ template class KNNSimpleResultSet : public ResultSet { int* indices; DistanceType* dists; int capacity; int count; DistanceType worst_distance_; public: KNNSimpleResultSet(int capacity_) : capacity(capacity_), count(0) { } void init(int* indices_, DistanceType* dists_) { indices = indices_; dists = dists_; count = 0; worst_distance_ = (std::numeric_limits::max)(); dists[capacity-1] = worst_distance_; } size_t size() const { return count; } bool full() const { return count == capacity; } void addPoint(DistanceType dist, int index) { if (dist >= worst_distance_) return; int i; for (i=count; i>0; --i) { #ifdef FLANN_FIRST_MATCH if ( (dists[i-1]>dist) || ((dist==dists[i-1])&&(indices[i-1]>index)) ) #else if (dists[i-1]>dist) #endif { if (i class KNNResultSet : public ResultSet { int* indices; DistanceType* dists; int capacity; int count; DistanceType worst_distance_; public: KNNResultSet(int capacity_) : capacity(capacity_), count(0) { } void init(int* indices_, DistanceType* dists_) { indices = indices_; dists = dists_; count = 0; worst_distance_ = (std::numeric_limits::max)(); dists[capacity-1] = worst_distance_; } size_t size() const { return count; } bool full() const { return count == capacity; } void addPoint(DistanceType dist, int index) { if (dist >= worst_distance_) return; int i; for (i = count; i > 0; --i) { #ifdef FLANN_FIRST_MATCH if ( (dists[i-1]<=dist) && ((dist!=dists[i-1])||(indices[i-1]<=index)) ) #else if (dists[i-1]<=dist) #endif { // Check for duplicate indices int j = i - 1; while ((j >= 0) && (dists[j] == dist)) { if (indices[j] == index) { return; } --j; } break; } } if (count < capacity) ++count; for (int j = count-1; j > i; --j) { dists[j] = dists[j-1]; indices[j] = indices[j-1]; } dists[i] = dist; indices[i] = index; worst_distance_ = dists[capacity-1]; } DistanceType worstDist() const { return worst_distance_; } }; /** * A result-set class used when performing a radius based search. */ template class RadiusResultSet : public ResultSet { DistanceType radius; int* indices; DistanceType* dists; size_t capacity; size_t count; public: RadiusResultSet(DistanceType radius_, int* indices_, DistanceType* dists_, int capacity_) : radius(radius_), indices(indices_), dists(dists_), capacity(capacity_) { init(); } ~RadiusResultSet() { } void init() { count = 0; } size_t size() const { return count; } bool full() const { return true; } void addPoint(DistanceType dist, int index) { if (dist0)&&(count < capacity)) { dists[count] = dist; indices[count] = index; } count++; } } DistanceType worstDist() const { return radius; } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Class that holds the k NN neighbors * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays */ template class UniqueResultSet : public ResultSet { public: struct DistIndex { DistIndex(DistanceType dist, unsigned int index) : dist_(dist), index_(index) { } bool operator<(const DistIndex dist_index) const { return (dist_ < dist_index.dist_) || ((dist_ == dist_index.dist_) && index_ < dist_index.index_); } DistanceType dist_; unsigned int index_; }; /** Default cosntructor */ UniqueResultSet() : worst_distance_(std::numeric_limits::max()) { } /** Check the status of the set * @return true if we have k NN */ inline bool full() const { return is_full_; } /** Remove all elements in the set */ virtual void clear() = 0; /** Copy the set to two C arrays * @param indices pointer to a C array of indices * @param dist pointer to a C array of distances * @param n_neighbors the number of neighbors to copy */ virtual void copy(int* indices, DistanceType* dist, int n_neighbors = -1) const { if (n_neighbors < 0) { for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = dist_indices_.end(); dist_index != dist_index_end; ++dist_index, ++indices, ++dist) { *indices = dist_index->index_; *dist = dist_index->dist_; } } else { int i = 0; for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = dist_indices_.end(); (dist_index != dist_index_end) && (i < n_neighbors); ++dist_index, ++indices, ++dist, ++i) { *indices = dist_index->index_; *dist = dist_index->dist_; } } } /** Copy the set to two C arrays but sort it according to the distance first * @param indices pointer to a C array of indices * @param dist pointer to a C array of distances * @param n_neighbors the number of neighbors to copy */ virtual void sortAndCopy(int* indices, DistanceType* dist, int n_neighbors = -1) const { copy(indices, dist, n_neighbors); } /** The number of neighbors in the set * @return */ size_t size() const { return dist_indices_.size(); } /** The distance of the furthest neighbor * If we don't have enough neighbors, it returns the max possible value * @return */ inline DistanceType worstDist() const { return worst_distance_; } protected: /** Flag to say if the set is full */ bool is_full_; /** The worst distance found so far */ DistanceType worst_distance_; /** The best candidates so far */ std::set dist_indices_; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Class that holds the k NN neighbors * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays */ template class KNNUniqueResultSet : public UniqueResultSet { public: /** Constructor * @param capacity the number of neighbors to store at max */ KNNUniqueResultSet(unsigned int capacity) : capacity_(capacity) { this->is_full_ = false; this->clear(); } /** Add a possible candidate to the best neighbors * @param dist distance for that neighbor * @param index index of that neighbor */ inline void addPoint(DistanceType dist, int index) { // Don't do anything if we are worse than the worst if (dist >= worst_distance_) return; dist_indices_.insert(DistIndex(dist, index)); if (is_full_) { if (dist_indices_.size() > capacity_) { dist_indices_.erase(*dist_indices_.rbegin()); worst_distance_ = dist_indices_.rbegin()->dist_; } } else if (dist_indices_.size() == capacity_) { is_full_ = true; worst_distance_ = dist_indices_.rbegin()->dist_; } } /** Remove all elements in the set */ void clear() { dist_indices_.clear(); worst_distance_ = std::numeric_limits::max(); is_full_ = false; } protected: typedef typename UniqueResultSet::DistIndex DistIndex; using UniqueResultSet::is_full_; using UniqueResultSet::worst_distance_; using UniqueResultSet::dist_indices_; /** The number of neighbors to keep */ unsigned int capacity_; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Class that holds the radius nearest neighbors * It is more accurate than RadiusResult as it is not limited in the number of neighbors */ template class RadiusUniqueResultSet : public UniqueResultSet { public: /** Constructor * @param radius the maximum distance of a neighbor */ RadiusUniqueResultSet(DistanceType radius) : radius_(radius) { is_full_ = true; } /** Add a possible candidate to the best neighbors * @param dist distance for that neighbor * @param index index of that neighbor */ void addPoint(DistanceType dist, int index) { if (dist <= radius_) dist_indices_.insert(DistIndex(dist, index)); } /** Remove all elements in the set */ inline void clear() { dist_indices_.clear(); } /** Check the status of the set * @return alwys false */ inline bool full() const { return true; } /** The distance of the furthest neighbor * If we don't have enough neighbors, it returns the max possible value * @return */ inline DistanceType worstDist() const { return radius_; } private: typedef typename UniqueResultSet::DistIndex DistIndex; using UniqueResultSet::dist_indices_; using UniqueResultSet::is_full_; /** The furthest distance a neighbor can be */ DistanceType radius_; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Class that holds the k NN neighbors within a radius distance */ template class KNNRadiusUniqueResultSet : public KNNUniqueResultSet { public: /** Constructor * @param capacity the number of neighbors to store at max * @param radius the maximum distance of a neighbor */ KNNRadiusUniqueResultSet(unsigned int capacity, DistanceType radius) { this->capacity_ = capacity; this->radius_ = radius; this->dist_indices_.reserve(capacity_); this->clear(); } /** Remove all elements in the set */ void clear() { dist_indices_.clear(); worst_distance_ = radius_; is_full_ = false; } private: using KNNUniqueResultSet::dist_indices_; using KNNUniqueResultSet::is_full_; using KNNUniqueResultSet::worst_distance_; /** The maximum number of neighbors to consider */ unsigned int capacity_; /** The maximum distance of a neighbor */ DistanceType radius_; }; } #endif //OPENCV_FLANN_RESULTSET_H ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/sampling.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_SAMPLING_H_ #define OPENCV_FLANN_SAMPLING_H_ #include "matrix.h" #include "random.h" namespace cvflann { template Matrix random_sample(Matrix& srcMatrix, long size, bool remove = false) { Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); T* src,* dest; for (long i=0; i Matrix random_sample(const Matrix& srcMatrix, size_t size) { UniqueRandom rand((int)srcMatrix.rows); Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); T* src,* dest; for (size_t i=0; i #include #include "general.h" #include "nn_index.h" #ifdef FLANN_SIGNATURE_ #undef FLANN_SIGNATURE_ #endif #define FLANN_SIGNATURE_ "FLANN_INDEX" namespace cvflann { template struct Datatype {}; template<> struct Datatype { static flann_datatype_t type() { return FLANN_INT8; } }; template<> struct Datatype { static flann_datatype_t type() { return FLANN_INT16; } }; template<> struct Datatype { static flann_datatype_t type() { return FLANN_INT32; } }; template<> struct Datatype { static flann_datatype_t type() { return FLANN_UINT8; } }; template<> struct Datatype { static flann_datatype_t type() { return FLANN_UINT16; } }; template<> struct Datatype { static flann_datatype_t type() { return FLANN_UINT32; } }; template<> struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT32; } }; template<> struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT64; } }; /** * Structure representing the index header. */ struct IndexHeader { char signature[16]; char version[16]; flann_datatype_t data_type; flann_algorithm_t index_type; size_t rows; size_t cols; }; /** * Saves index header to stream * * @param stream - Stream to save to * @param index - The index to save */ template void save_header(FILE* stream, const NNIndex& index) { IndexHeader header; memset(header.signature, 0, sizeof(header.signature)); strcpy(header.signature, FLANN_SIGNATURE_); memset(header.version, 0, sizeof(header.version)); strcpy(header.version, FLANN_VERSION_); header.data_type = Datatype::type(); header.index_type = index.getType(); header.rows = index.size(); header.cols = index.veclen(); std::fwrite(&header, sizeof(header),1,stream); } /** * * @param stream - Stream to load from * @return Index header */ inline IndexHeader load_header(FILE* stream) { IndexHeader header; size_t read_size = fread(&header,sizeof(header),1,stream); if (read_size!=(size_t)1) { throw FLANNException("Invalid index file, cannot read"); } if (strcmp(header.signature,FLANN_SIGNATURE_)!=0) { throw FLANNException("Invalid index file, wrong signature"); } return header; } template void save_value(FILE* stream, const T& value, size_t count = 1) { fwrite(&value, sizeof(value),count, stream); } template void save_value(FILE* stream, const cvflann::Matrix& value) { fwrite(&value, sizeof(value),1, stream); fwrite(value.data, sizeof(T),value.rows*value.cols, stream); } template void save_value(FILE* stream, const std::vector& value) { size_t size = value.size(); fwrite(&size, sizeof(size_t), 1, stream); fwrite(&value[0], sizeof(T), size, stream); } template void load_value(FILE* stream, T& value, size_t count = 1) { size_t read_cnt = fread(&value, sizeof(value), count, stream); if (read_cnt != count) { throw FLANNException("Cannot read from file"); } } template void load_value(FILE* stream, cvflann::Matrix& value) { size_t read_cnt = fread(&value, sizeof(value), 1, stream); if (read_cnt != 1) { throw FLANNException("Cannot read from file"); } value.data = new T[value.rows*value.cols]; read_cnt = fread(value.data, sizeof(T), value.rows*value.cols, stream); if (read_cnt != (size_t)(value.rows*value.cols)) { throw FLANNException("Cannot read from file"); } } template void load_value(FILE* stream, std::vector& value) { size_t size; size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); if (read_cnt!=1) { throw FLANNException("Cannot read from file"); } value.resize(size); read_cnt = fread(&value[0], sizeof(T), size, stream); if (read_cnt != size) { throw FLANNException("Cannot read from file"); } } } #endif /* OPENCV_FLANN_SAVING_H_ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann/simplex_downhill.h ================================================ /*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ #define OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ namespace cvflann { /** Adds val to array vals (and point to array points) and keeping the arrays sorted by vals. */ template void addValue(int pos, float val, float* vals, T* point, T* points, int n) { vals[pos] = val; for (int i=0; i0 && vals[j] float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL ) { const int MAX_ITERATIONS = 10; assert(n>0); T* p_o = new T[n]; T* p_r = new T[n]; T* p_e = new T[n]; int alpha = 1; int iterations = 0; bool ownVals = false; if (vals == NULL) { ownVals = true; vals = new float[n+1]; for (int i=0; i MAX_ITERATIONS) break; // compute average of simplex points (except the highest point) for (int j=0; j=vals[0])&&(val_r=vals[n]) { for (int i=0; i #include "opencv2/core.hpp" #include "opencv2/core/utility.hpp" namespace cvflann { /** * A start-stop timer class. * * Can be used to time portions of code. */ class StartStopTimer { int64 startTime; public: /** * Value of the timer. */ double value; /** * Constructor. */ StartStopTimer() { reset(); } /** * Starts the timer. */ void start() { startTime = cv::getTickCount(); } /** * Stops the timer and updates timer value. */ void stop() { int64 stopTime = cv::getTickCount(); value += ( (double)stopTime - startTime) / cv::getTickFrequency(); } /** * Resets the timer value to 0. */ void reset() { value = 0; } }; } #endif // FLANN_TIMER_H ================================================ FILE: src/3rdparty/opencv/include/opencv2/flann.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef _OPENCV_FLANN_HPP_ #define _OPENCV_FLANN_HPP_ #include "opencv2/core.hpp" #include "opencv2/flann/miniflann.hpp" #include "opencv2/flann/flann_base.hpp" /** @defgroup flann Clustering and Search in Multi-Dimensional Spaces This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest neighbor search in large datasets and for high dimensional features. More information about FLANN can be found in @cite Muja2009 . */ namespace cvflann { CV_EXPORTS flann_distance_t flann_distance_type(); FLANN_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order); } namespace cv { namespace flann { //! @addtogroup flann //! @{ template struct CvType {}; template <> struct CvType { static int type() { return CV_8U; } }; template <> struct CvType { static int type() { return CV_8S; } }; template <> struct CvType { static int type() { return CV_16U; } }; template <> struct CvType { static int type() { return CV_16S; } }; template <> struct CvType { static int type() { return CV_32S; } }; template <> struct CvType { static int type() { return CV_32F; } }; template <> struct CvType { static int type() { return CV_64F; } }; // bring the flann parameters into this namespace using ::cvflann::get_param; using ::cvflann::print_params; // bring the flann distances into this namespace using ::cvflann::L2_Simple; using ::cvflann::L2; using ::cvflann::L1; using ::cvflann::MinkowskiDistance; using ::cvflann::MaxDistance; using ::cvflann::HammingLUT; using ::cvflann::Hamming; using ::cvflann::Hamming2; using ::cvflann::HistIntersectionDistance; using ::cvflann::HellingerDistance; using ::cvflann::ChiSquareDistance; using ::cvflann::KL_Divergence; /** @brief The FLANN nearest neighbor index class. This class is templated with the type of elements for which the index is built. */ template class GenericIndex { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; /** @brief Constructs a nearest neighbor search index for a given dataset. @param features Matrix of containing the features(points) to index. The size of the matrix is num_features x feature_dimensionality and the data type of the elements in the matrix must coincide with the type of the index. @param params Structure containing the index parameters. The type of index that will be constructed depends on the type of this parameter. See the description. @param distance The method constructs a fast search structure from a set of features using the specified algorithm with specified parameters, as defined by params. params is a reference to one of the following class IndexParams descendants: - **LinearIndexParams** When passing an object of this type, the index will perform a linear, brute-force search. : @code struct LinearIndexParams : public IndexParams { }; @endcode - **KDTreeIndexParams** When passing an object of this type the index constructed will consist of a set of randomized kd-trees which will be searched in parallel. : @code struct KDTreeIndexParams : public IndexParams { KDTreeIndexParams( int trees = 4 ); }; @endcode - **KMeansIndexParams** When passing an object of this type the index constructed will be a hierarchical k-means tree. : @code struct KMeansIndexParams : public IndexParams { KMeansIndexParams( int branching = 32, int iterations = 11, flann_centers_init_t centers_init = CENTERS_RANDOM, float cb_index = 0.2 ); }; @endcode - **CompositeIndexParams** When using a parameters object of this type the index created combines the randomized kd-trees and the hierarchical k-means tree. : @code struct CompositeIndexParams : public IndexParams { CompositeIndexParams( int trees = 4, int branching = 32, int iterations = 11, flann_centers_init_t centers_init = CENTERS_RANDOM, float cb_index = 0.2 ); }; @endcode - **LshIndexParams** When using a parameters object of this type the index created uses multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007) : @code struct LshIndexParams : public IndexParams { LshIndexParams( unsigned int table_number, unsigned int key_size, unsigned int multi_probe_level ); }; @endcode - **AutotunedIndexParams** When passing an object of this type the index created is automatically tuned to offer the best performance, by choosing the optimal index type (randomized kd-trees, hierarchical kmeans, linear) and parameters for the dataset provided. : @code struct AutotunedIndexParams : public IndexParams { AutotunedIndexParams( float target_precision = 0.9, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1 ); }; @endcode - **SavedIndexParams** This object type is used for loading a previously saved index from the disk. : @code struct SavedIndexParams : public IndexParams { SavedIndexParams( String filename ); }; @endcode */ GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance()); ~GenericIndex(); /** @brief Performs a K-nearest neighbor search for a given query point using the index. @param query The query point @param indices Vector that will contain the indices of the K-nearest neighbors found. It must have at least knn size. @param dists Vector that will contain the distances to the K-nearest neighbors found. It must have at least knn size. @param knn Number of nearest neighbors to search for. @param params SearchParams */ void knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& params); void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); int radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& params); void save(String filename) { nnIndex->save(filename); } int veclen() const { return nnIndex->veclen(); } int size() const { return nnIndex->size(); } ::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); } FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); } private: ::cvflann::Index* nnIndex; }; //! @cond IGNORED #define FLANN_DISTANCE_CHECK \ if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \ printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\ "the distance using cvflann::set_distance_type. This is no longer working as expected "\ "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\ "for example for L1 distance use: GenericIndex< L1 > \n"); \ } template GenericIndex::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance) { CV_Assert(dataset.type() == CvType::type()); CV_Assert(dataset.isContinuous()); ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); nnIndex = new ::cvflann::Index(m_dataset, params, distance); FLANN_DISTANCE_CHECK nnIndex->buildIndex(); } template GenericIndex::~GenericIndex() { delete nnIndex; } template void GenericIndex::knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) { ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); FLANN_DISTANCE_CHECK nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams); } template void GenericIndex::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) { CV_Assert(queries.type() == CvType::type()); CV_Assert(queries.isContinuous()); ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); FLANN_DISTANCE_CHECK nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); } template int GenericIndex::radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) { ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); FLANN_DISTANCE_CHECK return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } template int GenericIndex::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) { CV_Assert(query.type() == CvType::type()); CV_Assert(query.isContinuous()); ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); FLANN_DISTANCE_CHECK return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } //! @endcond /** * @deprecated Use GenericIndex class instead */ template class #ifndef _MSC_VER FLANN_DEPRECATED #endif Index_ { public: typedef typename L2::ElementType ElementType; typedef typename L2::ResultType DistanceType; Index_(const Mat& features, const ::cvflann::IndexParams& params); ~Index_(); void knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& params); void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); int radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& params); void save(String filename) { if (nnIndex_L1) nnIndex_L1->save(filename); if (nnIndex_L2) nnIndex_L2->save(filename); } int veclen() const { if (nnIndex_L1) return nnIndex_L1->veclen(); if (nnIndex_L2) return nnIndex_L2->veclen(); } int size() const { if (nnIndex_L1) return nnIndex_L1->size(); if (nnIndex_L2) return nnIndex_L2->size(); } ::cvflann::IndexParams getParameters() { if (nnIndex_L1) return nnIndex_L1->getParameters(); if (nnIndex_L2) return nnIndex_L2->getParameters(); } FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { if (nnIndex_L1) return nnIndex_L1->getIndexParameters(); if (nnIndex_L2) return nnIndex_L2->getIndexParameters(); } private: // providing backwards compatibility for L2 and L1 distances (most common) ::cvflann::Index< L2 >* nnIndex_L2; ::cvflann::Index< L1 >* nnIndex_L1; }; #ifdef _MSC_VER template class FLANN_DEPRECATED Index_; #endif //! @cond IGNORED template Index_::Index_(const Mat& dataset, const ::cvflann::IndexParams& params) { printf("[WARNING] The cv::flann::Index_ class is deperecated, use cv::flann::GenericIndex instead\n"); CV_Assert(dataset.type() == CvType::type()); CV_Assert(dataset.isContinuous()); ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { nnIndex_L1 = NULL; nnIndex_L2 = new ::cvflann::Index< L2 >(m_dataset, params); } else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { nnIndex_L1 = new ::cvflann::Index< L1 >(m_dataset, params); nnIndex_L2 = NULL; } else { printf("[ERROR] cv::flann::Index_ only provides backwards compatibility for the L1 and L2 distances. " "For other distance types you must use cv::flann::GenericIndex\n"); CV_Assert(0); } if (nnIndex_L1) nnIndex_L1->buildIndex(); if (nnIndex_L2) nnIndex_L2->buildIndex(); } template Index_::~Index_() { if (nnIndex_L1) delete nnIndex_L1; if (nnIndex_L2) delete nnIndex_L2; } template void Index_::knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) { ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams); if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams); } template void Index_::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) { CV_Assert(queries.type() == CvType::type()); CV_Assert(queries.isContinuous()); ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); } template int Index_::radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) { ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } template int Index_::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) { CV_Assert(query.type() == CvType::type()); CV_Assert(query.isContinuous()); ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } //! @endcond /** @brief Clusters features using hierarchical k-means algorithm. @param features The points to be clustered. The matrix must have elements of type Distance::ElementType. @param centers The centers of the clusters obtained. The matrix must have type Distance::ResultType. The number of rows in this matrix represents the number of clusters desired, however, because of the way the cut in the hierarchical tree is chosen, the number of clusters computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of clusters desired, where branching is the tree's branching factor (see description of the KMeansIndexParams). @param params Parameters used in the construction of the hierarchical k-means tree. @param d Distance to be used for clustering. The method clusters the given feature vectors by constructing a hierarchical k-means tree and choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters found. */ template int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params, Distance d = Distance()) { typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; CV_Assert(features.type() == CvType::type()); CV_Assert(features.isContinuous()); ::cvflann::Matrix m_features((ElementType*)features.ptr(0), features.rows, features.cols); CV_Assert(centers.type() == CvType::type()); CV_Assert(centers.isContinuous()); ::cvflann::Matrix m_centers((DistanceType*)centers.ptr(0), centers.rows, centers.cols); return ::cvflann::hierarchicalClustering(m_features, m_centers, params, d); } /** @deprecated */ template FLANN_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params) { printf("[WARNING] cv::flann::hierarchicalClustering is deprecated, use " "cv::flann::hierarchicalClustering instead\n"); if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { return hierarchicalClustering< L2 >(features, centers, params); } else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { return hierarchicalClustering< L1 >(features, centers, params); } else { printf("[ERROR] cv::flann::hierarchicalClustering only provides backwards " "compatibility for the L1 and L2 distances. " "For other distance types you must use cv::flann::hierarchicalClustering\n"); CV_Assert(0); } } //! @} flann } } // namespace cv::flann #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/fuzzy/fuzzy_F0_math.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, University of Ostrava, Institute for Research and Applications of Fuzzy Modeling, // Pavel Vlasanek, all rights reserved. Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_FUZZY_F0_MATH_H__ #define __OPENCV_FUZZY_F0_MATH_H__ #include "opencv2/fuzzy/types.hpp" #include "opencv2/core.hpp" namespace cv { namespace ft { //! @addtogroup f0_math //! @{ /** @brief Computes components of the array using direct F0-transform. @param matrix Input 1-channel array. @param kernel Kernel used for processing. Function **createKernel** can be used. @param components Output 32-bit array for the components. @param mask Mask can be used for unwanted area marking. The function computes components using predefined kernel and mask. @note F-transform technique is described in paper @cite Perf:FT. */ CV_EXPORTS void FT02D_components(InputArray matrix, InputArray kernel, OutputArray components, InputArray mask); /** @brief Computes components of the array using direct F0-transform. @param matrix Input 1-channel array. @param kernel Kernel used for processing. Function **createKernel** can be used. @param components Output 32-bit array for the components. The function computes components using predefined kernel. @note F-transform technique is described in paper @cite Perf:FT. */ CV_EXPORTS void FT02D_components(InputArray matrix, InputArray kernel, OutputArray components); /** @brief Computes inverse F0-transfrom. @param components Input 32-bit array for the components. @param kernel Kernel used for processing. Function **createKernel** can be used. @param output Output 32-bit array. @param width Width of the output array. @param height Height of the output array. @note F-transform technique is described in paper @cite Perf:FT. */ CV_EXPORTS void FT02D_inverseFT(InputArray components, InputArray kernel, OutputArray output, int width, int height); /** @brief Computes F0-transfrom and inverse F0-transfrom at once. @param image Input image. @param kernel Kernel used for processing. Function **createKernel** can be used. @param output Output 32-bit array. @param mask Mask used for unwanted area marking. This function computes F-transfrom and inverse F-transfotm in one step. It is fully sufficient and optimized for **Mat**. */ CV_EXPORTS void FT02D_process(const Mat &image, const Mat &kernel, Mat &output, const Mat &mask); /** @brief Computes F0-transfrom and inverse F0-transfrom at once and return state. @param image Input image. @param kernel Kernel used for processing. Function **createKernel** can be used. @param imageOutput Output 32-bit array. @param mask Mask used for unwanted area marking. @param maskOutput Mask after one iteration. @param firstStop If **true** function returns -1 when first problem appears. In case of **false**, the process is completed and summation of all problems returned. This function computes iteration of F-transfrom and inverse F-transfotm and handle image and mask change. The function is used in *inpaint* function. */ CV_EXPORTS int FT02D_iteration(const Mat &image, const Mat &kernel, Mat &imageOutput, const Mat &mask, Mat &maskOutput, bool firstStop = true); //! @} } } #endif // __OPENCV_FUZZY_F0_MATH_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/fuzzy/fuzzy_image.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, University of Ostrava, Institute for Research and Applications of Fuzzy Modeling, // Pavel Vlasanek, all rights reserved. Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_FUZZY_IMAGE_H__ #define __OPENCV_FUZZY_IMAGE_H__ #include "types.hpp" #include "opencv2/core.hpp" namespace cv { namespace ft { //! @addtogroup f_image //! @{ /** @brief Creates kernel from basic functions. @param A Basic function used in axis **x**. @param B Basic function used in axis **y**. @param kernel Final 32-b kernel derived from **A** and **B**. @param chn Number of kernel channels. The function creates kernel usable for latter fuzzy image processing. */ CV_EXPORTS void createKernel(cv::InputArray A, cv::InputArray B, cv::OutputArray kernel, const int chn = 1); /** @brief Creates kernel from general functions. @param function Function type could be one of the following: - **LINEAR** Linear basic function. @param radius Radius of the basic function. @param kernel Final 32-b kernel. @param chn Number of kernel channels. The function creates kernel from predefined functions. */ CV_EXPORTS void createKernel(int function, int radius, cv::OutputArray kernel, const int chn = 1); /** @brief Image inpainting @param image Input image. @param mask Mask used for unwanted area marking. @param output Output 32-bit image. @param radius Radius of the basic function. @param function Function type could be one of the following: - **LINEAR** Linear basic function. @param algorithm Algorithm could be one of the following: - **ONE_STEP** One step algorithm. - **MULTI_STEP** Algorithm automaticaly increasing radius of the basic function. - **ITERATIVE** Iterative algorithm running in more steps using partial computations. This function provides inpainting technique based on the fuzzy mathematic. @note The algorithms are described in paper @cite Perf:rec. */ CV_EXPORTS void inpaint(const cv::Mat &image, const cv::Mat &mask, cv::Mat &output, int radius = 2, int function = ft::LINEAR, int algorithm = ft::ONE_STEP); /** @brief Image filtering @param image Input image. @param kernel Final 32-b kernel. @param output Output 32-bit image. Filtering of the input image by means of F-transform. */ CV_EXPORTS void filter(const cv::Mat &image, const cv::Mat &kernel, cv::Mat &output); //! @} } } #endif // __OPENCV_FUZZY_IMAGE_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/fuzzy/types.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, University of Ostrava, Institute for Research and Applications of Fuzzy Modeling, // Pavel Vlasanek, all rights reserved. Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_FUZZY_TYPES_H__ #define __OPENCV_FUZZY_TYPES_H__ namespace cv { namespace ft { //! @addtogroup fuzzy //! @{ enum { LINEAR = 1, SINUS = 2 }; enum { ONE_STEP = 1, MULTI_STEP = 2, ITERATIVE = 3 }; //! @} } } #endif // __OPENCV_FUZZY_TYPES_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/fuzzy.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2015, University of Ostrava, Institute for Research and Applications of Fuzzy Modeling, // Pavel Vlasanek, all rights reserved. Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_FUZZY_H__ #define __OPENCV_FUZZY_H__ #include "opencv2/fuzzy/types.hpp" #include "opencv2/fuzzy/fuzzy_F0_math.hpp" #include "opencv2/fuzzy/fuzzy_image.hpp" /** @defgroup fuzzy Image processing based on fuzzy mathematics Namespace for all functions is **ft**. The module brings implementation of the last image processing algorithms based on fuzzy mathematics. @{ @defgroup f0_math Math with F0-transfrom support Fuzzy transform (F-transform) of the 0th degree transform whole image to a vector of its components. These components are used in latter computation. @defgroup f_image Fuzzy image processing Image proceesing based on F-transform is fast to process and easy to understand. @} */ #endif // __OPENCV_FUZZY_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/highgui/highgui.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/highgui.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/highgui/highgui_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HIGHGUI_H__ #define __OPENCV_HIGHGUI_H__ #include "opencv2/core/core_c.h" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/imgcodecs/imgcodecs_c.h" #include "opencv2/videoio/videoio_c.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup highgui_c @{ */ /****************************************************************************************\ * Basic GUI functions * \****************************************************************************************/ //YV //-----------New for Qt /* For font */ enum { CV_FONT_LIGHT = 25,//QFont::Light, CV_FONT_NORMAL = 50,//QFont::Normal, CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, CV_FONT_BOLD = 75,//QFont::Bold, CV_FONT_BLACK = 87 //QFont::Black }; enum { CV_STYLE_NORMAL = 0,//QFont::StyleNormal, CV_STYLE_ITALIC = 1,//QFont::StyleItalic, CV_STYLE_OBLIQUE = 2 //QFont::StyleOblique }; /* ---------*/ //for color cvScalar(blue_component, green_component, red_component[, alpha_component]) //and alpha= 0 <-> 0xFF (not transparent <-> transparent) CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvScalar color CV_DEFAULT(cvScalarAll(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0)); CVAPI(void) cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont *arg2); CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms CV_DEFAULT(0)); CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms CV_DEFAULT(0)); CVAPI(void) cvSaveWindowParameters(const char* name); CVAPI(void) cvLoadWindowParameters(const char* name); CVAPI(int) cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); CVAPI(void) cvStopLoop( void ); typedef void (CV_CDECL *CvButtonCallback)(int state, void* userdata); enum {CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2}; CVAPI(int) cvCreateButton( const char* button_name CV_DEFAULT(NULL),CvButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)); //---------------------- /* this function is used to set some external parameters in case of X Window */ CVAPI(int) cvInitSystem( int argc, char** argv ); CVAPI(int) cvStartWindowThread( void ); // --------- YV --------- enum { //These 3 flags are used by cvSet/GetWindowProperty CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed CV_WINDOW_OPENGL = 0x00001000, //window with opengl support //Those flags are only for Qt CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar CV_GUI_NORMAL = 0x00000010, //old fashious way //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) CV_WINDOW_KEEPRATIO = 0x00000000//the ration image is respected. }; /* create window */ CVAPI(int) cvNamedWindow( const char* name, int flags CV_DEFAULT(CV_WINDOW_AUTOSIZE) ); /* Set and Get Property of the window */ CVAPI(void) cvSetWindowProperty(const char* name, int prop_id, double prop_value); CVAPI(double) cvGetWindowProperty(const char* name, int prop_id); /* display image within window (highgui windows remember their content) */ CVAPI(void) cvShowImage( const char* name, const CvArr* image ); /* resize/move window */ CVAPI(void) cvResizeWindow( const char* name, int width, int height ); CVAPI(void) cvMoveWindow( const char* name, int x, int y ); /* destroy window and all the trackers associated with it */ CVAPI(void) cvDestroyWindow( const char* name ); CVAPI(void) cvDestroyAllWindows(void); /* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ CVAPI(void*) cvGetWindowHandle( const char* name ); /* get name of highgui window given its native handle */ CVAPI(const char*) cvGetWindowName( void* window_handle ); typedef void (CV_CDECL *CvTrackbarCallback)(int pos); /* create trackbar and display it on top of given window, set callback */ CVAPI(int) cvCreateTrackbar( const char* trackbar_name, const char* window_name, int* value, int count, CvTrackbarCallback on_change CV_DEFAULT(NULL)); typedef void (CV_CDECL *CvTrackbarCallback2)(int pos, void* userdata); CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata CV_DEFAULT(0)); /* retrieve or set trackbar position */ CVAPI(int) cvGetTrackbarPos( const char* trackbar_name, const char* window_name ); CVAPI(void) cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos ); CVAPI(void) cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval); CVAPI(void) cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval); enum { CV_EVENT_MOUSEMOVE =0, CV_EVENT_LBUTTONDOWN =1, CV_EVENT_RBUTTONDOWN =2, CV_EVENT_MBUTTONDOWN =3, CV_EVENT_LBUTTONUP =4, CV_EVENT_RBUTTONUP =5, CV_EVENT_MBUTTONUP =6, CV_EVENT_LBUTTONDBLCLK =7, CV_EVENT_RBUTTONDBLCLK =8, CV_EVENT_MBUTTONDBLCLK =9, CV_EVENT_MOUSEWHEEL =10, CV_EVENT_MOUSEHWHEEL =11 }; enum { CV_EVENT_FLAG_LBUTTON =1, CV_EVENT_FLAG_RBUTTON =2, CV_EVENT_FLAG_MBUTTON =4, CV_EVENT_FLAG_CTRLKEY =8, CV_EVENT_FLAG_SHIFTKEY =16, CV_EVENT_FLAG_ALTKEY =32 }; #define CV_GET_WHEEL_DELTA(flags) ((short)((flags >> 16) & 0xffff)) // upper 16 bits typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param); /* assign callback for mouse events */ CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* param CV_DEFAULT(NULL)); /* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0)); // OpenGL support typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); CVAPI(void) cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata CV_DEFAULT(NULL)); CVAPI(void) cvSetOpenGlContext(const char* window_name); CVAPI(void) cvUpdateWindow(const char* window_name); /****************************************************************************************\ * Obsolete functions/synonyms * \****************************************************************************************/ #define cvAddSearchPath(path) #define cvvInitSystem cvInitSystem #define cvvNamedWindow cvNamedWindow #define cvvShowImage cvShowImage #define cvvResizeWindow cvResizeWindow #define cvvDestroyWindow cvDestroyWindow #define cvvCreateTrackbar cvCreateTrackbar #define cvvAddSearchPath cvAddSearchPath #define cvvWaitKey(name) cvWaitKey(0) #define cvvWaitKeyEx(name,delay) cvWaitKey(delay) #define HG_AUTOSIZE CV_WINDOW_AUTOSIZE #define set_preprocess_func cvSetPreprocessFuncWin32 #define set_postprocess_func cvSetPostprocessFuncWin32 #if defined WIN32 || defined _WIN32 CVAPI(void) cvSetPreprocessFuncWin32_(const void* callback); CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback); #define cvSetPreprocessFuncWin32(callback) cvSetPreprocessFuncWin32_((const void*)(callback)) #define cvSetPostprocessFuncWin32(callback) cvSetPostprocessFuncWin32_((const void*)(callback)) #endif /** @} highgui_c */ #ifdef __cplusplus } #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/highgui.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_HIGHGUI_HPP__ #define __OPENCV_HIGHGUI_HPP__ #include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/videoio.hpp" /** @defgroup highgui High-level GUI While OpenCV was designed for use in full-scale applications and can be used within functionally rich UI frameworks (such as Qt\*, WinForms\*, or Cocoa\*) or without any UI at all, sometimes there it is required to try functionality quickly and visualize the results. This is what the HighGUI module has been designed for. It provides easy interface to: - Create and manipulate windows that can display images and "remember" their content (no need to handle repaint events from OS). - Add trackbars to the windows, handle simple mouse events as well as keyboard commands. @{ @defgroup highgui_opengl OpenGL support @defgroup highgui_qt Qt New Functions ![image](pics/qtgui.png) This figure explains new functionality implemented with Qt\* GUI. The new GUI provides a statusbar, a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it. If you cannot see the control panel, press Ctrl+P or right-click any Qt window and select **Display properties window**. - To attach a trackbar, the window name parameter must be NULL. - To attach a buttonbar, a button must be created. If the last bar attached to the control panel is a buttonbar, the new button is added to the right of the last button. If the last bar attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is created. Then, a new button is attached to it. See below the example used to generate the figure: @code int main(int argc, char *argv[]) { int value = 50; int value2 = 0; namedWindow("main1",WINDOW_NORMAL); namedWindow("main2",WINDOW_AUTOSIZE | CV_GUI_NORMAL); createTrackbar( "track1", "main1", &value, 255, NULL); String nameb1 = "button1"; String nameb2 = "button2"; createButton(nameb1,callbackButton,&nameb1,QT_CHECKBOX,1); createButton(nameb2,callbackButton,NULL,QT_CHECKBOX,0); createTrackbar( "track2", NULL, &value2, 255, NULL); createButton("button5",callbackButton1,NULL,QT_RADIOBOX,0); createButton("button6",callbackButton2,NULL,QT_RADIOBOX,1); setMouseCallback( "main2",on_mouse,NULL ); Mat img1 = imread("files/flower.jpg"); VideoCapture video; video.open("files/hockey.avi"); Mat img2,img3; while( waitKey(33) != 27 ) { img1.convertTo(img2,-1,1,value); video >> img3; imshow("main1",img2); imshow("main2",img3); } destroyAllWindows(); return 0; } @endcode @defgroup highgui_winrt WinRT support This figure explains new functionality implemented with WinRT GUI. The new GUI provides an Image control, and a slider panel. Slider panel holds trackbars attached to it. Sliders are attached below the image control. Every new slider is added below the previous one. See below the example used to generate the figure: @code void sample_app::MainPage::ShowWindow() { static cv::String windowName("sample"); cv::winrt_initContainer(this->cvContainer); cv::namedWindow(windowName); // not required cv::Mat image = cv::imread("Assets/sample.jpg"); cv::Mat converted = cv::Mat(image.rows, image.cols, CV_8UC4); cv::cvtColor(image, converted, COLOR_BGR2BGRA); cv::imshow(windowName, converted); // this will create window if it hasn't been created before int state = 42; cv::TrackbarCallback callback = [](int pos, void* userdata) { if (pos == 0) { cv::destroyWindow(windowName); } }; cv::TrackbarCallback callbackTwin = [](int pos, void* userdata) { if (pos >= 70) { cv::destroyAllWindows(); } }; cv::createTrackbar("Sample trackbar", windowName, &state, 100, callback); cv::createTrackbar("Twin brother", windowName, &state, 100, callbackTwin); } @endcode @defgroup highgui_c C API @} */ ///////////////////////// graphical user interface ////////////////////////// namespace cv { //! @addtogroup highgui //! @{ //! Flags for cv::namedWindow enum WindowFlags { WINDOW_NORMAL = 0x00000000, //!< the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size. WINDOW_AUTOSIZE = 0x00000001, //!< the user cannot resize the window, the size is constrainted by the image displayed. WINDOW_OPENGL = 0x00001000, //!< window with opengl support. WINDOW_FULLSCREEN = 1, //!< change the window to fullscreen. WINDOW_FREERATIO = 0x00000100, //!< the image expends as much as it can (no ratio constraint). WINDOW_KEEPRATIO = 0x00000000 //!< the ratio of the image is respected. }; //! Flags for cv::setWindowProperty / cv::getWindowProperty enum WindowPropertyFlags { WND_PROP_FULLSCREEN = 0, //!< fullscreen property (can be WINDOW_NORMAL or WINDOW_FULLSCREEN). WND_PROP_AUTOSIZE = 1, //!< autosize property (can be WINDOW_NORMAL or WINDOW_AUTOSIZE). WND_PROP_ASPECT_RATIO = 2, //!< window's aspect ration (can be set to WINDOW_FREERATIO or WINDOW_KEEPRATIO). WND_PROP_OPENGL = 3 //!< opengl support. }; //! Mouse Events see cv::MouseCallback enum MouseEventTypes { EVENT_MOUSEMOVE = 0, //!< indicates that the mouse pointer has moved over the window. EVENT_LBUTTONDOWN = 1, //!< indicates that the left mouse button is pressed. EVENT_RBUTTONDOWN = 2, //!< indicates that the right mouse button is pressed. EVENT_MBUTTONDOWN = 3, //!< indicates that the middle mouse button is pressed. EVENT_LBUTTONUP = 4, //!< indicates that left mouse button is released. EVENT_RBUTTONUP = 5, //!< indicates that right mouse button is released. EVENT_MBUTTONUP = 6, //!< indicates that middle mouse button is released. EVENT_LBUTTONDBLCLK = 7, //!< indicates that left mouse button is double clicked. EVENT_RBUTTONDBLCLK = 8, //!< indicates that right mouse button is double clicked. EVENT_MBUTTONDBLCLK = 9, //!< indicates that middle mouse button is double clicked. EVENT_MOUSEWHEEL = 10,//!< positive and negative values mean forward and backward scrolling, respectively. EVENT_MOUSEHWHEEL = 11 //!< positive and negative values mean right and left scrolling, respectively. }; //! Mouse Event Flags see cv::MouseCallback enum MouseEventFlags { EVENT_FLAG_LBUTTON = 1, //!< indicates that the left mouse button is down. EVENT_FLAG_RBUTTON = 2, //!< indicates that the right mouse button is down. EVENT_FLAG_MBUTTON = 4, //!< indicates that the middle mouse button is down. EVENT_FLAG_CTRLKEY = 8, //!< indicates that CTRL Key is pressed. EVENT_FLAG_SHIFTKEY = 16,//!< indicates that SHIFT Key is pressed. EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed. }; //! Qt font weight enum QtFontWeights { QT_FONT_LIGHT = 25, //!< Weight of 25 QT_FONT_NORMAL = 50, //!< Weight of 50 QT_FONT_DEMIBOLD = 63, //!< Weight of 63 QT_FONT_BOLD = 75, //!< Weight of 75 QT_FONT_BLACK = 87 //!< Weight of 87 }; //! Qt font style enum QtFontStyles { QT_STYLE_NORMAL = 0, //!< Normal font. QT_STYLE_ITALIC = 1, //!< Italic font. QT_STYLE_OBLIQUE = 2 //!< Oblique font. }; //! Qt "button" type enum QtButtonTypes { QT_PUSH_BUTTON = 0, //!< Push button. QT_CHECKBOX = 1, //!< Checkbox button. QT_RADIOBOX = 2 //!< Radiobox button. }; /** @brief Callback function for mouse events. see cv::setMouseCallback @param event one of the cv::MouseEventTypes constants. @param x The x-coordinate of the mouse event. @param y The y-coordinate of the mouse event. @param flags one of the cv::MouseEventFlags constants. @param userdata The optional parameter. */ typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata); /** @brief Callback function for Trackbar see cv::createTrackbar @param pos current position of the specified trackbar. @param userdata The optional parameter. */ typedef void (*TrackbarCallback)(int pos, void* userdata); /** @brief Callback function defined to be called every frame. See cv::setOpenGlDrawCallback @param userdata The optional parameter. */ typedef void (*OpenGlDrawCallback)(void* userdata); /** @brief Callback function for a button created by cv::createButton @param state current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. @param userdata The optional parameter. */ typedef void (*ButtonCallback)(int state, void* userdata); /** @brief Creates a window. The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names. If a window with the same name already exists, the function does nothing. You can call cv::destroyWindow or cv::destroyAllWindows to close the window and de-allocate any associated memory usage. For a simple program, you do not really have to call these functions because all the resources and windows of the application are closed automatically by the operating system upon exit. @note Qt backend supports additional flags: - **WINDOW_NORMAL or WINDOW_AUTOSIZE:** WINDOW_NORMAL enables you to resize the window, whereas WINDOW_AUTOSIZE adjusts automatically the window size to fit the displayed image (see imshow ), and you cannot change the window size manually. - **WINDOW_FREERATIO or WINDOW_KEEPRATIO:** WINDOW_FREERATIO adjusts the image with no respect to its ratio, whereas WINDOW_KEEPRATIO keeps the image ratio. - **CV_GUI_NORMAL or CV_GUI_EXPANDED:** CV_GUI_NORMAL is the old way to draw the window without statusbar and toolbar, whereas CV_GUI_EXPANDED is a new enhanced GUI. By default, flags == WINDOW_AUTOSIZE | WINDOW_KEEPRATIO | CV_GUI_EXPANDED @param winname Name of the window in the window caption that may be used as a window identifier. @param flags Flags of the window. The supported flags are: (cv::WindowFlags) */ CV_EXPORTS_W void namedWindow(const String& winname, int flags = WINDOW_AUTOSIZE); /** @brief Destroys the specified window. The function destroyWindow destroys the window with the given name. @param winname Name of the window to be destroyed. */ CV_EXPORTS_W void destroyWindow(const String& winname); /** @brief Destroys all of the HighGUI windows. The function destroyAllWindows destroys all of the opened HighGUI windows. */ CV_EXPORTS_W void destroyAllWindows(); CV_EXPORTS_W int startWindowThread(); /** @brief Waits for a pressed key. The function waitKey waits for a key event infinitely (when \f$\texttt{delay}\leq 0\f$ ) or for delay milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is running on your computer at that time. It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed. @note This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing. @note The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active. @param delay Delay in milliseconds. 0 is the special value that means "forever". */ CV_EXPORTS_W int waitKey(int delay = 0); /** @brief Displays an image in the specified window. The function imshow displays an image in the specified window. If the window was created with the cv::WINDOW_AUTOSIZE flag, the image is shown with its original size, however it is still limited by the screen resolution. Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth: - If the image is 8-bit unsigned, it is displayed as is. - If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255\*256] is mapped to [0,255]. - If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255]. If window was created with OpenGL support, cv::imshow also support ogl::Buffer , ogl::Texture2D and cuda::GpuMat as input. If the window was not created before this function, it is assumed creating a window with cv::WINDOW_AUTOSIZE. If you need to show an image that is bigger than the screen resolution, you will need to call namedWindow("", WINDOW_NORMAL) before the imshow. @note This function should be followed by cv::waitKey function which displays the image for specified milliseconds. Otherwise, it won't display the image. For example, **waitKey(0)** will display the window infinitely until any keypress (it is suitable for image display). **waitKey(25)** will display a frame for 25 ms, after which display will be automatically closed. (If you put it in a loop to read videos, it will display the video frame-by-frame) @note [__Windows Backend Only__] Pressing Ctrl+C will copy the image to the clipboard. [__Windows Backend Only__] Pressing Ctrl+S will show a dialog to save the image. @param winname Name of the window. @param mat Image to be shown. */ CV_EXPORTS_W void imshow(const String& winname, InputArray mat); /** @brief Resizes window to the specified size @note - The specified window size is for the image area. Toolbars are not counted. - Only windows created without cv::WINDOW_AUTOSIZE flag can be resized. @param winname Window name. @param width The new window width. @param height The new window height. */ CV_EXPORTS_W void resizeWindow(const String& winname, int width, int height); /** @brief Moves window to the specified position @param winname Name of the window. @param x The new x-coordinate of the window. @param y The new y-coordinate of the window. */ CV_EXPORTS_W void moveWindow(const String& winname, int x, int y); /** @brief Changes parameters of a window dynamically. The function setWindowProperty enables changing properties of a window. @param winname Name of the window. @param prop_id Window property to edit. The supported operation flags are: (cv::WindowPropertyFlags) @param prop_value New value of the window property. The supported flags are: (cv::WindowFlags) */ CV_EXPORTS_W void setWindowProperty(const String& winname, int prop_id, double prop_value); /** @brief Updates window title @param winname Name of the window. @param title New title. */ CV_EXPORTS_W void setWindowTitle(const String& winname, const String& title); /** @brief Provides parameters of a window. The function getWindowProperty returns properties of a window. @param winname Name of the window. @param prop_id Window property to retrieve. The following operation flags are available: (cv::WindowPropertyFlags) @sa setWindowProperty */ CV_EXPORTS_W double getWindowProperty(const String& winname, int prop_id); /** @brief Sets mouse handler for the specified window @param winname Name of the window. @param onMouse Mouse callback. See OpenCV samples, such as , on how to specify and use the callback. @param userdata The optional parameter passed to the callback. */ CV_EXPORTS void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0); /** @brief Gets the mouse-wheel motion delta, when handling mouse-wheel events cv::EVENT_MOUSEWHEEL and cv::EVENT_MOUSEHWHEEL. For regular mice with a scroll-wheel, delta will be a multiple of 120. The value 120 corresponds to a one notch rotation of the wheel or the threshold for action to be taken and one such action should occur for each delta. Some high-precision mice with higher-resolution freely-rotating wheels may generate smaller values. For cv::EVENT_MOUSEWHEEL positive and negative values mean forward and backward scrolling, respectively. For cv::EVENT_MOUSEHWHEEL, where available, positive and negative values mean right and left scrolling, respectively. With the C API, the macro CV_GET_WHEEL_DELTA(flags) can be used alternatively. @note Mouse-wheel events are currently supported only on Windows. @param flags The mouse callback flags parameter. */ CV_EXPORTS int getMouseWheelDelta(int flags); /** @brief Creates a trackbar and attaches it to the specified window. The function createTrackbar creates a trackbar (a slider or range control) with the specified name and range, assigns a variable value to be a position synchronized with the trackbar and specifies the callback function onChange to be called on the trackbar position change. The created trackbar is displayed in the specified window winname. @note [__Qt Backend Only__] winname can be empty (or NULL) if the trackbar should be attached to the control panel. Clicking the label of each trackbar enables editing the trackbar values manually. @param trackbarname Name of the created trackbar. @param winname Name of the window that will be used as a parent of the created trackbar. @param value Optional pointer to an integer variable whose value reflects the position of the slider. Upon creation, the slider position is defined by this variable. @param count Maximal position of the slider. The minimal position is always 0. @param onChange Pointer to the function to be called every time the slider changes position. This function should be prototyped as void Foo(int,void\*); , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is the NULL pointer, no callbacks are called, but only value is updated. @param userdata User data that is passed as is to the callback. It can be used to handle trackbar events without using global variables. */ CV_EXPORTS int createTrackbar(const String& trackbarname, const String& winname, int* value, int count, TrackbarCallback onChange = 0, void* userdata = 0); /** @brief Returns the trackbar position. The function returns the current position of the specified trackbar. @note [__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control panel. @param trackbarname Name of the trackbar. @param winname Name of the window that is the parent of the trackbar. */ CV_EXPORTS_W int getTrackbarPos(const String& trackbarname, const String& winname); /** @brief Sets the trackbar position. The function sets the position of the specified trackbar in the specified window. @note [__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control panel. @param trackbarname Name of the trackbar. @param winname Name of the window that is the parent of trackbar. @param pos New position. */ CV_EXPORTS_W void setTrackbarPos(const String& trackbarname, const String& winname, int pos); /** @brief Sets the trackbar maximum position. The function sets the maximum position of the specified trackbar in the specified window. @note [__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control panel. @param trackbarname Name of the trackbar. @param winname Name of the window that is the parent of trackbar. @param maxval New maximum position. */ CV_EXPORTS_W void setTrackbarMax(const String& trackbarname, const String& winname, int maxval); /** @brief Sets the trackbar minimum position. The function sets the minimum position of the specified trackbar in the specified window. @note [__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control panel. @param trackbarname Name of the trackbar. @param winname Name of the window that is the parent of trackbar. @param minval New maximum position. */ CV_EXPORTS_W void setTrackbarMin(const String& trackbarname, const String& winname, int minval); //! @addtogroup highgui_opengl OpenGL support //! @{ /** @brief Displays OpenGL 2D texture in the specified window. @param winname Name of the window. @param tex OpenGL 2D texture data. */ CV_EXPORTS void imshow(const String& winname, const ogl::Texture2D& tex); /** @brief Sets a callback function to be called to draw on top of displayed image. The function setOpenGlDrawCallback can be used to draw 3D data on the window. See the example of callback function below: @code void on_opengl(void* param) { glLoadIdentity(); glTranslated(0.0, 0.0, -1.0); glRotatef( 55, 1, 0, 0 ); glRotatef( 45, 0, 1, 0 ); glRotatef( 0, 0, 0, 1 ); static const int coords[6][4][3] = { { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } }; for (int i = 0; i < 6; ++i) { glColor3ub( i*20, 100+i*10, i*42 ); glBegin(GL_QUADS); for (int j = 0; j < 4; ++j) { glVertex3d(0.2 * coords[i][j][0], 0.2 * coords[i][j][1], 0.2 * coords[i][j][2]); } glEnd(); } } @endcode @param winname Name of the window. @param onOpenGlDraw Pointer to the function to be called every frame. This function should be prototyped as void Foo(void\*) . @param userdata Pointer passed to the callback function.(__Optional__) */ CV_EXPORTS void setOpenGlDrawCallback(const String& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0); /** @brief Sets the specified window as current OpenGL context. @param winname Name of the window. */ CV_EXPORTS void setOpenGlContext(const String& winname); /** @brief Force window to redraw its context and call draw callback ( See cv::setOpenGlDrawCallback ). @param winname Name of the window. */ CV_EXPORTS void updateWindow(const String& winname); //! @} highgui_opengl //! @addtogroup highgui_qt //! @{ /** @brief QtFont available only for Qt. See cv::fontQt */ struct QtFont { const char* nameFont; //!< Name of the font Scalar color; //!< Color of the font. Scalar(blue_component, green_component, red_component[, alpha_component]) int font_face; //!< See cv::QtFontStyles const int* ascii; //!< font data and metrics const int* greek; const int* cyrillic; float hscale, vscale; float shear; //!< slope coefficient: 0 - normal, >0 - italic int thickness; //!< See cv::QtFontWeights float dx; //!< horizontal interval between letters int line_type; //!< PointSize }; /** @brief Creates the font to draw a text on an image. The function fontQt creates a cv::QtFont object. This cv::QtFont is not compatible with putText . A basic usage of this function is the following: : @code QtFont font = fontQt("Times"); addText( img1, "Hello World !", Point(50,50), font); @endcode @param nameFont Name of the font. The name should match the name of a system font (such as *Times*). If the font is not found, a default one is used. @param pointSize Size of the font. If not specified, equal zero or negative, the point size of the font is set to a system-dependent default value. Generally, this is 12 points. @param color Color of the font in BGRA where A = 255 is fully transparent. Use the macro CV_RGB for simplicity. @param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. @param style Font style. Available operation flags are : cv::QtFontStyles @param spacing Spacing between characters. It can be negative or positive. */ CV_EXPORTS QtFont fontQt(const String& nameFont, int pointSize = -1, Scalar color = Scalar::all(0), int weight = QT_FONT_NORMAL, int style = QT_STYLE_NORMAL, int spacing = 0); /** @brief Draws a text on the image. The function addText draws *text* on the image *img* using a specific font *font* (see example cv::fontQt ) @param img 8-bit 3-channel image where the text should be drawn. @param text Text to write on an image. @param org Point(x,y) where the text should start on an image. @param font Font to use to draw a text. */ CV_EXPORTS void addText( const Mat& img, const String& text, Point org, const QtFont& font); /** @brief Displays a text on a window image as an overlay for a specified duration. The function displayOverlay displays useful information/tips on top of the window for a certain amount of time *delayms*. The function does not modify the image, displayed in the window, that is, after the specified delay the original content of the window is restored. @param winname Name of the window. @param text Overlay text to write on a window image. @param delayms The period (in milliseconds), during which the overlay text is displayed. If this function is called before the previous overlay text timed out, the timer is restarted and the text is updated. If this value is zero, the text never disappears. */ CV_EXPORTS void displayOverlay(const String& winname, const String& text, int delayms = 0); /** @brief Displays a text on the window statusbar during the specified period of time. The function displayStatusBar displays useful information/tips on top of the window for a certain amount of time *delayms* . This information is displayed on the window statusbar (the window must be created with the CV_GUI_EXPANDED flags). @param winname Name of the window. @param text Text to write on the window statusbar. @param delayms Duration (in milliseconds) to display the text. If this function is called before the previous text timed out, the timer is restarted and the text is updated. If this value is zero, the text never disappears. */ CV_EXPORTS void displayStatusBar(const String& winname, const String& text, int delayms = 0); /** @brief Saves parameters of the specified window. The function saveWindowParameters saves size, location, flags, trackbars value, zoom and panning location of the window windowName. @param windowName Name of the window. */ CV_EXPORTS void saveWindowParameters(const String& windowName); /** @brief Loads parameters of the specified window. The function loadWindowParameters loads size, location, flags, trackbars value, zoom and panning location of the window windowName. @param windowName Name of the window. */ CV_EXPORTS void loadWindowParameters(const String& windowName); CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); CV_EXPORTS void stopLoop(); /** @brief Attaches a button to the control panel. The function createButton attaches a button to the control panel. Each button is added to a buttonbar to the right of the last button. A new buttonbar is created if nothing was attached to the control panel before, or if the last element attached to the control panel was a trackbar. See below various examples of the cv::createButton function call: : @code createButton(NULL,callbackButton);//create a push button "button 0", that will call callbackButton. createButton("button2",callbackButton,NULL,QT_CHECKBOX,0); createButton("button3",callbackButton,&value); createButton("button5",callbackButton1,NULL,QT_RADIOBOX); createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON,1); @endcode @param bar_name Name of the button. @param on_change Pointer to the function to be called every time the button changes its state. This function should be prototyped as void Foo(int state,\*void); . *state* is the current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. @param userdata Pointer passed to the callback function. @param type Optional type of the button. Available types are: (cv::QtButtonTypes) @param initial_button_state Default state of the button. Use for checkbox and radiobox. Its value could be 0 or 1. (__Optional__) */ CV_EXPORTS int createButton( const String& bar_name, ButtonCallback on_change, void* userdata = 0, int type = QT_PUSH_BUTTON, bool initial_button_state = false); //! @} highgui_qt //! @} highgui } // cv #ifndef DISABLE_OPENCV_24_COMPATIBILITY #include "opencv2/highgui/highgui_c.h" #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgcodecs/imgcodecs.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/imgcodecs.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgcodecs/imgcodecs_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_IMGCODECS_H__ #define __OPENCV_IMGCODECS_H__ #include "opencv2/core/core_c.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup imgcodecs_c @{ */ enum { /* 8bit, color or not */ CV_LOAD_IMAGE_UNCHANGED =-1, /* 8bit, gray */ CV_LOAD_IMAGE_GRAYSCALE =0, /* ?, color */ CV_LOAD_IMAGE_COLOR =1, /* any depth, ? */ CV_LOAD_IMAGE_ANYDEPTH =2, /* ?, any color */ CV_LOAD_IMAGE_ANYCOLOR =4 }; /* load image from file iscolor can be a combination of above flags where CV_LOAD_IMAGE_UNCHANGED overrides the other flags using CV_LOAD_IMAGE_ANYCOLOR alone is equivalent to CV_LOAD_IMAGE_UNCHANGED unless CV_LOAD_IMAGE_ANYDEPTH is specified images are converted to 8bit */ CVAPI(IplImage*) cvLoadImage( const char* filename, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR)); CVAPI(CvMat*) cvLoadImageM( const char* filename, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR)); enum { CV_IMWRITE_JPEG_QUALITY =1, CV_IMWRITE_JPEG_PROGRESSIVE =2, CV_IMWRITE_JPEG_OPTIMIZE =3, CV_IMWRITE_JPEG_RST_INTERVAL =4, CV_IMWRITE_JPEG_LUMA_QUALITY =5, CV_IMWRITE_JPEG_CHROMA_QUALITY =6, CV_IMWRITE_PNG_COMPRESSION =16, CV_IMWRITE_PNG_STRATEGY =17, CV_IMWRITE_PNG_BILEVEL =18, CV_IMWRITE_PNG_STRATEGY_DEFAULT =0, CV_IMWRITE_PNG_STRATEGY_FILTERED =1, CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2, CV_IMWRITE_PNG_STRATEGY_RLE =3, CV_IMWRITE_PNG_STRATEGY_FIXED =4, CV_IMWRITE_PXM_BINARY =32, CV_IMWRITE_WEBP_QUALITY =64 }; /* save image to file */ CVAPI(int) cvSaveImage( const char* filename, const CvArr* image, const int* params CV_DEFAULT(0) ); /* decode image stored in the buffer */ CVAPI(IplImage*) cvDecodeImage( const CvMat* buf, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR)); CVAPI(CvMat*) cvDecodeImageM( const CvMat* buf, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR)); /* encode image and store the result as a byte vector (single-row 8uC1 matrix) */ CVAPI(CvMat*) cvEncodeImage( const char* ext, const CvArr* image, const int* params CV_DEFAULT(0) ); enum { CV_CVTIMG_FLIP =1, CV_CVTIMG_SWAP_RB =2 }; /* utility function: convert one image to another with optional vertical flip */ CVAPI(void) cvConvertImage( const CvArr* src, CvArr* dst, int flags CV_DEFAULT(0)); CVAPI(int) cvHaveImageReader(const char* filename); CVAPI(int) cvHaveImageWriter(const char* filename); /****************************************************************************************\ * Obsolete functions/synonyms * \****************************************************************************************/ #define cvvLoadImage(name) cvLoadImage((name),1) #define cvvSaveImage cvSaveImage #define cvvConvertImage cvConvertImage /** @} imgcodecs_c */ #ifdef __cplusplus } #endif #endif // __OPENCV_IMGCODECS_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgcodecs/ios.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #import #import #import #import #include "opencv2/core/core.hpp" //! @addtogroup imgcodecs_ios //! @{ UIImage* MatToUIImage(const cv::Mat& image); void UIImageToMat(const UIImage* image, cv::Mat& m, bool alphaExist = false); //! @} ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgcodecs.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_IMGCODECS_HPP__ #define __OPENCV_IMGCODECS_HPP__ #include "opencv2/core.hpp" /** @defgroup imgcodecs Image file reading and writing @{ @defgroup imgcodecs_c C API @defgroup imgcodecs_ios iOS glue @} */ //////////////////////////////// image codec //////////////////////////////// namespace cv { //! @addtogroup imgcodecs //! @{ //! Imread flags enum ImreadModes { IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image. IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image. IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. IMREAD_REDUCED_COLOR_8 = 65 //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. }; //! Imwrite flags enum ImwriteFlags { IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is 0 - don't use. IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is 0 - don't use. IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3. IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_DEFAULT. IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. IMWRITE_WEBP_QUALITY = 64 //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. }; //! Imwrite PNG specific flags used to tune the compression algorithm. /** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. - The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. - IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data. - The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. - IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. */ enum ImwritePNGFlags { IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. }; /** @brief Loads an image from a file. @anchor imread 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: - Windows bitmaps - \*.bmp, \*.dib (always supported) - JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Notes* section) - JPEG 2000 files - \*.jp2 (see the *Notes* section) - Portable Network Graphics - \*.png (see the *Notes* section) - WebP - \*.webp (see the *Notes* section) - Portable image format - \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm (always supported) - Sun rasters - \*.sr, \*.ras (always supported) - TIFF files - \*.tiff, \*.tif (see the *Notes* section) - OpenEXR Image files - \*.exr (see the *Notes* section) - Radiance HDR - \*.hdr, \*.pic (always supported) - Raster and Vector geospatial data supported by Gdal (see the *Notes* section) @note - The function determines the type of an image by the content, not by the file extension. - In the case of color images, the decoded images will have the channels stored in **B G R** order. - 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. - 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. - In the case you set *WITH_GDAL* flag to true in CMake and @ref IMREAD_LOAD_GDAL to load the image, then [GDAL](http://www.gdal.org) driver will be used in order to decode the image by supporting the following formats: [Raster](http://www.gdal.org/formats_list.html), [Vector](http://www.gdal.org/ogr_formats.html). @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes */ CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR ); /** @brief Loads a multi-page image from a file. The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. @param mats A vector of Mat objects holding each page, if more than one. @sa cv::imread */ CV_EXPORTS_W bool imreadmulti(const String& filename, std::vector& mats, int flags = IMREAD_ANYCOLOR); /** @brief Saves an image to a specified file. The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see cv::imread for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) 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 Mat::convertTo , and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format. 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 : @code #include using namespace cv; using namespace std; void createAlphaMat(Mat &mat) { CV_Assert(mat.channels() == 4); for (int i = 0; i < mat.rows; ++i) { for (int j = 0; j < mat.cols; ++j) { Vec4b& bgra = mat.at(i, j); bgra[0] = UCHAR_MAX; // Blue bgra[1] = saturate_cast((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green bgra[2] = saturate_cast((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red bgra[3] = saturate_cast(0.5 * (bgra[1] + bgra[2])); // Alpha } } } int main(int argv, char **argc) { // Create mat with alpha channel Mat mat(480, 640, CV_8UC4); createAlphaMat(mat); vector compression_params; compression_params.push_back(IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); try { imwrite("alpha.png", mat, compression_params); } catch (cv::Exception& ex) { fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what()); return 1; } fprintf(stdout, "Saved PNG file with alpha data.\n"); return 0; } @endcode @param filename Name of the file. @param img Image to be saved. @param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags */ CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, const std::vector& params = std::vector()); /** @brief Reads an image from a buffer in memory. The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). See cv::imread for the list of supported formats and flags description. @note In the case of color images, the decoded images will have the channels stored in **B G R** order. @param buf Input array or vector of bytes. @param flags The same flags as in cv::imread, see cv::ImreadModes. */ CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); /** @overload @param buf @param flags @param dst The optional output placeholder for the decoded matrix. It can save the image reallocations when the function is called repeatedly for images of the same size. */ CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); /** @brief Encodes an image into a memory buffer. The function imencode compresses the image and stores it in the memory buffer that is resized to fit the result. See cv::imwrite for the list of supported formats and flags description. @param ext File extension that defines the output format. @param img Image to be written. @param buf Output buffer resized to fit the compressed image. @param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. */ CV_EXPORTS_W bool imencode( const String& ext, InputArray img, CV_OUT std::vector& buf, const std::vector& params = std::vector()); //! @} imgcodecs } // cv #endif //__OPENCV_IMGCODECS_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgproc/detail/distortion_model.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_IMGPROC_DETAIL_DISTORTION_MODEL_HPP__ #define __OPENCV_IMGPROC_DETAIL_DISTORTION_MODEL_HPP__ //! @cond IGNORED namespace cv { namespace detail { /** Computes the matrix for the projection onto a tilted image sensor \param tauX angular parameter rotation around x-axis \param tauY angular parameter rotation around y-axis \param matTilt if not NULL returns the matrix \f[ \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)} {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} {0}{0}{1} R(\tau_x, \tau_y) \f] where \f[ R(\tau_x, \tau_y) = \vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)} \vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} = \vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)} {0}{\cos(\tau_x)}{\sin(\tau_x)} {\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}. \f] \param dMatTiltdTauX if not NULL it returns the derivative of matTilt with respect to \f$\tau_x\f$. \param dMatTiltdTauY if not NULL it returns the derivative of matTilt with respect to \f$\tau_y\f$. \param invMatTilt if not NULL it returns the inverse of matTilt **/ template void computeTiltProjectionMatrix(FLOAT tauX, FLOAT tauY, Matx* matTilt = 0, Matx* dMatTiltdTauX = 0, Matx* dMatTiltdTauY = 0, Matx* invMatTilt = 0) { FLOAT cTauX = cos(tauX); FLOAT sTauX = sin(tauX); FLOAT cTauY = cos(tauY); FLOAT sTauY = sin(tauY); Matx matRotX = Matx(1,0,0,0,cTauX,sTauX,0,-sTauX,cTauX); Matx matRotY = Matx(cTauY,0,-sTauY,0,1,0,sTauY,0,cTauY); Matx matRotXY = matRotY * matRotX; Matx matProjZ = Matx(matRotXY(2,2),0,-matRotXY(0,2),0,matRotXY(2,2),-matRotXY(1,2),0,0,1); if (matTilt) { // Matrix for trapezoidal distortion of tilted image sensor *matTilt = matProjZ * matRotXY; } if (dMatTiltdTauX) { // Derivative with respect to tauX Matx dMatRotXYdTauX = matRotY * Matx(0,0,0,0,-sTauX,cTauX,0,-cTauX,-sTauX); Matx dMatProjZdTauX = Matx(dMatRotXYdTauX(2,2),0,-dMatRotXYdTauX(0,2), 0,dMatRotXYdTauX(2,2),-dMatRotXYdTauX(1,2),0,0,0); *dMatTiltdTauX = (matProjZ * dMatRotXYdTauX) + (dMatProjZdTauX * matRotXY); } if (dMatTiltdTauY) { // Derivative with respect to tauY Matx dMatRotXYdTauY = Matx(-sTauY,0,-cTauY,0,0,0,cTauY,0,-sTauY) * matRotX; Matx dMatProjZdTauY = Matx(dMatRotXYdTauY(2,2),0,-dMatRotXYdTauY(0,2), 0,dMatRotXYdTauY(2,2),-dMatRotXYdTauY(1,2),0,0,0); *dMatTiltdTauY = (matProjZ * dMatRotXYdTauY) + (dMatProjZdTauY * matRotXY); } if (invMatTilt) { FLOAT inv = 1./matRotXY(2,2); Matx invMatProjZ = Matx(inv,0,inv*matRotXY(0,2),0,inv,inv*matRotXY(1,2),0,0,1); *invMatTilt = matRotXY.t()*invMatProjZ; } } }} // namespace detail, cv //! @endcond #endif // __OPENCV_IMGPROC_DETAIL_DISTORTION_MODEL_HPP__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgproc/imgproc.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/imgproc.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgproc/imgproc_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_IMGPROC_IMGPROC_C_H__ #define __OPENCV_IMGPROC_IMGPROC_C_H__ #include "opencv2/imgproc/types_c.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup imgproc_c @{ */ /*********************** Background statistics accumulation *****************************/ /** @brief Adds image to accumulator @see cv::accumulate */ CVAPI(void) cvAcc( const CvArr* image, CvArr* sum, const CvArr* mask CV_DEFAULT(NULL) ); /** @brief Adds squared image to accumulator @see cv::accumulateSquare */ CVAPI(void) cvSquareAcc( const CvArr* image, CvArr* sqsum, const CvArr* mask CV_DEFAULT(NULL) ); /** @brief Adds a product of two images to accumulator @see cv::accumulateProduct */ CVAPI(void) cvMultiplyAcc( const CvArr* image1, const CvArr* image2, CvArr* acc, const CvArr* mask CV_DEFAULT(NULL) ); /** @brief Adds image to accumulator with weights: acc = acc*(1-alpha) + image*alpha @see cv::accumulateWeighted */ CVAPI(void) cvRunningAvg( const CvArr* image, CvArr* acc, double alpha, const CvArr* mask CV_DEFAULT(NULL) ); /****************************************************************************************\ * Image Processing * \****************************************************************************************/ /** Copies source 2D array inside of the larger destination array and makes a border of the specified type (IPL_BORDER_*) around the copied area. */ CVAPI(void) cvCopyMakeBorder( const CvArr* src, CvArr* dst, CvPoint offset, int bordertype, CvScalar value CV_DEFAULT(cvScalarAll(0))); /** @brief Smooths the image in one of several ways. @param src The source image @param dst The destination image @param smoothtype Type of the smoothing, see SmoothMethod_c @param size1 The first parameter of the smoothing operation, the aperture width. Must be a positive odd number (1, 3, 5, ...) @param size2 The second parameter of the smoothing operation, the aperture height. Ignored by CV_MEDIAN and CV_BILATERAL methods. In the case of simple scaled/non-scaled and Gaussian blur if size2 is zero, it is set to size1. Otherwise it must be a positive odd number. @param sigma1 In the case of a Gaussian parameter this parameter may specify Gaussian \f$\sigma\f$ (standard deviation). If it is zero, it is calculated from the kernel size: \f[\sigma = 0.3 (n/2 - 1) + 0.8 \quad \text{where} \quad n= \begin{array}{l l} \mbox{\texttt{size1} for horizontal kernel} \\ \mbox{\texttt{size2} for vertical kernel} \end{array}\f] Using standard sigma for small kernels ( \f$3\times 3\f$ to \f$7\times 7\f$ ) gives better speed. If sigma1 is not zero, while size1 and size2 are zeros, the kernel size is calculated from the sigma (to provide accurate enough operation). @param sigma2 additional parameter for bilateral filtering @see cv::GaussianBlur, cv::blur, cv::medianBlur, cv::bilateralFilter. */ CVAPI(void) cvSmooth( const CvArr* src, CvArr* dst, int smoothtype CV_DEFAULT(CV_GAUSSIAN), int size1 CV_DEFAULT(3), int size2 CV_DEFAULT(0), double sigma1 CV_DEFAULT(0), double sigma2 CV_DEFAULT(0)); /** @brief Convolves an image with the kernel. @param src input image. @param dst output image of the same size and the same number of channels as src. @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point matrix; if you want to apply different kernels to different channels, split the image into separate color planes using split and process them individually. @param anchor anchor of the kernel that indicates the relative position of a filtered point within the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor is at the kernel center. @see cv::filter2D */ CVAPI(void) cvFilter2D( const CvArr* src, CvArr* dst, const CvMat* kernel, CvPoint anchor CV_DEFAULT(cvPoint(-1,-1))); /** @brief Finds integral image: SUM(X,Y) = sum(x \texttt{hist1}(I)\)}{\frac{\texttt{hist2}(I) \cdot \texttt{scale}}{\texttt{hist1}(I)}}{if \(\texttt{hist1}(I) \ne 0\) and \(\texttt{hist2}(I) \le \texttt{hist1}(I)\)}\f] @param hist1 First histogram (the divisor). @param hist2 Second histogram. @param dst_hist Destination histogram. @param scale Scale factor for the destination histogram. */ CVAPI(void) cvCalcProbDensity( const CvHistogram* hist1, const CvHistogram* hist2, CvHistogram* dst_hist, double scale CV_DEFAULT(255) ); /** @brief equalizes histogram of 8-bit single-channel image @see cv::equalizeHist */ CVAPI(void) cvEqualizeHist( const CvArr* src, CvArr* dst ); /** @brief Applies distance transform to binary image @see cv::distanceTransform */ CVAPI(void) cvDistTransform( const CvArr* src, CvArr* dst, int distance_type CV_DEFAULT(CV_DIST_L2), int mask_size CV_DEFAULT(3), const float* mask CV_DEFAULT(NULL), CvArr* labels CV_DEFAULT(NULL), int labelType CV_DEFAULT(CV_DIST_LABEL_CCOMP)); /** @brief Applies fixed-level threshold to grayscale image. This is a basic operation applied before retrieving contours @see cv::threshold */ CVAPI(double) cvThreshold( const CvArr* src, CvArr* dst, double threshold, double max_value, int threshold_type ); /** @brief Applies adaptive threshold to grayscale image. The two parameters for methods CV_ADAPTIVE_THRESH_MEAN_C and CV_ADAPTIVE_THRESH_GAUSSIAN_C are: neighborhood size (3, 5, 7 etc.), and a constant subtracted from mean (...,-3,-2,-1,0,1,2,3,...) @see cv::adaptiveThreshold */ CVAPI(void) cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double max_value, int adaptive_method CV_DEFAULT(CV_ADAPTIVE_THRESH_MEAN_C), int threshold_type CV_DEFAULT(CV_THRESH_BINARY), int block_size CV_DEFAULT(3), double param1 CV_DEFAULT(5)); /** @brief Fills the connected component until the color difference gets large enough @see cv::floodFill */ CVAPI(void) cvFloodFill( CvArr* image, CvPoint seed_point, CvScalar new_val, CvScalar lo_diff CV_DEFAULT(cvScalarAll(0)), CvScalar up_diff CV_DEFAULT(cvScalarAll(0)), CvConnectedComp* comp CV_DEFAULT(NULL), int flags CV_DEFAULT(4), CvArr* mask CV_DEFAULT(NULL)); /****************************************************************************************\ * Feature detection * \****************************************************************************************/ /** @brief Runs canny edge detector @see cv::Canny */ CVAPI(void) cvCanny( const CvArr* image, CvArr* edges, double threshold1, double threshold2, int aperture_size CV_DEFAULT(3) ); /** @brief Calculates constraint image for corner detection Dx^2 * Dyy + Dxx * Dy^2 - 2 * Dx * Dy * Dxy. Applying threshold to the result gives coordinates of corners @see cv::preCornerDetect */ CVAPI(void) cvPreCornerDetect( const CvArr* image, CvArr* corners, int aperture_size CV_DEFAULT(3) ); /** @brief Calculates eigen values and vectors of 2x2 gradient covariation matrix at every image pixel @see cv::cornerEigenValsAndVecs */ CVAPI(void) cvCornerEigenValsAndVecs( const CvArr* image, CvArr* eigenvv, int block_size, int aperture_size CV_DEFAULT(3) ); /** @brief Calculates minimal eigenvalue for 2x2 gradient covariation matrix at every image pixel @see cv::cornerMinEigenVal */ CVAPI(void) cvCornerMinEigenVal( const CvArr* image, CvArr* eigenval, int block_size, int aperture_size CV_DEFAULT(3) ); /** @brief Harris corner detector: Calculates det(M) - k*(trace(M)^2), where M is 2x2 gradient covariation matrix for each pixel @see cv::cornerHarris */ CVAPI(void) cvCornerHarris( const CvArr* image, CvArr* harris_response, int block_size, int aperture_size CV_DEFAULT(3), double k CV_DEFAULT(0.04) ); /** @brief Adjust corner position using some sort of gradient search @see cv::cornerSubPix */ CVAPI(void) cvFindCornerSubPix( const CvArr* image, CvPoint2D32f* corners, int count, CvSize win, CvSize zero_zone, CvTermCriteria criteria ); /** @brief Finds a sparse set of points within the selected region that seem to be easy to track @see cv::goodFeaturesToTrack */ CVAPI(void) cvGoodFeaturesToTrack( const CvArr* image, CvArr* eig_image, CvArr* temp_image, CvPoint2D32f* corners, int* corner_count, double quality_level, double min_distance, const CvArr* mask CV_DEFAULT(NULL), int block_size CV_DEFAULT(3), int use_harris CV_DEFAULT(0), double k CV_DEFAULT(0.04) ); /** @brief Finds lines on binary image using one of several methods. line_storage is either memory storage or 1 x _max number of lines_ CvMat, its number of columns is changed by the function. method is one of CV_HOUGH_*; rho, theta and threshold are used for each of those methods; param1 ~ line length, param2 ~ line gap - for probabilistic, param1 ~ srn, param2 ~ stn - for multi-scale @see cv::HoughLines */ CVAPI(CvSeq*) cvHoughLines2( CvArr* image, void* line_storage, int method, double rho, double theta, int threshold, double param1 CV_DEFAULT(0), double param2 CV_DEFAULT(0), double min_theta CV_DEFAULT(0), double max_theta CV_DEFAULT(CV_PI)); /** @brief Finds circles in the image @see cv::HoughCircles */ CVAPI(CvSeq*) cvHoughCircles( CvArr* image, void* circle_storage, int method, double dp, double min_dist, double param1 CV_DEFAULT(100), double param2 CV_DEFAULT(100), int min_radius CV_DEFAULT(0), int max_radius CV_DEFAULT(0)); /** @brief Fits a line into set of 2d or 3d points in a robust way (M-estimator technique) @see cv::fitLine */ CVAPI(void) cvFitLine( const CvArr* points, int dist_type, double param, double reps, double aeps, float* line ); /****************************************************************************************\ * Drawing * \****************************************************************************************/ /****************************************************************************************\ * Drawing functions work with images/matrices of arbitrary type. * * For color images the channel order is BGR[A] * * Antialiasing is supported only for 8-bit image now. * * All the functions include parameter color that means rgb value (that may be * * constructed with CV_RGB macro) for color images and brightness * * for grayscale images. * * If a drawn figure is partially or completely outside of the image, it is clipped.* \****************************************************************************************/ #define CV_RGB( r, g, b ) cvScalar( (b), (g), (r), 0 ) #define CV_FILLED -1 #define CV_AA 16 /** @brief Draws 4-connected, 8-connected or antialiased line segment connecting two points @see cv::line */ CVAPI(void) cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); /** @brief Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2) if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn @see cv::rectangle */ CVAPI(void) cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); /** @brief Draws a rectangle specified by a CvRect structure @see cv::rectangle */ CVAPI(void) cvRectangleR( CvArr* img, CvRect r, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); /** @brief Draws a circle with specified center and radius. Thickness works in the same way as with cvRectangle @see cv::circle */ CVAPI(void) cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); /** @brief Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector depending on _thickness_, _start_angle_ and _end_angle_ parameters. The resultant figure is rotated by _angle_. All the angles are in degrees @see cv::ellipse */ CVAPI(void) cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle, double start_angle, double end_angle, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); CV_INLINE void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ) { CvSize axes; axes.width = cvRound(box.size.width*0.5); axes.height = cvRound(box.size.height*0.5); cvEllipse( img, cvPointFrom32f( box.center ), axes, box.angle, 0, 360, color, thickness, line_type, shift ); } /** @brief Fills convex or monotonous polygon. @see cv::fillConvexPoly */ CVAPI(void) cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); /** @brief Fills an area bounded by one or more arbitrary polygons @see cv::fillPoly */ CVAPI(void) cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, int contours, CvScalar color, int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); /** @brief Draws one or more polygonal curves @see cv::polylines */ CVAPI(void) cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, int is_closed, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); #define cvDrawRect cvRectangle #define cvDrawLine cvLine #define cvDrawCircle cvCircle #define cvDrawEllipse cvEllipse #define cvDrawPolyLine cvPolyLine /** @brief Clips the line segment connecting *pt1 and *pt2 by the rectangular window (0<=xptr will point to pt1 (or pt2, see left_to_right description) location in the image. Returns the number of pixels on the line between the ending points. @see cv::LineIterator */ CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, CvLineIterator* line_iterator, int connectivity CV_DEFAULT(8), int left_to_right CV_DEFAULT(0)); #define CV_NEXT_LINE_POINT( line_iterator ) \ { \ int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \ (line_iterator).err += (line_iterator).minus_delta + \ ((line_iterator).plus_delta & _line_iterator_mask); \ (line_iterator).ptr += (line_iterator).minus_step + \ ((line_iterator).plus_step & _line_iterator_mask); \ } #define CV_FONT_HERSHEY_SIMPLEX 0 #define CV_FONT_HERSHEY_PLAIN 1 #define CV_FONT_HERSHEY_DUPLEX 2 #define CV_FONT_HERSHEY_COMPLEX 3 #define CV_FONT_HERSHEY_TRIPLEX 4 #define CV_FONT_HERSHEY_COMPLEX_SMALL 5 #define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6 #define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7 #define CV_FONT_ITALIC 16 #define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX /** Font structure */ typedef struct CvFont { const char* nameFont; //Qt:nameFont CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red_component[, alpha_component]) int font_face; //Qt: bool italic /** =CV_FONT_* */ const int* ascii; //!< font data and metrics const int* greek; const int* cyrillic; float hscale, vscale; float shear; //!< slope coefficient: 0 - normal, >0 - italic int thickness; //!< Qt: weight /** letters thickness */ float dx; //!< horizontal interval between letters int line_type; //!< Qt: PointSize } CvFont; /** @brief Initializes font structure (OpenCV 1.x API). The function initializes the font structure that can be passed to text rendering functions. @param font Pointer to the font structure initialized by the function @param font_face Font name identifier. See cv::HersheyFonts and corresponding old CV_* identifiers. @param hscale Horizontal scale. If equal to 1.0f , the characters have the original width depending on the font type. If equal to 0.5f , the characters are of half the original width. @param vscale Vertical scale. If equal to 1.0f , the characters have the original height depending on the font type. If equal to 0.5f , the characters are of half the original height. @param shear Approximate tangent of the character slope relative to the vertical line. A zero value means a non-italic font, 1.0f means about a 45 degree slope, etc. @param thickness Thickness of the text strokes @param line_type Type of the strokes, see line description @sa cvPutText */ CVAPI(void) cvInitFont( CvFont* font, int font_face, double hscale, double vscale, double shear CV_DEFAULT(0), int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8)); CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) ) { CvFont font; cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA ); return font; } /** @brief Renders text stroke with specified font and color at specified location. CvFont should be initialized with cvInitFont @see cvInitFont, cvGetTextSize, cvFont, cv::putText */ CVAPI(void) cvPutText( CvArr* img, const char* text, CvPoint org, const CvFont* font, CvScalar color ); /** @brief Calculates bounding box of text stroke (useful for alignment) @see cv::getTextSize */ CVAPI(void) cvGetTextSize( const char* text_string, const CvFont* font, CvSize* text_size, int* baseline ); /** @brief Unpacks color value if arrtype is CV_8UC?, _color_ is treated as packed color value, otherwise the first channels (depending on arrtype) of destination scalar are set to the same value = _color_ */ CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype ); /** @brief Returns the polygon points which make up the given ellipse. The ellipse is define by the box of size 'axes' rotated 'angle' around the 'center'. A partial sweep of the ellipse arc can be done by spcifying arc_start and arc_end to be something other than 0 and 360, respectively. The input array 'pts' must be large enough to hold the result. The total number of points stored into 'pts' is returned by this function. @see cv::ellipse2Poly */ CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes, int angle, int arc_start, int arc_end, CvPoint * pts, int delta ); /** @brief Draws contour outlines or filled interiors on the image @see cv::drawContours */ CVAPI(void) cvDrawContours( CvArr *img, CvSeq* contour, CvScalar external_color, CvScalar hole_color, int max_level, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), CvPoint offset CV_DEFAULT(cvPoint(0,0))); /** @} */ #ifdef __cplusplus } #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgproc/types_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_IMGPROC_TYPES_C_H__ #define __OPENCV_IMGPROC_TYPES_C_H__ #include "opencv2/core/core_c.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup imgproc_c @{ */ /** Connected component structure */ typedef struct CvConnectedComp { double area; /** DBL_EPSILON ? 1./std::sqrt(am00) : 0; } operator cv::Moments() const { return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); } #endif } CvMoments; /** Hu invariants */ typedef struct CvHuMoments { double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /**< Hu invariants */ } CvHuMoments; /** Template matching methods */ enum { CV_TM_SQDIFF =0, CV_TM_SQDIFF_NORMED =1, CV_TM_CCORR =2, CV_TM_CCORR_NORMED =3, CV_TM_CCOEFF =4, CV_TM_CCOEFF_NORMED =5 }; typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param ); /** Contour retrieval modes */ enum { CV_RETR_EXTERNAL=0, CV_RETR_LIST=1, CV_RETR_CCOMP=2, CV_RETR_TREE=3, CV_RETR_FLOODFILL=4 }; /** Contour approximation methods */ enum { CV_CHAIN_CODE=0, CV_CHAIN_APPROX_NONE=1, CV_CHAIN_APPROX_SIMPLE=2, CV_CHAIN_APPROX_TC89_L1=3, CV_CHAIN_APPROX_TC89_KCOS=4, CV_LINK_RUNS=5 }; /* Internal structure that is used for sequential retrieving contours from the image. It supports both hierarchical and plane variants of Suzuki algorithm. */ typedef struct _CvContourScanner* CvContourScanner; /** Freeman chain reader state */ typedef struct CvChainPtReader { CV_SEQ_READER_FIELDS() char code; CvPoint pt; schar deltas[8][2]; } CvChainPtReader; /** initializes 8-element array for fast access to 3x3 neighborhood of a pixel */ #define CV_INIT_3X3_DELTAS( deltas, step, nch ) \ ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \ (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \ (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) /** Contour approximation algorithms */ enum { CV_POLY_APPROX_DP = 0 }; /** @brief Shape matching methods \f$A\f$ denotes object1,\f$B\f$ denotes object2 \f$\begin{array}{l} m^A_i = \mathrm{sign} (h^A_i) \cdot \log{h^A_i} \\ m^B_i = \mathrm{sign} (h^B_i) \cdot \log{h^B_i} \end{array}\f$ and \f$h^A_i, h^B_i\f$ are the Hu moments of \f$A\f$ and \f$B\f$ , respectively. */ enum ShapeMatchModes { CV_CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] CV_CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] CV_CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] }; /** Shape orientation */ enum { CV_CLOCKWISE =1, CV_COUNTER_CLOCKWISE =2 }; /** Convexity defect */ typedef struct CvConvexityDefect { CvPoint* start; /**< point of the contour where the defect begins */ CvPoint* end; /**< point of the contour where the defect ends */ CvPoint* depth_point; /**< the farthest from the convex hull point within the defect */ float depth; /**< distance between the farthest point and the convex hull */ } CvConvexityDefect; /** Histogram comparison methods */ enum { CV_COMP_CORREL =0, CV_COMP_CHISQR =1, CV_COMP_INTERSECT =2, CV_COMP_BHATTACHARYYA =3, CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA, CV_COMP_CHISQR_ALT =4, CV_COMP_KL_DIV =5 }; /** Mask size for distance transform */ enum { CV_DIST_MASK_3 =3, CV_DIST_MASK_5 =5, CV_DIST_MASK_PRECISE =0 }; /** Content of output label array: connected components or pixels */ enum { CV_DIST_LABEL_CCOMP = 0, CV_DIST_LABEL_PIXEL = 1 }; /** Distance types for Distance Transform and M-estimators */ enum { CV_DIST_USER =-1, /**< User defined distance */ CV_DIST_L1 =1, /**< distance = |x1-x2| + |y1-y2| */ CV_DIST_L2 =2, /**< the simple euclidean distance */ CV_DIST_C =3, /**< distance = max(|x1-x2|,|y1-y2|) */ CV_DIST_L12 =4, /**< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */ CV_DIST_FAIR =5, /**< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */ CV_DIST_WELSCH =6, /**< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */ CV_DIST_HUBER =7 /**< distance = |x| threshold ? max_value : 0 */ CV_THRESH_BINARY_INV =1, /**< value = value > threshold ? 0 : max_value */ CV_THRESH_TRUNC =2, /**< value = value > threshold ? threshold : value */ CV_THRESH_TOZERO =3, /**< value = value > threshold ? value : 0 */ CV_THRESH_TOZERO_INV =4, /**< value = value > threshold ? 0 : value */ CV_THRESH_MASK =7, CV_THRESH_OTSU =8, /**< use Otsu algorithm to choose the optimal threshold value; combine the flag with one of the above CV_THRESH_* values */ CV_THRESH_TRIANGLE =16 /**< use Triangle algorithm to choose the optimal threshold value; combine the flag with one of the above CV_THRESH_* values, but not with CV_THRESH_OTSU */ }; /** Adaptive threshold methods */ enum { CV_ADAPTIVE_THRESH_MEAN_C =0, CV_ADAPTIVE_THRESH_GAUSSIAN_C =1 }; /** FloodFill flags */ enum { CV_FLOODFILL_FIXED_RANGE =(1 << 16), CV_FLOODFILL_MASK_ONLY =(1 << 17) }; /** Canny edge detector flags */ enum { CV_CANNY_L2_GRADIENT =(1 << 31) }; /** Variants of a Hough transform */ enum { CV_HOUGH_STANDARD =0, CV_HOUGH_PROBABILISTIC =1, CV_HOUGH_MULTI_SCALE =2, CV_HOUGH_GRADIENT =3 }; /* Fast search data structures */ struct CvFeatureTree; struct CvLSH; struct CvLSHOperations; /** @} */ #ifdef __cplusplus } #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/imgproc.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_IMGPROC_HPP__ #define __OPENCV_IMGPROC_HPP__ #include "opencv2/core.hpp" /** @defgroup imgproc Image processing @{ @defgroup imgproc_filter Image Filtering Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images (represented as Mat's). It means that for each pixel location \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of morphological operations, it is the minimum or maximum values, and so on. The computed response is stored in the destination image at the same location \f$(x,y)\f$. It means that the output image will be of the same size as the input image. Normally, the functions support multi-channel arrays, in which case every channel is processed independently. Therefore, the output image will also have the same number of channels as the input one. Another common feature of the functions and classes described in this section is that, unlike simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when processing the left-most pixels in each row, you need pixels to the left of them, that is, outside of the image. You can let these pixels be the same as the left-most image pixels ("replicated border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method. For details, see cv::BorderTypes @anchor filter_depths ### Depth combinations Input depth (src.depth()) | Output depth (ddepth) --------------------------|---------------------- CV_8U | -1/CV_16S/CV_32F/CV_64F CV_16U/CV_16S | -1/CV_32F/CV_64F CV_32F | -1/CV_32F/CV_64F CV_64F | -1/CV_64F @note when ddepth=-1, the output image will have the same depth as the source. @defgroup imgproc_transform Geometric Image Transformations The functions in this section perform various geometrical transformations of 2D images. They do not change the image content but deform the pixel grid and map this deformed grid to the destination image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the functions compute coordinates of the corresponding "donor" pixel in the source image and copy the pixel value: \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f] In case when you specify the forward mapping \f$\left: \texttt{src} \rightarrow \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping \f$\left: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula. The actual implementations of the geometrical transformations, from the most generic remap and to the simplest and the fastest resize, need to solve two main problems with the above formula: - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both of them may fall outside of the image. In this case, an extrapolation method needs to be used. OpenCV provides the same selection of extrapolation methods as in the filtering functions. In addition, it provides the method BORDER_TRANSPARENT. This means that the corresponding pixels in the destination image will not be modified at all. - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point numbers. This means that \f$\left\f$ can be either an affine or perspective transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the nearest integer coordinates and the corresponding pixel can be used. This is called a nearest-neighbor interpolation. However, a better result can be achieved by using more sophisticated [interpolation methods](http://en.wikipedia.org/wiki/Multivariate_interpolation) , where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y), f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See resize for details. @defgroup imgproc_misc Miscellaneous Image Transformations @defgroup imgproc_draw Drawing Functions Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be rendered with antialiasing (implemented only for 8-bit images for now). All the functions include the parameter color that uses an RGB value (that may be constructed with the Scalar constructor ) for color images and brightness for grayscale images. For color images, the channel ordering is normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a color using the Scalar constructor, it should look like: \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f] If you are using your own image rendering and I/O functions, you can use any channel ordering. The drawing functions process each channel independently and do not depend on the channel order or even on the used color space. The whole image can be converted from BGR to RGB or to a different color space using cvtColor . If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means that the coordinates can be passed as fixed-point numbers encoded as integers. The number of fractional bits is specified by the shift parameter and the real point coordinates are calculated as \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is especially effective when rendering antialiased shapes. @note The functions do not support alpha-transparency when the target image is 4-channel. In this case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image. @defgroup imgproc_colormap ColorMaps in OpenCV The human perception isn't built for observing fine changes in grayscale images. Human eyes are more sensitive to observing changes between colors, so you often need to recolor your grayscale images to get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your computer vision application. In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample code reads the path to an image from command line, applies a Jet colormap on it and shows the result: @code #include #include #include #include using namespace cv; #include using namespace std; int main(int argc, const char *argv[]) { // We need an input image. (can be grayscale or color) if (argc < 2) { cerr << "We need an image to process here. Please run: colorMap [path_to_image]" << endl; return -1; } Mat img_in = imread(argv[1]); if(img_in.empty()) { cerr << "Sample image (" << argv[1] << ") is empty. Please adjust your path, so it points to a valid input image!" << endl; return -1; } // Holds the colormap version of the image: Mat img_color; // Apply the colormap: applyColorMap(img_in, img_color, COLORMAP_JET); // Show the result: imshow("colorMap", img_color); waitKey(0); return 0; } @endcode @see cv::ColormapTypes @defgroup imgproc_hist Histograms @defgroup imgproc_shape Structural Analysis and Shape Descriptors @defgroup imgproc_motion Motion Analysis and Object Tracking @defgroup imgproc_feature Feature Detection @defgroup imgproc_object Object Detection @defgroup imgproc_c C API @} */ namespace cv { /** @addtogroup imgproc @{ */ //! @addtogroup imgproc_filter //! @{ //! type of morphological operation enum MorphTypes{ MORPH_ERODE = 0, //!< see cv::erode MORPH_DILATE = 1, //!< see cv::dilate MORPH_OPEN = 2, //!< an opening operation //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] MORPH_CLOSE = 3, //!< a closing operation //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f] MORPH_GRADIENT = 4, //!< a morphological gradient //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] MORPH_TOPHAT = 5, //!< "top hat" //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] MORPH_BLACKHAT = 6, //!< "black hat" //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] MORPH_HITMISS = 7 //!< "hit and miss" //!< .- Only supported for CV_8UC1 binary images. Tutorial can be found in [this page](http://opencv-code.com/tutorials/hit-or-miss-transform-in-opencv/) }; //! shape of the structuring element enum MorphShapes { MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f] MORPH_CROSS = 1, //!< a cross-shaped structuring element: //!< \f[E_{ij} = \fork{1}{if i=\texttt{anchor.y} or j=\texttt{anchor.x}}{0}{otherwise}\f] MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed //!< into the rectangle Rect(0, 0, esize.width, 0.esize.height) }; //! @} imgproc_filter //! @addtogroup imgproc_transform //! @{ //! interpolation algorithm enum InterpolationFlags{ /** nearest neighbor interpolation */ INTER_NEAREST = 0, /** bilinear interpolation */ INTER_LINEAR = 1, /** bicubic interpolation */ INTER_CUBIC = 2, /** resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. */ INTER_AREA = 3, /** Lanczos interpolation over 8x8 neighborhood */ INTER_LANCZOS4 = 4, /** mask for interpolation codes */ INTER_MAX = 7, /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the source image, they are set to zero */ WARP_FILL_OUTLIERS = 8, /** flag, inverse transformation For example, polar transforms: - flag is __not__ set: \f$dst( \phi , \rho ) = src(x,y)\f$ - flag is set: \f$dst(x,y) = src( \phi , \rho )\f$ */ WARP_INVERSE_MAP = 16 }; enum InterpolationMasks { INTER_BITS = 5, INTER_BITS2 = INTER_BITS * 2, INTER_TAB_SIZE = 1 << INTER_BITS, INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE }; //! @} imgproc_transform //! @addtogroup imgproc_misc //! @{ //! Distance types for Distance Transform and M-estimators //! @see cv::distanceTransform, cv::fitLine enum DistanceTypes { DIST_USER = -1, //!< User defined distance DIST_L1 = 1, //!< distance = |x1-x2| + |y1-y2| DIST_L2 = 2, //!< the simple euclidean distance DIST_C = 3, //!< distance = max(|x1-x2|,|y1-y2|) DIST_L12 = 4, //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) DIST_FAIR = 5, //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 DIST_WELSCH = 6, //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 DIST_HUBER = 7 //!< distance = |x| \texttt{thresh}\)}{0}{otherwise}\f] THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] THRESH_MASK = 7, THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value }; //! adaptive threshold algorithm //! see cv::adaptiveThreshold enum AdaptiveThresholdTypes { /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */ ADAPTIVE_THRESH_MEAN_C = 0, /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C . The default sigma (standard deviation) is used for the specified blockSize . See cv::getGaussianKernel*/ ADAPTIVE_THRESH_GAUSSIAN_C = 1 }; //! cv::undistort mode enum UndistortTypes { PROJ_SPHERICAL_ORTHO = 0, PROJ_SPHERICAL_EQRECT = 1 }; //! class of the pixel in GrabCut algorithm enum GrabCutClasses { GC_BGD = 0, //!< an obvious background pixels GC_FGD = 1, //!< an obvious foreground (object) pixel GC_PR_BGD = 2, //!< a possible background pixel GC_PR_FGD = 3 //!< a possible foreground pixel }; //! GrabCut algorithm flags enum GrabCutModes { /** The function initializes the state and the mask using the provided rectangle. After that it runs iterCount iterations of the algorithm. */ GC_INIT_WITH_RECT = 0, /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are automatically initialized with GC_BGD .*/ GC_INIT_WITH_MASK = 1, /** The value means that the algorithm should just resume. */ GC_EVAL = 2 }; //! distanceTransform algorithm flags enum DistanceTransformLabelTypes { /** each connected component of zeros in src (as well as all the non-zero pixels closest to the connected component) will be assigned the same label */ DIST_LABEL_CCOMP = 0, /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */ DIST_LABEL_PIXEL = 1 }; //! floodfill algorithm flags enum FloodFillFlags { /** If set, the difference between the current pixel and seed pixel is considered. Otherwise, the difference between neighbor pixels is considered (that is, the range is floating). */ FLOODFILL_FIXED_RANGE = 1 << 16, /** If set, the function does not change the image ( newVal is ignored), and only fills the mask with the value specified in bits 8-16 of flags as described above. This option only make sense in function variants that have the mask parameter. */ FLOODFILL_MASK_ONLY = 1 << 17 }; //! @} imgproc_misc //! @addtogroup imgproc_shape //! @{ //! connected components algorithm output formats enum ConnectedComponentsTypes { CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding //!< box in the horizontal direction. CC_STAT_TOP = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding //!< box in the vertical direction. CC_STAT_WIDTH = 2, //!< The horizontal size of the bounding box CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box CC_STAT_AREA = 4, //!< The total area (in pixels) of the connected component CC_STAT_MAX = 5 }; //! mode of the contour retrieval algorithm enum RetrievalModes { /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for all the contours. */ RETR_EXTERNAL = 0, /** retrieves all of the contours without establishing any hierarchical relationships. */ RETR_LIST = 1, /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level. */ RETR_CCOMP = 2, /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/ RETR_TREE = 3, RETR_FLOODFILL = 4 //!< }; //! the contour approximation algorithm enum ContourApproximationModes { /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, max(abs(x1-x2),abs(y2-y1))==1. */ CHAIN_APPROX_NONE = 1, /** compresses horizontal, vertical, and diagonal segments and leaves only their end points. For example, an up-right rectangular contour is encoded with 4 points. */ CHAIN_APPROX_SIMPLE = 2, /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ CHAIN_APPROX_TC89_L1 = 3, /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ CHAIN_APPROX_TC89_KCOS = 4 }; //! @} imgproc_shape //! Variants of a Hough transform enum HoughModes { /** classical or standard Hough transform. Every line is represented by two floating-point numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line, and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must be (the created sequence will be) of CV_32FC2 type */ HOUGH_STANDARD = 0, /** probabilistic Hough transform (more efficient in case if the picture contains a few long linear segments). It returns line segments rather than the whole line. Each segment is represented by starting and ending points, and the matrix must be (the created sequence will be) of the CV_32SC4 type. */ HOUGH_PROBABILISTIC = 1, /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as HOUGH_STANDARD. */ HOUGH_MULTI_SCALE = 2, HOUGH_GRADIENT = 3 //!< basically *21HT*, described in @cite Yuen90 }; //! Variants of Line Segment %Detector //! @ingroup imgproc_feature enum LineSegmentDetectorModes { LSD_REFINE_NONE = 0, //!< No refinement applied LSD_REFINE_STD = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations. LSD_REFINE_ADV = 2 //!< Advanced refinement. Number of false alarms is calculated, lines are //!< refined through increase of precision, decrement in size, etc. }; /** Histogram comparison methods @ingroup imgproc_hist */ enum HistCompMethods { /** Correlation \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f] where \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f] and \f$N\f$ is a total number of histogram bins. */ HISTCMP_CORREL = 0, /** Chi-Square \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */ HISTCMP_CHISQR = 1, /** Intersection \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] */ HISTCMP_INTERSECT = 2, /** Bhattacharyya distance (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.) \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */ HISTCMP_BHATTACHARYYA = 3, HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA /** Alternative Chi-Square \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f] This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */ HISTCMP_CHISQR_ALT = 4, /** Kullback-Leibler divergence \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */ HISTCMP_KL_DIV = 5 }; /** the color conversion code @see @ref imgproc_color_conversions @ingroup imgproc_misc */ enum ColorConversionCodes { COLOR_BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image COLOR_RGB2RGBA = COLOR_BGR2BGRA, COLOR_BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image COLOR_RGBA2RGB = COLOR_BGRA2BGR, COLOR_BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel) COLOR_RGB2BGRA = COLOR_BGR2RGBA, COLOR_RGBA2BGR = 3, COLOR_BGRA2RGB = COLOR_RGBA2BGR, COLOR_BGR2RGB = 4, COLOR_RGB2BGR = COLOR_BGR2RGB, COLOR_BGRA2RGBA = 5, COLOR_RGBA2BGRA = COLOR_BGRA2RGBA, COLOR_BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions" COLOR_RGB2GRAY = 7, COLOR_GRAY2BGR = 8, COLOR_GRAY2RGB = COLOR_GRAY2BGR, COLOR_GRAY2BGRA = 9, COLOR_GRAY2RGBA = COLOR_GRAY2BGRA, COLOR_BGRA2GRAY = 10, COLOR_RGBA2GRAY = 11, COLOR_BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images) COLOR_RGB2BGR565 = 13, COLOR_BGR5652BGR = 14, COLOR_BGR5652RGB = 15, COLOR_BGRA2BGR565 = 16, COLOR_RGBA2BGR565 = 17, COLOR_BGR5652BGRA = 18, COLOR_BGR5652RGBA = 19, COLOR_GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images) COLOR_BGR5652GRAY = 21, COLOR_BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images) COLOR_RGB2BGR555 = 23, COLOR_BGR5552BGR = 24, COLOR_BGR5552RGB = 25, COLOR_BGRA2BGR555 = 26, COLOR_RGBA2BGR555 = 27, COLOR_BGR5552BGRA = 28, COLOR_BGR5552RGBA = 29, COLOR_GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images) COLOR_BGR5552GRAY = 31, COLOR_BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions" COLOR_RGB2XYZ = 33, COLOR_XYZ2BGR = 34, COLOR_XYZ2RGB = 35, COLOR_BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions" COLOR_RGB2YCrCb = 37, COLOR_YCrCb2BGR = 38, COLOR_YCrCb2RGB = 39, COLOR_BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value), @ref color_convert_rgb_hsv "color conversions" COLOR_RGB2HSV = 41, COLOR_BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions" COLOR_RGB2Lab = 45, COLOR_BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions" COLOR_RGB2Luv = 51, COLOR_BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation), @ref color_convert_rgb_hls "color conversions" COLOR_RGB2HLS = 53, COLOR_HSV2BGR = 54, //!< backward conversions to RGB/BGR COLOR_HSV2RGB = 55, COLOR_Lab2BGR = 56, COLOR_Lab2RGB = 57, COLOR_Luv2BGR = 58, COLOR_Luv2RGB = 59, COLOR_HLS2BGR = 60, COLOR_HLS2RGB = 61, COLOR_BGR2HSV_FULL = 66, //!< COLOR_RGB2HSV_FULL = 67, COLOR_BGR2HLS_FULL = 68, COLOR_RGB2HLS_FULL = 69, COLOR_HSV2BGR_FULL = 70, COLOR_HSV2RGB_FULL = 71, COLOR_HLS2BGR_FULL = 72, COLOR_HLS2RGB_FULL = 73, COLOR_LBGR2Lab = 74, COLOR_LRGB2Lab = 75, COLOR_LBGR2Luv = 76, COLOR_LRGB2Luv = 77, COLOR_Lab2LBGR = 78, COLOR_Lab2LRGB = 79, COLOR_Luv2LBGR = 80, COLOR_Luv2LRGB = 81, COLOR_BGR2YUV = 82, //!< convert between RGB/BGR and YUV COLOR_RGB2YUV = 83, COLOR_YUV2BGR = 84, COLOR_YUV2RGB = 85, //! YUV 4:2:0 family to RGB COLOR_YUV2RGB_NV12 = 90, COLOR_YUV2BGR_NV12 = 91, COLOR_YUV2RGB_NV21 = 92, COLOR_YUV2BGR_NV21 = 93, COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, COLOR_YUV2RGBA_NV12 = 94, COLOR_YUV2BGRA_NV12 = 95, COLOR_YUV2RGBA_NV21 = 96, COLOR_YUV2BGRA_NV21 = 97, COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, COLOR_YUV2RGB_YV12 = 98, COLOR_YUV2BGR_YV12 = 99, COLOR_YUV2RGB_IYUV = 100, COLOR_YUV2BGR_IYUV = 101, COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, COLOR_YUV2RGBA_YV12 = 102, COLOR_YUV2BGRA_YV12 = 103, COLOR_YUV2RGBA_IYUV = 104, COLOR_YUV2BGRA_IYUV = 105, COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, COLOR_YUV2GRAY_420 = 106, COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, //! YUV 4:2:2 family to RGB COLOR_YUV2RGB_UYVY = 107, COLOR_YUV2BGR_UYVY = 108, //COLOR_YUV2RGB_VYUY = 109, //COLOR_YUV2BGR_VYUY = 110, COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, COLOR_YUV2RGBA_UYVY = 111, COLOR_YUV2BGRA_UYVY = 112, //COLOR_YUV2RGBA_VYUY = 113, //COLOR_YUV2BGRA_VYUY = 114, COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, COLOR_YUV2RGB_YUY2 = 115, COLOR_YUV2BGR_YUY2 = 116, COLOR_YUV2RGB_YVYU = 117, COLOR_YUV2BGR_YVYU = 118, COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, COLOR_YUV2RGBA_YUY2 = 119, COLOR_YUV2BGRA_YUY2 = 120, COLOR_YUV2RGBA_YVYU = 121, COLOR_YUV2BGRA_YVYU = 122, COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, COLOR_YUV2GRAY_UYVY = 123, COLOR_YUV2GRAY_YUY2 = 124, //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, //! alpha premultiplication COLOR_RGBA2mRGBA = 125, COLOR_mRGBA2RGBA = 126, //! RGB to YUV 4:2:0 family COLOR_RGB2YUV_I420 = 127, COLOR_BGR2YUV_I420 = 128, COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420, COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420, COLOR_RGBA2YUV_I420 = 129, COLOR_BGRA2YUV_I420 = 130, COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, COLOR_RGB2YUV_YV12 = 131, COLOR_BGR2YUV_YV12 = 132, COLOR_RGBA2YUV_YV12 = 133, COLOR_BGRA2YUV_YV12 = 134, //! Demosaicing COLOR_BayerBG2BGR = 46, COLOR_BayerGB2BGR = 47, COLOR_BayerRG2BGR = 48, COLOR_BayerGR2BGR = 49, COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, COLOR_BayerBG2GRAY = 86, COLOR_BayerGB2GRAY = 87, COLOR_BayerRG2GRAY = 88, COLOR_BayerGR2GRAY = 89, //! Demosaicing using Variable Number of Gradients COLOR_BayerBG2BGR_VNG = 62, COLOR_BayerGB2BGR_VNG = 63, COLOR_BayerRG2BGR_VNG = 64, COLOR_BayerGR2BGR_VNG = 65, COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, //! Edge-Aware Demosaicing COLOR_BayerBG2BGR_EA = 135, COLOR_BayerGB2BGR_EA = 136, COLOR_BayerRG2BGR_EA = 137, COLOR_BayerGR2BGR_EA = 138, COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA, COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA, COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA, COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA, COLOR_COLORCVT_MAX = 139 }; /** types of intersection between rectangles @ingroup imgproc_shape */ enum RectanglesIntersectTypes { INTERSECT_NONE = 0, //!< No intersection INTERSECT_PARTIAL = 1, //!< There is a partial intersection INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other }; //! finds arbitrary template in the grayscale image using Generalized Hough Transform class CV_EXPORTS GeneralizedHough : public Algorithm { public: //! set template to search virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0; virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0; //! find template on image virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0; virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0; //! Canny low threshold. virtual void setCannyLowThresh(int cannyLowThresh) = 0; virtual int getCannyLowThresh() const = 0; //! Canny high threshold. virtual void setCannyHighThresh(int cannyHighThresh) = 0; virtual int getCannyHighThresh() const = 0; //! Minimum distance between the centers of the detected objects. virtual void setMinDist(double minDist) = 0; virtual double getMinDist() const = 0; //! Inverse ratio of the accumulator resolution to the image resolution. virtual void setDp(double dp) = 0; virtual double getDp() const = 0; //! Maximal size of inner buffers. virtual void setMaxBufferSize(int maxBufferSize) = 0; virtual int getMaxBufferSize() const = 0; }; //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122. //! Detects position only without traslation and rotation class CV_EXPORTS GeneralizedHoughBallard : public GeneralizedHough { public: //! R-Table levels. virtual void setLevels(int levels) = 0; virtual int getLevels() const = 0; //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected. virtual void setVotesThreshold(int votesThreshold) = 0; virtual int getVotesThreshold() const = 0; }; //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038. //! Detects position, traslation and rotation class CV_EXPORTS GeneralizedHoughGuil : public GeneralizedHough { public: //! Angle difference in degrees between two points in feature. virtual void setXi(double xi) = 0; virtual double getXi() const = 0; //! Feature table levels. virtual void setLevels(int levels) = 0; virtual int getLevels() const = 0; //! Maximal difference between angles that treated as equal. virtual void setAngleEpsilon(double angleEpsilon) = 0; virtual double getAngleEpsilon() const = 0; //! Minimal rotation angle to detect in degrees. virtual void setMinAngle(double minAngle) = 0; virtual double getMinAngle() const = 0; //! Maximal rotation angle to detect in degrees. virtual void setMaxAngle(double maxAngle) = 0; virtual double getMaxAngle() const = 0; //! Angle step in degrees. virtual void setAngleStep(double angleStep) = 0; virtual double getAngleStep() const = 0; //! Angle votes threshold. virtual void setAngleThresh(int angleThresh) = 0; virtual int getAngleThresh() const = 0; //! Minimal scale to detect. virtual void setMinScale(double minScale) = 0; virtual double getMinScale() const = 0; //! Maximal scale to detect. virtual void setMaxScale(double maxScale) = 0; virtual double getMaxScale() const = 0; //! Scale step. virtual void setScaleStep(double scaleStep) = 0; virtual double getScaleStep() const = 0; //! Scale votes threshold. virtual void setScaleThresh(int scaleThresh) = 0; virtual int getScaleThresh() const = 0; //! Position votes threshold. virtual void setPosThresh(int posThresh) = 0; virtual int getPosThresh() const = 0; }; class CV_EXPORTS_W CLAHE : public Algorithm { public: CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; CV_WRAP virtual void setClipLimit(double clipLimit) = 0; CV_WRAP virtual double getClipLimit() const = 0; CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; CV_WRAP virtual Size getTilesGridSize() const = 0; CV_WRAP virtual void collectGarbage() = 0; }; class CV_EXPORTS_W Subdiv2D { public: enum { PTLOC_ERROR = -2, PTLOC_OUTSIDE_RECT = -1, PTLOC_INSIDE = 0, PTLOC_VERTEX = 1, PTLOC_ON_EDGE = 2 }; enum { NEXT_AROUND_ORG = 0x00, NEXT_AROUND_DST = 0x22, PREV_AROUND_ORG = 0x11, PREV_AROUND_DST = 0x33, NEXT_AROUND_LEFT = 0x13, NEXT_AROUND_RIGHT = 0x31, PREV_AROUND_LEFT = 0x20, PREV_AROUND_RIGHT = 0x02 }; CV_WRAP Subdiv2D(); CV_WRAP Subdiv2D(Rect rect); CV_WRAP void initDelaunay(Rect rect); CV_WRAP int insert(Point2f pt); CV_WRAP void insert(const std::vector& ptvec); CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0); CV_WRAP void getEdgeList(CV_OUT std::vector& edgeList) const; CV_WRAP void getTriangleList(CV_OUT std::vector& triangleList) const; CV_WRAP void getVoronoiFacetList(const std::vector& idx, CV_OUT std::vector >& facetList, CV_OUT std::vector& facetCenters); CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const; CV_WRAP int getEdge( int edge, int nextEdgeType ) const; CV_WRAP int nextEdge(int edge) const; CV_WRAP int rotateEdge(int edge, int rotate) const; CV_WRAP int symEdge(int edge) const; CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const; CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const; protected: int newEdge(); void deleteEdge(int edge); int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0); void deletePoint(int vtx); void setEdgePoints( int edge, int orgPt, int dstPt ); void splice( int edgeA, int edgeB ); int connectEdges( int edgeA, int edgeB ); void swapEdges( int edge ); int isRightOf(Point2f pt, int edge) const; void calcVoronoi(); void clearVoronoi(); void checkSubdiv() const; struct CV_EXPORTS Vertex { Vertex(); Vertex(Point2f pt, bool _isvirtual, int _firstEdge=0); bool isvirtual() const; bool isfree() const; int firstEdge; int type; Point2f pt; }; struct CV_EXPORTS QuadEdge { QuadEdge(); QuadEdge(int edgeidx); bool isfree() const; int next[4]; int pt[4]; }; std::vector vtx; std::vector qedges; int freeQEdge; int freePoint; bool validGeometry; int recentEdge; Point2f topLeft; Point2f bottomRight; }; //! @addtogroup imgproc_feature //! @{ /** @example lsd_lines.cpp An example using the LineSegmentDetector */ /** @brief Line segment detector class following the algorithm described at @cite Rafael12 . */ class CV_EXPORTS_W LineSegmentDetector : public Algorithm { public: /** @brief Finds lines in the input image. This is the output of the default parameters of the algorithm on the above shown image. ![image](pics/building_lsd.png) @param _image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);` @param _lines A vector of Vec4i or Vec4f elements specifying the beginning and ending point of a line. Where Vec4i/Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly oriented depending on the gradient. @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. @param prec Vector of precisions with which the lines are found. @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The bigger the value, logarithmically better the detection. - -1 corresponds to 10 mean false alarms - 0 corresponds to 1 mean false alarm - 1 corresponds to 0.1 mean false alarms This vector will be calculated only when the objects type is LSD_REFINE_ADV. */ CV_WRAP virtual void detect(InputArray _image, OutputArray _lines, OutputArray width = noArray(), OutputArray prec = noArray(), OutputArray nfa = noArray()) = 0; /** @brief Draws the line segments on a given image. @param _image The image, where the liens will be drawn. Should be bigger or equal to the image, where the lines were found. @param lines A vector of the lines that needed to be drawn. */ CV_WRAP virtual void drawSegments(InputOutputArray _image, InputArray lines) = 0; /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. @param size The size of the image, where lines1 and lines2 were found. @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. @param lines2 The second group of lines. They visualized in red color. @param _image Optional image, where the lines will be drawn. The image should be color(3-channel) in order for lines1 and lines2 to be drawn in the above mentioned colors. */ CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray _image = noArray()) = 0; virtual ~LineSegmentDetector() { } }; /** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it. The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want to edit those, as to tailor it for their own application. @param _refine The way found lines will be refined, see cv::LineSegmentDetectorModes @param _scale The scale of the image that will be used to find the lines. Range (0..1]. @param _sigma_scale Sigma for Gaussian filter. It is computed as sigma = _sigma_scale/_scale. @param _quant Bound to the quantization error on the gradient norm. @param _ang_th Gradient angle tolerance in degrees. @param _log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advancent refinement is chosen. @param _density_th Minimal density of aligned region points in the enclosing rectangle. @param _n_bins Number of bins in pseudo-ordering of gradient modulus. */ CV_EXPORTS_W Ptr createLineSegmentDetector( int _refine = LSD_REFINE_STD, double _scale = 0.8, double _sigma_scale = 0.6, double _quant = 2.0, double _ang_th = 22.5, double _log_eps = 0, double _density_th = 0.7, int _n_bins = 1024); //! @} imgproc_feature //! @addtogroup imgproc_filter //! @{ /** @brief Returns Gaussian filter coefficients. The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter coefficients: \f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f] where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$. Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. You may also use the higher-level GaussianBlur. @param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive. @param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as `sigma = 0.3\*((ksize-1)\*0.5 - 1) + 0.8`. @param ktype Type of filter coefficients. It can be CV_32F or CV_64F . @sa sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur */ CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F ); /** @brief Returns filter coefficients for computing spatial image derivatives. The function computes and returns the filter coefficients for spatial image derivatives. When `ksize=CV_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see cv::Scharr). Otherwise, Sobel kernels are generated (see cv::Sobel). The filters are normally passed to sepFilter2D or to @param kx Output matrix of row filter coefficients. It has the type ktype . @param ky Output matrix of column filter coefficients. It has the type ktype . @param dx Derivative order in respect of x. @param dy Derivative order in respect of y. @param ksize Aperture size. It can be CV_SCHARR, 1, 3, 5, or 7. @param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are going to filter floating-point images, you are likely to use the normalized kernels. But if you compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve all the fractional bits, you may want to set normalize=false . @param ktype Type of filter coefficients. It can be CV_32f or CV_64F . */ CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, int dx, int dy, int ksize, bool normalize = false, int ktype = CV_32F ); /** @brief Returns Gabor filter coefficients. For more details about gabor filter equations and parameters, see: [Gabor Filter](http://en.wikipedia.org/wiki/Gabor_filter). @param ksize Size of the filter returned. @param sigma Standard deviation of the gaussian envelope. @param theta Orientation of the normal to the parallel stripes of a Gabor function. @param lambd Wavelength of the sinusoidal factor. @param gamma Spatial aspect ratio. @param psi Phase offset. @param ktype Type of filter coefficients. It can be CV_32F or CV_64F . */ CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, double gamma, double psi = CV_PI*0.5, int ktype = CV_64F ); //! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } /** @brief Returns a structuring element of the specified size and shape for morphological operations. The function constructs and returns the structuring element that can be further passed to cv::erode, cv::dilate or cv::morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as the structuring element. @param shape Element shape that could be one of cv::MorphShapes @param ksize Size of the structuring element. @param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor position. In other cases the anchor just regulates how much the result of the morphological operation is shifted. */ CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)); /** @brief Blurs an image using the median filter. The function smoothes an image using the median filter with the \f$\texttt{ksize} \times \texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. In-place operation is supported. @param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. @param dst destination array of the same size and type as src. @param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... @sa bilateralFilter, blur, boxFilter, GaussianBlur */ CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); /** @brief Blurs an image using a Gaussian filter. The function convolves the source image with the specified Gaussian kernel. In-place filtering is supported. @param src input image; the image can have any number of channels, which are processed independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src. @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be positive and odd. Or, they can be zero's and then they are computed from sigma. @param sigmaX Gaussian kernel standard deviation in X direction. @param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, respectively (see cv::getGaussianKernel for details); to fully control the result regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY. @param borderType pixel extrapolation method, see cv::BorderTypes @sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur */ CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY = 0, int borderType = BORDER_DEFAULT ); /** @brief Applies the bilateral filter to an image. The function applies bilateral filtering to the input image, as described in http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is very slow compared to most filters. _Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< 10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very strong effect, making the image look "cartoonish". _Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time applications, and perhaps d=9 for offline applications that need heavy noise filtering. This filter does not work inplace. @param src Source 8-bit or floating-point, 1-channel or 3-channel image. @param dst Destination image of the same size and type as src . @param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, it is computed from sigmaSpace. @param sigmaColor Filter sigma in the color space. A larger value of the parameter means that farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting in larger areas of semi-equal color. @param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that farther pixels will influence each other as long as their colors are close enough (see sigmaColor ). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is proportional to sigmaSpace. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes */ CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, int borderType = BORDER_DEFAULT ); /** @brief Blurs an image using the box filter. The function smoothes an image using the kernel: \f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] where \f[\alpha = \fork{\frac{1}{\texttt{ksize.width*ksize.height}}}{when \texttt{normalize=true}}{1}{otherwise}\f] Unnormalized box filter is useful for computing various integral characteristics over each pixel neighborhood, such as covariance matrices of image derivatives (used in dense optical flow algorithms, and so on). If you need to compute pixel sums over variable-size windows, use cv::integral. @param src input image. @param dst output image of the same size and type as src. @param ddepth the output image depth (-1 to use src.depth()). @param ksize blurring kernel size. @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel center. @param normalize flag, specifying whether the kernel is normalized by its area or not. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes @sa blur, bilateralFilter, GaussianBlur, medianBlur, integral */ CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), bool normalize = true, int borderType = BORDER_DEFAULT ); /** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter. For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$. The unnormalized square box filter can be useful in computing local image statistics such as the the local variance and standard deviation around the neighborhood of a pixel. @param _src input image @param _dst output image of the same size and type as _src @param ddepth the output image depth (-1 to use src.depth()) @param ksize kernel size @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel center. @param normalize flag, specifying whether the kernel is to be normalized by it's area or not. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes @sa boxFilter */ CV_EXPORTS_W void sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth, Size ksize, Point anchor = Point(-1, -1), bool normalize = true, int borderType = BORDER_DEFAULT ); /** @brief Blurs an image using the normalized box filter. The function smoothes an image using the kernel: \f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), anchor, true, borderType)`. @param src input image; it can have any number of channels, which are processed independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src. @param ksize blurring kernel size. @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel center. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes @sa boxFilter, bilateralFilter, GaussianBlur, medianBlur */ CV_EXPORTS_W void blur( InputArray src, OutputArray dst, Size ksize, Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT ); /** @brief Convolves an image with the kernel. The function applies an arbitrary linear filter to an image. In-place operation is supported. When the aperture is partially outside the image, the function interpolates outlier pixel values according to the specified border mode. The function does actually compute correlation, not the convolution: \f[\texttt{dst} (x,y) = \sum _{ \stackrel{0\leq x' < \texttt{kernel.cols},}{0\leq y' < \texttt{kernel.rows}} } \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip the kernel using cv::flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - anchor.y - 1)`. The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or larger) and the direct algorithm for small kernels. @param src input image. @param dst output image of the same size and the same number of channels as src. @param ddepth desired depth of the destination image, see @ref filter_depths "combinations" @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point matrix; if you want to apply different kernels to different channels, split the image into separate color planes using split and process them individually. @param anchor anchor of the kernel that indicates the relative position of a filtered point within the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor is at the kernel center. @param delta optional value added to the filtered pixels before storing them in dst. @param borderType pixel extrapolation method, see cv::BorderTypes @sa sepFilter2D, dft, matchTemplate */ CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernel, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT ); /** @brief Applies a separable linear filter to an image. The function applies a separable linear filter to the image. That is, first, every row of src is filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D kernel kernelY. The final result shifted by delta is stored in dst . @param src Source image. @param dst Destination image of the same size and the same number of channels as src . @param ddepth Destination image depth, see @ref filter_depths "combinations" @param kernelX Coefficients for filtering each row. @param kernelY Coefficients for filtering each column. @param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor is at the kernel center. @param delta Value added to the filtered results before storing them. @param borderType Pixel extrapolation method, see cv::BorderTypes @sa filter2D, Sobel, GaussianBlur, boxFilter, blur */ CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernelX, InputArray kernelY, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT ); /** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first or the second x- or y- derivatives. There is also the special value `ksize = CV_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is \f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] for the x-derivative, or transposed for the y-derivative. The function calculates an image derivative by convolving the image with the appropriate kernel: \f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first case corresponds to a kernel of: \f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] The second case corresponds to a kernel of: \f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] @param src input image. @param dst output image of the same size and the same number of channels as src . @param ddepth output image depth, see @ref filter_depths "combinations"; in the case of 8-bit input images it will result in truncated derivatives. @param dx order of the derivative x. @param dy order of the derivative y. @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. @param scale optional scale factor for the computed derivative values; by default, no scaling is applied (see cv::getDerivKernels for details). @param delta optional delta value that is added to the results prior to storing them in dst. @param borderType pixel extrapolation method, see cv::BorderTypes @sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar */ CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); /** @brief Calculates the first order image derivative in both x and y using a Sobel operator Equivalent to calling: @code Sobel( src, dx, CV_16SC1, 1, 0, 3 ); Sobel( src, dy, CV_16SC1, 0, 1, 3 ); @endcode @param src input image. @param dx output image with first-order derivative in x. @param dy output image with first-order derivative in y. @param ksize size of Sobel kernel. It must be 3. @param borderType pixel extrapolation method, see cv::BorderTypes @sa Sobel */ CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx, OutputArray dy, int ksize = 3, int borderType = BORDER_DEFAULT ); /** @brief Calculates the first x- or y- image derivative using Scharr operator. The function computes the first x- or y- spatial image derivative using the Scharr operator. The call \f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f] is equivalent to \f[\texttt{Sobel(src, dst, ddepth, dx, dy, CV\_SCHARR, scale, delta, borderType)} .\f] @param src input image. @param dst output image of the same size and the same number of channels as src. @param ddepth output image depth, see @ref filter_depths "combinations" @param dx order of the derivative x. @param dy order of the derivative y. @param scale optional scale factor for the computed derivative values; by default, no scaling is applied (see getDerivKernels for details). @param delta optional delta value that is added to the results prior to storing them in dst. @param borderType pixel extrapolation method, see cv::BorderTypes @sa cartToPolar */ CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); /** @example laplace.cpp An example using Laplace transformations for edge detection */ /** @brief Calculates the Laplacian of an image. The function calculates the Laplacian of the source image by adding up the second x and y derivatives calculated using the Sobel operator: \f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image with the following \f$3 \times 3\f$ aperture: \f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] @param src Source image. @param dst Destination image of the same size and the same number of channels as src . @param ddepth Desired depth of the destination image. @param ksize Aperture size used to compute the second-derivative filters. See getDerivKernels for details. The size must be positive and odd. @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is applied. See getDerivKernels for details. @param delta Optional delta value that is added to the results prior to storing them in dst . @param borderType Pixel extrapolation method, see cv::BorderTypes @sa Sobel, Scharr */ CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth, int ksize = 1, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); //! @} imgproc_filter //! @addtogroup imgproc_feature //! @{ /** @example edge.cpp An example on using the canny edge detector */ /** @brief Finds edges in an image using the Canny algorithm @cite Canny86 . The function finds edges in the input image image and marks them in the output map edges using the Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The largest value is used to find initial segments of strong edges. See @param image 8-bit input image. @param edges output edge map; single channels 8-bit image, which has the same size as image . @param threshold1 first threshold for the hysteresis procedure. @param threshold2 second threshold for the hysteresis procedure. @param apertureSize aperture size for the Sobel operator. @param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm \f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( L2gradient=false ). */ CV_EXPORTS_W void Canny( InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false ); /** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection. The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms of the formulae in the cornerEigenValsAndVecs description. @param src Input single-channel 8-bit or floating-point image. @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as src . @param blockSize Neighborhood size (see the details on cornerEigenValsAndVecs ). @param ksize Aperture parameter for the Sobel operator. @param borderType Pixel extrapolation method. See cv::BorderTypes. */ CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst, int blockSize, int ksize = 3, int borderType = BORDER_DEFAULT ); /** @brief Harris corner detector. The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it computes the following characteristic: \f[\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f] Corners in the image can be found as the local maxima of this response map. @param src Input single-channel 8-bit or floating-point image. @param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same size as src . @param blockSize Neighborhood size (see the details on cornerEigenValsAndVecs ). @param ksize Aperture parameter for the Sobel operator. @param k Harris detector free parameter. See the formula below. @param borderType Pixel extrapolation method. See cv::BorderTypes. */ CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, int ksize, double k, int borderType = BORDER_DEFAULT ); /** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection. For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as: \f[M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f] where the derivatives are computed using the Sobel operator. After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as \f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where - \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$ - \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$ - \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$ The output of the function can be used for robust edge or corner detection. @param src Input single-channel 8-bit or floating-point image. @param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . @param blockSize Neighborhood size (see details below). @param ksize Aperture parameter for the Sobel operator. @param borderType Pixel extrapolation method. See cv::BorderTypes. @sa cornerMinEigenVal, cornerHarris, preCornerDetect */ CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, int blockSize, int ksize, int borderType = BORDER_DEFAULT ); /** @brief Calculates a feature map for corner detection. The function calculates the complex spatial derivative-based function of the source image \f[\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\f] where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image derivatives, and \f$D_{xy}\f$ is the mixed derivative. The corners can be found as local maximums of the functions, as shown below: @code Mat corners, dilated_corners; preCornerDetect(image, corners, 3); // dilation with 3x3 rectangular structuring element dilate(corners, dilated_corners, Mat(), 1); Mat corner_mask = corners == dilated_corners; @endcode @param src Source single-channel 8-bit of floating-point image. @param dst Output image that has the type CV_32F and the same size as src . @param ksize %Aperture size of the Sobel . @param borderType Pixel extrapolation method. See cv::BorderTypes. */ CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize, int borderType = BORDER_DEFAULT ); /** @brief Refines the corner locations. The function iterates to find the sub-pixel accurate location of corners or radial saddle points, as shown on the figure below. ![image](pics/cornersubpix.png) Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$ to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$ subject to image and measurement noise. Consider the expression: \f[\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\f] where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up with \f$\epsilon_i\f$ set to zero: \f[\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\f] where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first gradient term \f$G\f$ and the second gradient term \f$b\f$ gives: \f[q = G^{-1} \cdot b\f] The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates until the center stays within a set threshold. @param image Input image. @param corners Initial coordinates of the input corners and refined coordinates provided for output. @param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , then a \f$5*2+1 \times 5*2+1 = 11 \times 11\f$ search window is used. @param zeroZone Half of the size of the dead region in the middle of the search zone over which the summation in the formula below is not done. It is used sometimes to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such a size. @param criteria Criteria for termination of the iterative process of corner refinement. That is, the process of corner position refinement stops either after criteria.maxCount iterations or when the corner position moves by less than criteria.epsilon on some iteration. */ CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners, Size winSize, Size zeroZone, TermCriteria criteria ); /** @brief Determines strong corners on an image. The function finds the most prominent corners in the image or in the specified image region, as described in @cite Shi94 - Function calculates the corner quality measure at every source image pixel using the cornerMinEigenVal or cornerHarris . - Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are retained). - The corners with the minimal eigenvalue less than \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. - The remaining corners are sorted by the quality measure in the descending order. - Function throws away each corner for which there is a stronger corner at a distance less than maxDistance. The function can be used to initialize a point-based tracker of an object. @note If the function is called with different values A and B of the parameter qualityLevel , and A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector with qualityLevel=B . @param image Input 8-bit or floating-point 32-bit, single-channel image. @param corners Output vector of detected corners. @param maxCorners Maximum number of corners to return. If there are more corners than are found, the strongest of them is returned. @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue (see cornerMinEigenVal ) or the Harris function response (see cornerHarris ). The corners with the quality measure less than the product are rejected. For example, if the best corner has the quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure less than 15 are rejected. @param minDistance Minimum possible Euclidean distance between the returned corners. @param mask Optional region of interest. If the image is not empty (it needs to have the type CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. @param blockSize Size of an average block for computing a derivative covariation matrix over each pixel neighborhood. See cornerEigenValsAndVecs . @param useHarrisDetector Parameter indicating whether to use a Harris detector (see cornerHarris) or cornerMinEigenVal. @param k Free parameter of the Harris detector. @sa cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, */ CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, int maxCorners, double qualityLevel, double minDistance, InputArray mask = noArray(), int blockSize = 3, bool useHarrisDetector = false, double k = 0.04 ); /** @example houghlines.cpp An example using the Hough line detector */ /** @brief Finds lines in a binary image using the standard Hough transform. The function implements the standard or standard multi-scale Hough transform algorithm for line detection. See for a good explanation of Hough transform. @param image 8-bit, single-channel binary source image. The image may be modified by the function. @param lines Output vector of lines. Each line is represented by a two-element vector \f$(\rho, \theta)\f$ . \f$\rho\f$ is the distance from the coordinate origin \f$(0,0)\f$ (top-left corner of the image). \f$\theta\f$ is the line rotation angle in radians ( \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ). @param rho Distance resolution of the accumulator in pixels. @param theta Angle resolution of the accumulator in radians. @param threshold Accumulator threshold parameter. Only those lines are returned that get enough votes ( \f$>\texttt{threshold}\f$ ). @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho . The coarse accumulator distance resolution is rho and the accurate accumulator resolution is rho/srn . If both srn=0 and stn=0 , the classical Hough transform is used. Otherwise, both these parameters should be positive. @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. @param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. Must fall between 0 and max_theta. @param max_theta For standard and multi-scale Hough transform, maximum angle to check for lines. Must fall between min_theta and CV_PI. */ CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI ); /** @brief Finds line segments in a binary image using the probabilistic Hough transform. The function implements the probabilistic Hough transform algorithm for line detection, described in @cite Matas00 See the line detection example below: @code #include #include using namespace cv; using namespace std; int main(int argc, char** argv) { Mat src, dst, color_dst; if( argc != 2 || !(src=imread(argv[1], 0)).data) return -1; Canny( src, dst, 50, 200, 3 ); cvtColor( dst, color_dst, COLOR_GRAY2BGR ); #if 0 vector lines; HoughLines( dst, lines, 1, CV_PI/180, 100 ); for( size_t i = 0; i < lines.size(); i++ ) { float rho = lines[i][0]; float theta = lines[i][1]; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; Point pt1(cvRound(x0 + 1000*(-b)), cvRound(y0 + 1000*(a))); Point pt2(cvRound(x0 - 1000*(-b)), cvRound(y0 - 1000*(a))); line( color_dst, pt1, pt2, Scalar(0,0,255), 3, 8 ); } #else vector lines; HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 ); for( size_t i = 0; i < lines.size(); i++ ) { line( color_dst, Point(lines[i][0], lines[i][1]), Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8 ); } #endif namedWindow( "Source", 1 ); imshow( "Source", src ); namedWindow( "Detected Lines", 1 ); imshow( "Detected Lines", color_dst ); waitKey(0); return 0; } @endcode This is a sample picture the function parameters have been tuned for: ![image](pics/building.jpg) And this is the output of the above program in case of the probabilistic Hough transform: ![image](pics/houghp.png) @param image 8-bit, single-channel binary source image. The image may be modified by the function. @param lines Output vector of lines. Each line is represented by a 4-element vector \f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected line segment. @param rho Distance resolution of the accumulator in pixels. @param theta Angle resolution of the accumulator in radians. @param threshold Accumulator threshold parameter. Only those lines are returned that get enough votes ( \f$>\texttt{threshold}\f$ ). @param minLineLength Minimum line length. Line segments shorter than that are rejected. @param maxLineGap Maximum allowed gap between points on the same line to link them. @sa LineSegmentDetector */ CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0 ); /** @example houghcircles.cpp An example using the Hough circle detector */ /** @brief Finds circles in a grayscale image using the Hough transform. The function finds circles in a grayscale image using a modification of the Hough transform. Example: : @code #include #include #include using namespace cv; using namespace std; int main(int argc, char** argv) { Mat img, gray; if( argc != 2 || !(img=imread(argv[1], 1)).data) return -1; cvtColor(img, gray, COLOR_BGR2GRAY); // smooth it, otherwise a lot of false circles may be detected GaussianBlur( gray, gray, Size(9, 9), 2, 2 ); vector circles; HoughCircles(gray, circles, HOUGH_GRADIENT, 2, gray.rows/4, 200, 100 ); for( size_t i = 0; i < circles.size(); i++ ) { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); // draw the circle center circle( img, center, 3, Scalar(0,255,0), -1, 8, 0 ); // draw the circle outline circle( img, center, radius, Scalar(0,0,255), 3, 8, 0 ); } namedWindow( "circles", 1 ); imshow( "circles", img ); waitKey(0); return 0; } @endcode @note Usually the function detects the centers of circles well. However, it may fail to find correct radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if you know it. Or, you may ignore the returned radius, use only the center, and find the correct radius using an additional procedure. @param image 8-bit, single-channel, grayscale input image. @param circles Output vector of found circles. Each vector is encoded as a 3-element floating-point vector \f$(x, y, radius)\f$ . @param method Detection method, see cv::HoughModes. Currently, the only implemented method is HOUGH_GRADIENT @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has half as big width and height. @param minDist Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed. @param param1 First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). @param param2 Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first. @param minRadius Minimum circle radius. @param maxRadius Maximum circle radius. @sa fitEllipse, minEnclosingCircle */ CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, int method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0 ); //! @} imgproc_feature //! @addtogroup imgproc_filter //! @{ /** @example morphology2.cpp An example using the morphological operations */ /** @brief Erodes an image by using a specific structuring element. The function erodes the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the minimum is taken: \f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In case of multi-channel images, each channel is processed independently. @param src input image; the number of channels can be arbitrary, but the depth should be one of CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src. @param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular structuring element is used. Kernel can be created using getStructuringElement. @param anchor position of the anchor within the element; default value (-1, -1) means that the anchor is at the element center. @param iterations number of times erosion is applied. @param borderType pixel extrapolation method, see cv::BorderTypes @param borderValue border value in case of a constant border @sa dilate, morphologyEx, getStructuringElement */ CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); /** @brief Dilates an image by using a specific structuring element. The function dilates the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the maximum is taken: \f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In case of multi-channel images, each channel is processed independently. @param src input image; the number of channels can be arbitrary, but the depth should be one of CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src\`. @param kernel structuring element used for dilation; if elemenat=Mat(), a 3 x 3 rectangular structuring element is used. Kernel can be created using getStructuringElement @param anchor position of the anchor within the element; default value (-1, -1) means that the anchor is at the element center. @param iterations number of times dilation is applied. @param borderType pixel extrapolation method, see cv::BorderTypes @param borderValue border value in case of a constant border @sa erode, morphologyEx, getStructuringElement */ CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); /** @brief Performs advanced morphological transformations. The function morphologyEx can perform advanced morphological transformations using an erosion and dilation as basic operations. Any of the operations can be done in-place. In case of multi-channel images, each channel is processed independently. @param src Source image. The number of channels can be arbitrary. The depth should be one of CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst Destination image of the same size and type as source image. @param op Type of a morphological operation, see cv::MorphTypes @param kernel Structuring element. It can be created using cv::getStructuringElement. @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the kernel center. @param iterations Number of times erosion and dilation are applied. @param borderType Pixel extrapolation method, see cv::BorderTypes @param borderValue Border value in case of a constant border. The default value has a special meaning. @sa dilate, erode, getStructuringElement */ CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); //! @} imgproc_filter //! @addtogroup imgproc_transform //! @{ /** @brief Resizes an image. The function resize resizes the image src down to or up to the specified size. Note that the initial dst type or size are not taken into account. Instead, the size and type are derived from the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst, you may call the function as follows: @code // explicitly specify dsize=dst.size(); fx and fy will be computed from that. resize(src, dst, dst.size(), 0, 0, interpolation); @endcode If you want to decimate the image by factor of 2 in each direction, you can call the function this way: @code // specify fx and fy and let the function compute the destination image size. resize(src, dst, Size(), 0.5, 0.5, interpolation); @endcode To shrink an image, it will generally look best with cv::INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with cv::INTER_CUBIC (slow) or cv::INTER_LINEAR (faster but still looks OK). @param src input image. @param dst output image; it has the size dsize (when it is non-zero) or the size computed from src.size(), fx, and fy; the type of dst is the same as of src. @param dsize output image size; if it equals zero, it is computed as: \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] Either dsize or both fx and fy must be non-zero. @param fx scale factor along the horizontal axis; when it equals 0, it is computed as \f[\texttt{(double)dsize.width/src.cols}\f] @param fy scale factor along the vertical axis; when it equals 0, it is computed as \f[\texttt{(double)dsize.height/src.rows}\f] @param interpolation interpolation method, see cv::InterpolationFlags @sa warpAffine, warpPerspective, remap */ CV_EXPORTS_W void resize( InputArray src, OutputArray dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR ); /** @brief Applies an affine transformation to an image. The function warpAffine transforms the source image using the specified matrix: \f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with cv::invertAffineTransform and then put in the formula above instead of M. The function cannot operate in-place. @param src input image. @param dst output image that has the size dsize and the same type as src . @param M \f$2\times 3\f$ transformation matrix. @param dsize size of the output image. @param flags combination of interpolation methods (see cv::InterpolationFlags) and the optional flag WARP_INVERSE_MAP that means that M is the inverse transformation ( \f$\texttt{dst}\rightarrow\texttt{src}\f$ ). @param borderMode pixel extrapolation method (see cv::BorderTypes); when borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to the "outliers" in the source image are not modified by the function. @param borderValue value used in case of a constant border; by default, it is 0. @sa warpPerspective, resize, remap, getRectSubPix, transform */ CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); /** @brief Applies a perspective transformation to an image. The function warpPerspective transforms the source image using the specified matrix: \f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert and then put in the formula above instead of M. The function cannot operate in-place. @param src input image. @param dst output image that has the size dsize and the same type as src . @param M \f$3\times 3\f$ transformation matrix. @param dsize size of the output image. @param flags combination of interpolation methods (INTER_LINEAR or INTER_NEAREST) and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation ( \f$\texttt{dst}\rightarrow\texttt{src}\f$ ). @param borderMode pixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE). @param borderValue value used in case of a constant border; by default, it equals 0. @sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform */ CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); /** @brief Applies a generic geometrical transformation to an image. The function remap transforms the source image using the specified map: \f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] where values of pixels with non-integer coordinates are computed using one of available interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in \f$map_1\f$, or fixed-point maps created by using convertMaps. The reason you might want to convert from floating to fixed-point representations of a map is that they can yield much faster (\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. This function cannot operate in-place. @param src Source image. @param dst Destination image. It has the same size as map1 and the same type as src . @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , CV_32FC1, or CV_32FC2. See convertMaps for details on converting a floating point representation to fixed-point for speed. @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map if map1 is (x,y) points), respectively. @param interpolation Interpolation method (see cv::InterpolationFlags). The method INTER_AREA is not supported by this function. @param borderMode Pixel extrapolation method (see cv::BorderTypes). When borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function. @param borderValue Value used in case of a constant border. By default, it is 0. */ CV_EXPORTS_W void remap( InputArray src, OutputArray dst, InputArray map1, InputArray map2, int interpolation, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); /** @brief Converts image transformation maps from one representation to another. The function converts a pair of maps for remap from one representation to another. The following options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are supported: - \f$\texttt{(CV\_32FC1, CV\_32FC1)} \rightarrow \texttt{(CV\_16SC2, CV\_16UC1)}\f$. This is the most frequently used conversion operation, in which the original floating-point maps (see remap ) are converted to a more compact and much faster fixed-point representation. The first output array contains the rounded coordinates and the second array (created only when nninterpolation=false ) contains indices in the interpolation tables. - \f$\texttt{(CV\_32FC2)} \rightarrow \texttt{(CV\_16SC2, CV\_16UC1)}\f$. The same as above but the original maps are stored in one 2-channel matrix. - Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same as the originals. @param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . @param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), respectively. @param dstmap1 The first output map that has the type dstmap1type and the same size as src . @param dstmap2 The second output map. @param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or CV_32FC2 . @param nninterpolation Flag indicating whether the fixed-point maps are used for the nearest-neighbor or for a more complex interpolation. @sa remap, undistort, initUndistortRectifyMap */ CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, int dstmap1type, bool nninterpolation = false ); /** @brief Calculates an affine matrix of 2D rotation. The function calculates the following matrix: \f[\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\f] where \f[\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f] The transformation maps the rotation center to itself. If this is not the target, adjust the shift. @param center Center of the rotation in the source image. @param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner). @param scale Isotropic scale factor. @sa getAffineTransform, warpAffine, transform */ CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale ); //! returns 3x3 perspective transformation for the corresponding 4 point pairs. CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] ); /** @brief Calculates an affine transform from three pairs of the corresponding points. The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that: \f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map\_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] where \f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f] @param src Coordinates of triangle vertices in the source image. @param dst Coordinates of the corresponding triangle vertices in the destination image. @sa warpAffine, transform */ CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); /** @brief Inverts an affine transformation. The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M: \f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f] The result is also a \f$2 \times 3\f$ matrix of the same type as M. @param M Original affine transformation. @param iM Output reverse affine transformation. */ CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM ); /** @brief Calculates a perspective transform from four pairs of the corresponding points. The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that: \f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map\_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] where \f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f] @param src Coordinates of quadrangle vertices in the source image. @param dst Coordinates of the corresponding quadrangle vertices in the destination image. @sa findHomography, warpPerspective, perspectiveTransform */ CV_EXPORTS_W Mat getPerspectiveTransform( InputArray src, InputArray dst ); CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst ); /** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy. The function getRectSubPix extracts pixels from src: \f[dst(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f] where the values of the pixels at non-integer coordinates are retrieved using bilinear interpolation. Every channel of multi-channel images is processed independently. While the center of the rectangle must be inside the image, parts of the rectangle may be outside. In this case, the replication border mode (see cv::BorderTypes) is used to extrapolate the pixel values outside of the image. @param image Source image. @param patchSize Size of the extracted patch. @param center Floating point coordinates of the center of the extracted rectangle within the source image. The center must be inside the image. @param patch Extracted patch that has the size patchSize and the same number of channels as src . @param patchType Depth of the extracted pixels. By default, they have the same depth as src . @sa warpAffine, warpPerspective */ CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize, Point2f center, OutputArray patch, int patchType = -1 ); /** @example polar_transforms.cpp An example using the cv::linearPolar and cv::logPolar operations */ /** @brief Remaps an image to log-polar space. transforms the source image using the following transformation: \f[dst( \phi , \rho ) = src(x,y)\f] where \f[\rho = M \cdot \log{\sqrt{x^2 + y^2}} , \phi =atan(y/x)\f] The function emulates the human "foveal" vision and can be used for fast scale and rotation-invariant template matching, for object tracking and so forth. The function can not operate in-place. @param src Source image @param dst Destination image @param center The transformation center; where the output precision is maximal @param M Magnitude scale parameter. @param flags A combination of interpolation methods, see cv::InterpolationFlags */ CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst, Point2f center, double M, int flags ); /** @brief Remaps an image to polar space. transforms the source image using the following transformation: \f[dst( \phi , \rho ) = src(x,y)\f] where \f[\rho = (src.width/maxRadius) \cdot \sqrt{x^2 + y^2} , \phi =atan(y/x)\f] The function can not operate in-place. @param src Source image @param dst Destination image @param center The transformation center; @param maxRadius Inverse magnitude scale parameter @param flags A combination of interpolation methods, see cv::InterpolationFlags */ CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst, Point2f center, double maxRadius, int flags ); //! @} imgproc_transform //! @addtogroup imgproc_misc //! @{ /** @overload */ CV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth = -1 ); /** @overload */ CV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum, OutputArray sqsum, int sdepth = -1, int sqdepth = -1 ); /** @brief Calculates the integral of an image. The functions calculate one or more integral images for the source image as follows: \f[\texttt{sum} (X,Y) = \sum _{x Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed with getOptimalDFTSize. The function performs the following equations: - First it applies a Hanning window (see ) to each image to remove possible edge effects. This window is cached until the array size changes to speed up processing time. - Next it computes the forward DFTs of each source array: \f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f] where \f$\mathcal{F}\f$ is the forward DFT. - It then computes the cross-power spectrum of each frequency domain array: \f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f] - Next the cross-correlation is converted back into the time domain via the inverse DFT: \f[r = \mathcal{F}^{-1}\{R\}\f] - Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to achieve sub-pixel accuracy. \f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f] - If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5 centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single peak) and will be smaller when there are multiple peaks. @param src1 Source floating point array (CV_32FC1 or CV_64FC1) @param src2 Source floating point array (CV_32FC1 or CV_64FC1) @param window Floating point array with windowing coefficients to reduce edge effects (optional). @param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). @returns detected phase shift (sub-pixel) between the two arrays. @sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow */ CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, InputArray window = noArray(), CV_OUT double* response = 0); /** @brief This function computes a Hanning window coefficients in two dimensions. See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function) for more information. An example is shown below: @code // create hanning window of size 100x100 and type CV_32F Mat hann; createHanningWindow(hann, Size(100, 100), CV_32F); @endcode @param dst Destination array to place Hann coefficients in @param winSize The window size specifications @param type Created array type */ CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); //! @} imgproc_motion //! @addtogroup imgproc_misc //! @{ /** @brief Applies a fixed-level threshold to each array element. The function applies fixed-level thresholding to a single-channel array. The function is typically used to get a bi-level (binary) image out of a grayscale image ( cv::compare could be also used for this purpose) or for removing a noise, that is, filtering out pixels with too small or too large values. There are several types of thresholding supported by the function. They are determined by type parameter. Also, the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined with one of the above values. In these cases, the function determines the optimal threshold value using the Otsu's or Triangle algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu's and Triangle methods are implemented only for 8-bit images. @param src input array (single-channel, 8-bit or 32-bit floating point). @param dst output array of the same size and type as src. @param thresh threshold value. @param maxval maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types. @param type thresholding type (see the cv::ThresholdTypes). @sa adaptiveThreshold, findContours, compare, min, max */ CV_EXPORTS_W double threshold( InputArray src, OutputArray dst, double thresh, double maxval, int type ); /** @brief Applies an adaptive threshold to an array. The function transforms a grayscale image to a binary image according to the formulae: - **THRESH_BINARY** \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f] - **THRESH_BINARY_INV** \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f] where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter). The function can process the image in-place. @param src Source 8-bit single-channel image. @param dst Destination image of the same size and the same type as src. @param maxValue Non-zero value assigned to the pixels for which the condition is satisfied @param adaptiveMethod Adaptive thresholding algorithm to use, see cv::AdaptiveThresholdTypes @param thresholdType Thresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV, see cv::ThresholdTypes. @param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. @param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well. @sa threshold, blur, GaussianBlur */ CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C ); //! @} imgproc_misc //! @addtogroup imgproc_filter //! @{ /** @brief Blurs an image and downsamples it. By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in any case, the following conditions should be satisfied: \f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f] The function performs the downsampling step of the Gaussian pyramid construction. First, it convolves the source image with the kernel: \f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f] Then, it downsamples the image by rejecting even rows and columns. @param src input image. @param dst output image; it has the specified size and the same type as src. @param dstsize size of the output image. @param borderType Pixel extrapolation method, see cv::BorderTypes (BORDER_CONSTANT isn't supported) */ CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); /** @brief Upsamples an image and then blurs it. By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any case, the following conditions should be satisfied: \f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\f] The function performs the upsampling step of the Gaussian pyramid construction, though it can actually be used to construct the Laplacian pyramid. First, it upsamples the source image by injecting even zero rows and columns and then convolves the result with the same kernel as in pyrDown multiplied by 4. @param src input image. @param dst output image. It has the specified size and the same type as src . @param dstsize size of the output image. @param borderType Pixel extrapolation method, see cv::BorderTypes (only BORDER_DEFAULT is supported) */ CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); /** @brief Constructs the Gaussian pyramid for an image. The function constructs a vector of images and builds the Gaussian pyramid by recursively applying pyrDown to the previously built pyramid layers, starting from `dst[0]==src`. @param src Source image. Check pyrDown for the list of supported types. @param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on. @param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative. @param borderType Pixel extrapolation method, see cv::BorderTypes (BORDER_CONSTANT isn't supported) */ CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, int maxlevel, int borderType = BORDER_DEFAULT ); //! @} imgproc_filter //! @addtogroup imgproc_transform //! @{ /** @brief Transforms an image to compensate for lens distortion. The function transforms an image to compensate radial and tangential lens distortion. The function is simply a combination of cv::initUndistortRectifyMap (with unity R ) and cv::remap (with bilinear interpolation). See the former function for details of the transformation being performed. Those pixels in the destination image, for which there is no correspondent pixels in the source image, are filled with zeros (black color). A particular subset of the source image that will be visible in the corrected image can be regulated by newCameraMatrix. You can use cv::getOptimalNewCameraMatrix to compute the appropriate newCameraMatrix depending on your requirements. The camera matrix and the distortion parameters can be determined using cv::calibrateCamera. If the resolution of images is different from the resolution used at the calibration stage, \f$f_x, f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain the same. @param src Input (distorted) image. @param dst Output (corrected) image that has the same size and type as src . @param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as cameraMatrix but you may additionally scale and shift the result by using a different matrix. */ CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray newCameraMatrix = noArray() ); /** @brief Computes the undistortion and rectification transformation map. The function computes the joint undistortion and rectification transformation and represents the result in the form of maps for remap. The undistorted image looks like original, as if it is captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by cv::getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera, newCameraMatrix is normally set to P1 or P2 computed by cv::stereoRectify . Also, this new camera is oriented differently in the coordinate space, according to R. That, for example, helps to align two heads of a stereo camera so that the epipolar lines on both images become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera). The function actually builds the maps for the inverse mapping algorithm that is used by remap. That is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function computes the corresponding coordinates in the source image (that is, in the original image from camera). The following process is applied: \f[ \begin{array}{l} x \leftarrow (u - {c'}_x)/{f'}_x \\ y \leftarrow (v - {c'}_y)/{f'}_y \\ {[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\ x' \leftarrow X/W \\ y' \leftarrow Y/W \\ r^2 \leftarrow x'^2 + y'^2 \\ x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\ y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ s\vecthree{x'''}{y'''}{1} = \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)} {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} {0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\ map_x(u,v) \leftarrow x''' f_x + c_x \\ map_y(u,v) \leftarrow y''' f_y + c_y \end{array} \f] where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ are the distortion coefficients. In case of a stereo camera, this function is called twice: once for each camera head, after stereoRectify, which in its turn is called after cv::stereoCalibrate. But if the stereo camera was not calibrated, it is still possible to compute the rectification transformations directly from the fundamental matrix using cv::stereoRectifyUncalibrated. For each camera, the function computes homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D space. R can be computed from H as \f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] where cameraMatrix can be chosen arbitrarily. @param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 , computed by stereoRectify can be passed here. If the matrix is empty, the identity transformation is assumed. In cvInitUndistortMap R assumed to be an identity matrix. @param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. @param size Undistorted image size. @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2, see cv::convertMaps @param map1 The first output map. @param map2 The second output map. */ CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs, InputArray R, InputArray newCameraMatrix, Size size, int m1type, OutputArray map1, OutputArray map2 ); //! initializes maps for cv::remap() for wide-angle CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, int destImageWidth, int m1type, OutputArray map1, OutputArray map2, int projType = PROJ_SPHERICAL_EQRECT, double alpha = 0); /** @brief Returns the default new camera matrix. The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true). In the latter case, the new camera matrix will be: \f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f] where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively. By default, the undistortion functions in OpenCV (see initUndistortRectifyMap, undistort) do not move the principal point. However, when you work with stereo, it is important to move the principal points in both views to the same y-coordinate (which is required by most of stereo correspondence algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for each view where the principal points are located at the center. @param cameraMatrix Input camera matrix. @param imgsize Camera view image size in pixels. @param centerPrincipalPoint Location of the principal point in the new camera matrix. The parameter indicates whether this location should be at the image center or not. */ CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize = Size(), bool centerPrincipalPoint = false ); /** @brief Computes the ideal point coordinates from the observed point coordinates. The function is similar to cv::undistort and cv::initUndistortRectifyMap but it operates on a sparse set of points instead of a raster image. Also the function performs a reverse transformation to projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a planar object, it does, up to a translation vector, if the proper R is specified. @code // (u,v) is the input point, (u', v') is the output point // camera_matrix=[fx 0 cx; 0 fy cy; 0 0 1] // P=[fx' 0 cx' tx; 0 fy' cy' ty; 0 0 1 tz] x" = (u - cx)/fx y" = (v - cy)/fy (x',y') = undistort(x",y",dist_coeffs) [X,Y,W]T = R*[x' y' 1]T x = X/W, y = Y/W // only performed if P=[fx' 0 cx' [tx]; 0 fy' cy' [ty]; 0 0 1 [tz]] is specified u' = x*fx' + cx' v' = y*fy' + cy', @endcode where cv::undistort is an approximate iterative algorithm that estimates the normalized original point coordinates out of the normalized distorted point coordinates ("normalized" means that the coordinates do not depend on the camera matrix). The function can be used for both a stereo camera head or a monocular camera (when R is empty). @param src Observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2). @param dst Output ideal point coordinates after undistortion and reverse perspective transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates. @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by cv::stereoRectify can be passed here. If the matrix is empty, the identity transformation is used. @param P New camera matrix (3x3) or new projection matrix (3x4). P1 or P2 computed by cv::stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used. */ CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray R = noArray(), InputArray P = noArray()); //! @} imgproc_transform //! @addtogroup imgproc_hist //! @{ /** @example demhist.cpp An example for creating histograms of an image */ /** @brief Calculates a histogram of a set of arrays. The functions calcHist calculate the histogram of one or more arrays. The elements of a tuple used to increment a histogram bin are taken from the corresponding input arrays at the same location. The sample below shows how to compute a 2D Hue-Saturation histogram for a color image. : @code #include #include using namespace cv; int main( int argc, char** argv ) { Mat src, hsv; if( argc != 2 || !(src=imread(argv[1], 1)).data ) return -1; cvtColor(src, hsv, COLOR_BGR2HSV); // Quantize the hue to 30 levels // and the saturation to 32 levels int hbins = 30, sbins = 32; int histSize[] = {hbins, sbins}; // hue varies from 0 to 179, see cvtColor float hranges[] = { 0, 180 }; // saturation varies from 0 (black-gray-white) to // 255 (pure spectrum color) float sranges[] = { 0, 256 }; const float* ranges[] = { hranges, sranges }; MatND hist; // we compute the histogram from the 0-th and 1-st channels int channels[] = {0, 1}; calcHist( &hsv, 1, channels, Mat(), // do not use mask hist, 2, histSize, ranges, true, // the histogram is uniform false ); double maxVal=0; minMaxLoc(hist, 0, &maxVal, 0, 0); int scale = 10; Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3); for( int h = 0; h < hbins; h++ ) for( int s = 0; s < sbins; s++ ) { float binVal = hist.at(h, s); int intensity = cvRound(binVal*255/maxVal); rectangle( histImg, Point(h*scale, s*scale), Point( (h+1)*scale - 1, (s+1)*scale - 1), Scalar::all(intensity), CV_FILLED ); } namedWindow( "Source", 1 ); imshow( "Source", src ); namedWindow( "H-S Histogram", 1 ); imshow( "H-S Histogram", histImg ); waitKey(); } @endcode @param images Source arrays. They all should have the same depth, CV_8U or CV_32F , and the same size. Each of them can have an arbitrary number of channels. @param nimages Number of source images. @param channels List of the dims channels used to compute the histogram. The first array channels are numerated from 0 to images[0].channels()-1 , the second array channels are counted from images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. @param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size as images[i] . The non-zero mask elements mark the array elements counted in the histogram. @param hist Output histogram, which is a dense or sparse dims -dimensional array. @param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS (equal to 32 in the current OpenCV version). @param histSize Array of histogram sizes in each dimension. @param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower (inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary \f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform ( uniform=false ), then each of ranges[i] contains histSize[i]+1 elements: \f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$ . The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not counted in the histogram. @param uniform Flag indicating whether the histogram is uniform or not (see above). @param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning when it is allocated. This feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time. */ CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform = true, bool accumulate = false ); /** @overload this variant uses cv::SparseMat for output */ CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, SparseMat& hist, int dims, const int* histSize, const float** ranges, bool uniform = true, bool accumulate = false ); /** @overload */ CV_EXPORTS_W void calcHist( InputArrayOfArrays images, const std::vector& channels, InputArray mask, OutputArray hist, const std::vector& histSize, const std::vector& ranges, bool accumulate = false ); /** @brief Calculates the back projection of a histogram. The functions calcBackProject calculate the back project of the histogram. That is, similarly to cv::calcHist , at each location (x, y) the function collects the values from the selected channels in the input images and finds the corresponding histogram bin. But instead of incrementing it, the function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of statistics, the function computes probability of each element value in respect with the empirical probability distribution represented by the histogram. See how, for example, you can find and track a bright-colored object in a scene: - Before tracking, show the object to the camera so that it covers almost the whole frame. Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant colors in the object. - When tracking, calculate a back projection of a hue plane of each input video frame using that pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels. - Find connected components in the resulting picture and choose, for example, the largest component. This is an approximate algorithm of the CamShift color object tracker. @param images Source arrays. They all should have the same depth, CV_8U or CV_32F , and the same size. Each of them can have an arbitrary number of channels. @param nimages Number of source images. @param channels The list of channels used to compute the back projection. The number of channels must match the histogram dimensionality. The first array channels are numerated from 0 to images[0].channels()-1 , the second array channels are counted from images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. @param hist Input histogram that can be dense or sparse. @param backProject Destination back projection array that is a single-channel array of the same size and depth as images[0] . @param ranges Array of arrays of the histogram bin boundaries in each dimension. See calcHist . @param scale Optional scale factor for the output back projection. @param uniform Flag indicating whether the histogram is uniform or not (see above). @sa cv::calcHist, cv::compareHist */ CV_EXPORTS void calcBackProject( const Mat* images, int nimages, const int* channels, InputArray hist, OutputArray backProject, const float** ranges, double scale = 1, bool uniform = true ); /** @overload */ CV_EXPORTS void calcBackProject( const Mat* images, int nimages, const int* channels, const SparseMat& hist, OutputArray backProject, const float** ranges, double scale = 1, bool uniform = true ); /** @overload */ CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector& channels, InputArray hist, OutputArray dst, const std::vector& ranges, double scale ); /** @brief Compares two histograms. The function compare two dense or two sparse histograms using the specified method. The function returns \f$d(H_1, H_2)\f$ . While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms or more general sparse configurations of weighted points, consider using the cv::EMD function. @param H1 First compared histogram. @param H2 Second compared histogram of the same size as H1 . @param method Comparison method, see cv::HistCompMethods */ CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); /** @overload */ CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); /** @brief Equalizes the histogram of a grayscale image. The function equalizes the histogram of the input image using the following algorithm: - Calculate the histogram \f$H\f$ for src . - Normalize the histogram so that the sum of histogram bins is 255. - Compute the integral of the histogram: \f[H'_i = \sum _{0 \le j < i} H(j)\f] - Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ The algorithm normalizes the brightness and increases the contrast of the image. @param src Source 8-bit single channel image. @param dst Destination image of the same size and type as src . */ CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); /** @brief Computes the "minimal work" distance between two weighted point configurations. The function computes the earth mover distance and/or a lower boundary of the distance between the two weighted point configurations. One of the applications described in @cite RubnerSept98, @cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation problem that is solved using some modification of a simplex algorithm, thus the complexity is exponential in the worst case, though, on average it is much faster. In the case of a real metric the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used to determine roughly whether the two signatures are far enough so that they cannot relate to the same object. @param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix. Each row stores the point weight followed by the point coordinates. The matrix is allowed to have a single column (weights only) if the user-defined cost matrix is used. @param signature2 Second signature of the same format as signature1 , though the number of rows may be different. The total weights may be different. In this case an extra "dummy" point is added to either signature1 or signature2 . @param distType Used metric. See cv::DistanceTypes. @param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix is used, lower boundary lowerBound cannot be calculated because it needs a metric function. @param lowerBound Optional input/output parameter: lower boundary of a distance between the two signatures that is a distance between mass centers. The lower boundary may not be calculated if the user-defined cost matrix is used, the total weights of point configurations are not equal, or if the signatures consist of weights only (the signature matrices have a single column). You **must** initialize \*lowerBound . If the calculated distance between mass centers is greater or equal to \*lowerBound (it means that the signatures are far enough), the function does not calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound should be set to 0. @param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 . */ CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), float* lowerBound = 0, OutputArray flow = noArray() ); //! @} imgproc_hist /** @example watershed.cpp An example using the watershed algorithm */ /** @brief Performs a marker-based image segmentation using the watershed algorithm. The function implements one of the variants of watershed, non-parametric marker-based segmentation algorithm, described in @cite Meyer92 . Before passing the image to the function, you have to roughly outline the desired regions in the image markers with positive (\>0) indices. So, every region is represented as one or more connected components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary mask using findContours and drawContours (see the watershed.cpp demo). The markers are "seeds" of the future image regions. All the other pixels in markers , whose relation to the outlined regions is not known and should be defined by the algorithm, should be set to 0's. In the function output, each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the regions. @note Any two neighbor connected components are not necessarily separated by a watershed boundary (-1's pixels); for example, they can touch each other in the initial marker image passed to the function. @param image Input 8-bit 3-channel image. @param markers Input/output 32-bit single-channel image (map) of markers. It should have the same size as image . @sa findContours @ingroup imgproc_misc */ CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers ); //! @addtogroup imgproc_filter //! @{ /** @brief Performs initial step of meanshift segmentation of an image. The function implements the filtering stage of meanshift segmentation, that is, the output of the function is the filtered "posterized" image with color gradients and fine-grain texture flattened. At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is considered: \f[(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\f] where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively (though, the algorithm does not depend on the color space used, so any 3-component color space can be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector (R',G',B') are found and they act as the neighborhood center on the next iteration: \f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f] After the iterations over, the color components of the initial pixel (that is, the pixel from where the iterations started) are set to the final value (average color at the last iteration): \f[I(X,Y) <- (R*,G*,B*)\f] When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is run on the smallest layer first. After that, the results are propagated to the larger layer and the iterations are run again only on those pixels where the layer colors differ by more than sr from the lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the results will be actually different from the ones obtained by running the meanshift procedure on the whole original image (i.e. when maxLevel==0). @param src The source 8-bit, 3-channel image. @param dst The destination image of the same format and the same size as the source. @param sp The spatial window radius. @param sr The color window radius. @param maxLevel Maximum level of the pyramid for the segmentation. @param termcrit Termination criteria: when to stop meanshift iterations. */ CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst, double sp, double sr, int maxLevel = 1, TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); //! @} //! @addtogroup imgproc_misc //! @{ /** @example grabcut.cpp An example using the GrabCut algorithm */ /** @brief Runs the GrabCut algorithm. The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). @param img Input 8-bit 3-channel image. @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when mode is set to GC_INIT_WITH_RECT. Its elements may have one of the cv::GrabCutClasses. @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as "obvious background". The parameter is only used when mode==GC_INIT_WITH_RECT . @param bgdModel Temporary array for the background model. Do not modify it while you are processing the same image. @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are processing the same image. @param iterCount Number of iterations the algorithm should make before returning the result. Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL . @param mode Operation mode that could be one of the cv::GrabCutModes */ CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, int mode = GC_EVAL ); /** @example distrans.cpp An example on using the distance transform\ */ /** @brief Calculates the distance to the closest zero pixel for each pixel of the source image. The functions distanceTransform calculate the approximate or precise distance from every binary image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. When maskSize == DIST_MASK_PRECISE and distanceType == DIST_L2 , the function runs the algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library. In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall distance is calculated as a sum of these basic distances. Since the distance function should be symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the same cost (denoted as `c`). For the cv::DIST_C and cv::DIST_L1 types, the distance is calculated precisely, whereas for cv::DIST_L2 (Euclidean distance) the distance can be calculated only with a relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV uses the values suggested in the original paper: - DIST_L1: `a = 1, b = 2` - DIST_L2: - `3 x 3`: `a=0.955, b=1.3693` - `5 x 5`: `a=1, b=1.4, c=2.1969` - DIST_C: `a = 1, b = 1` Typically, for a fast, coarse distance estimation DIST_L2, a \f$3\times 3\f$ mask is used. For a more accurate distance estimation DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used. Note that both the precise and the approximate algorithms are linear on the number of pixels. This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$ but also identifies the nearest connected component consisting of zero pixels (labelType==DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==DIST_LABEL_PIXEL). Index of the component/pixel is stored in `labels(x, y)`. When labelType==DIST_LABEL_CCOMP, the function automatically finds connected components of zero pixels in the input image and marks them with distinct labels. When labelType==DIST_LABEL_CCOMP, the function scans through the input image and marks all the zero pixels with distinct labels. In this mode, the complexity is still linear. That is, the function provides a very fast way to compute the Voronoi diagram for a binary image. Currently, the second variant can use only the approximate distance transform algorithm, i.e. maskSize=DIST_MASK_PRECISE is not supported yet. @param src 8-bit, single-channel (binary) source image. @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, single-channel image of the same size as src. @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type CV_32SC1 and the same size as src. @param distanceType Type of distance, see cv::DistanceTypes @param maskSize Size of the distance transform mask, see cv::DistanceTransformMasks. DIST_MASK_PRECISE is not supported by this variant. In case of the DIST_L1 or DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times 5\f$ or any larger aperture. @param labelType Type of the label array to build, see cv::DistanceTransformLabelTypes. */ CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, OutputArray labels, int distanceType, int maskSize, int labelType = DIST_LABEL_CCOMP ); /** @overload @param src 8-bit, single-channel (binary) source image. @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, single-channel image of the same size as src . @param distanceType Type of distance, see cv::DistanceTypes @param maskSize Size of the distance transform mask, see cv::DistanceTransformMasks. In case of the DIST_L1 or DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times 5\f$ or any larger aperture. @param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for the first variant of the function and distanceType == DIST_L1. */ CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, int distanceType, int maskSize, int dstType=CV_32F); /** @example ffilldemo.cpp An example using the FloodFill technique */ /** @overload variant without `mask` parameter */ CV_EXPORTS int floodFill( InputOutputArray image, Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4 ); /** @brief Fills a connected component with the given color. The functions floodFill fill a connected component starting from the seed point with the specified color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if: - in case of a grayscale image and floating range \f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f] - in case of a grayscale image and fixed range \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f] - in case of a color image and floating range \f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f] \f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f] and \f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f] - in case of a color image and fixed range \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f] \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f] and \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f] where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the component. That is, to be added to the connected component, a color/brightness of the pixel should be close enough to: - Color/brightness of one of its neighbors that already belong to the connected component in case of a floating range. - Color/brightness of the seed point in case of a fixed range. Use these functions to either mark a connected component with the specified color in-place, or build a mask and then extract the contour, or copy the region to another image, and so on. @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See the details below. @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels taller than image. Since this is both an input and output parameter, you must take responsibility of initializing it. Flood-filling cannot go across non-zero pixels in the input mask. For example, an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the mask corresponding to filled pixels in the image are set to 1 or to the a value specified in flags as described below. It is therefore possible to use the same mask in multiple calls to the function to make sure the filled areas do not overlap. @param seedPoint Starting point. @param newVal New value of the repainted domain pixels. @param loDiff Maximal lower brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component. @param upDiff Maximal upper brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component. @param rect Optional output parameter set by the function to the minimum bounding rectangle of the repainted domain. @param flags Operation flags. The first 8 bits contain a connectivity value. The default value of 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest neighbours and fill the mask with a value of 255. The following additional options occupy higher bits and therefore may be further combined with the connectivity and mask fill values using bit-wise or (|), see cv::FloodFillFlags. @note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the pixel \f$(x+1, y+1)\f$ in the mask . @sa findContours */ CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4 ); /** @brief Converts an image from one color space to another. The function converts an input image from one color space to another. In case of a transformation to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. The conventional ranges for R, G, and B channel values are: - 0 to 255 for CV_8U images - 0 to 65535 for CV_16U images - 0 to 1 for CV_32F images In case of linear transformations, the range does not matter. But in case of a non-linear transformation, an input RGB image should be normalized to the proper value range to get the correct results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a 32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will have the 0..255 value range instead of 0..1 assumed by the function. So, before calling cvtColor , you need first to scale the image down: @code img *= 1./255; cvtColor(img, img, COLOR_BGR2Luv); @endcode If you use cvtColor with 8-bit images, the conversion will have some information lost. For many applications, this will not be noticeable but it is recommended to use 32-bit images in applications that need the full range of colors or that convert an image before an operation and then convert back. If conversion adds the alpha channel, its value will set to the maximum of corresponding channel range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point. @param dst output image of the same size and depth as src. @param code color space conversion code (see cv::ColorConversionCodes). @param dstCn number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code. @see @ref imgproc_color_conversions */ CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0 ); //! @} imgproc_misc // main function for all demosaicing procceses CV_EXPORTS_W void demosaicing(InputArray _src, OutputArray _dst, int code, int dcn = 0); //! @addtogroup imgproc_shape //! @{ /** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape. The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The results are returned in the structure cv::Moments. @param array Raster image (single-channel, 8-bit or floating-point 2D array) or an array ( \f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f ). @param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is used for images only. @returns moments. @sa contourArea, arcLength */ CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false ); /** @brief Calculates seven Hu invariants. The function calculates seven Hu invariants (introduced in @cite Hu62; see also ) defined as: \f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f] where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ . These values are proved to be invariants to the image scale, rotation, and reflection except the seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of infinite image resolution. In case of raster images, the computed Hu invariants for the original and transformed images are a bit different. @param moments Input moments computed with moments . @param hu Output Hu invariants. @sa matchShapes */ CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); /** @overload */ CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu ); //! @} imgproc_shape //! @addtogroup imgproc_object //! @{ //! type of the template matching operation enum TemplateMatchModes { TM_SQDIFF = 0, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f] TM_SQDIFF_NORMED = 1, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] TM_CCORR = 2, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f] TM_CCORR_NORMED = 3, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] TM_CCOEFF = 4, //!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f] //!< where //!< \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f] TM_CCOEFF_NORMED = 5 //!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }\f] }; /** @brief Compares a template against overlapped image regions. The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against templ using the specified method and stores the comparison results in result . Here are the formulae for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ template, \f$R\f$ result ). The summation is done over template and/or the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$ After the function finishes the comparison, the best matches can be found as global minimums (when TM_SQDIFF was used) or maximums (when TM_CCORR or TM_CCOEFF was used) using the minMaxLoc function. In case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels and separate mean values are used for each channel. That is, the function can take a color template and a color image. The result will still be a single-channel image, which is easier to analyze. @param image Image where the search is running. It must be 8-bit or 32-bit floating-point. @param templ Searched template. It must be not greater than the source image and have the same data type. @param result Map of comparison results. It must be single-channel 32-bit floating-point. If image is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ . @param method Parameter specifying the comparison method, see cv::TemplateMatchModes @param mask Mask of searched template. It must have the same datatype and size with templ. It is not set by default. */ CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ, OutputArray result, int method, InputArray mask = noArray() ); //! @} //! @addtogroup imgproc_shape //! @{ /** @brief computes the connected components labeled image of boolean image image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image. @param image the 8-bit single-channel image to be labeled @param labels destination labeled image @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively @param ltype output image label type. Currently CV_32S and CV_16U are supported. */ CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels, int connectivity = 8, int ltype = CV_32S); /** @overload @param image the 8-bit single-channel image to be labeled @param labels destination labeled image @param stats statistics output for each label, including the background label, see below for available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of cv::ConnectedComponentsTypes. The data type is CV_32S. @param centroids centroid output for each label, including the background label. Centroids are accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively @param ltype output image label type. Currently CV_32S and CV_16U are supported. */ CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats, OutputArray centroids, int connectivity = 8, int ltype = CV_32S); /** @brief Finds contours in a binary image. The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours are a useful tool for shape analysis and object detection and recognition. See squares.c in the OpenCV sample directory. @note Source image is modified by this function. Also, the function does not take into account 1-pixel border of the image (it's filled with 0's and used for neighbor analysis in the algorithm), therefore the contours touching the image border will be clipped. @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero pixels remain 0's, so the image is treated as binary . You can use compare , inRange , threshold , adaptiveThreshold , Canny , and others to create a binary image out of a grayscale or color one. The function modifies the image while extracting the contours. If mode equals to RETR_CCOMP or RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). @param contours Detected contours. Each contour is stored as a vector of points. @param hierarchy Optional output vector, containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i] , the elements hierarchy[i][0] , hiearchy[i][1] , hiearchy[i][2] , and hiearchy[i][3] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. @param mode Contour retrieval mode, see cv::RetrievalModes @param method Contour approximation method, see cv::ContourApproximationModes @param offset Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. */ CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset = Point()); /** @overload */ CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset = Point()); /** @brief Approximates a polygonal curve(s) with the specified precision. The functions approxPolyDP approximate a curve or a polygon with another curve/polygon with less vertices so that the distance between them is less or equal to the specified precision. It uses the Douglas-Peucker algorithm @param curve Input vector of a 2D point stored in std::vector or Mat @param approxCurve Result of the approximation. The type should match the type of the input curve. @param epsilon Parameter specifying the approximation accuracy. This is the maximum distance between the original curve and its approximation. @param closed If true, the approximated curve is closed (its first and last vertices are connected). Otherwise, it is not closed. */ CV_EXPORTS_W void approxPolyDP( InputArray curve, OutputArray approxCurve, double epsilon, bool closed ); /** @brief Calculates a contour perimeter or a curve length. The function computes a curve length or a closed contour perimeter. @param curve Input vector of 2D points, stored in std::vector or Mat. @param closed Flag indicating whether the curve is closed or not. */ CV_EXPORTS_W double arcLength( InputArray curve, bool closed ); /** @brief Calculates the up-right bounding rectangle of a point set. The function calculates and returns the minimal up-right bounding rectangle for the specified point set. @param points Input 2D point set, stored in std::vector or Mat. */ CV_EXPORTS_W Rect boundingRect( InputArray points ); /** @brief Calculates a contour area. The function computes a contour area. Similarly to moments , the area is computed using the Green formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using drawContours or fillPoly , can be different. Also, the function will most certainly give a wrong results for contours with self-intersections. Example: @code vector contour; contour.push_back(Point2f(0, 0)); contour.push_back(Point2f(10, 0)); contour.push_back(Point2f(10, 10)); contour.push_back(Point2f(5, 4)); double area0 = contourArea(contour); vector approx; approxPolyDP(contour, approx, 5, true); double area1 = contourArea(approx); cout << "area0 =" << area0 << endl << "area1 =" << area1 << endl << "approx poly vertices" << approx.size() << endl; @endcode @param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. @param oriented Oriented area flag. If it is true, the function returns a signed area value, depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can determine orientation of a contour by taking the sign of an area. By default, the parameter is false, which means that the absolute value is returned. */ CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false ); /** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set. The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a specified point set. See the OpenCV sample minarea.cpp . Developer should keep in mind that the returned rotatedRect can contain negative indices when data is close to the containing Mat element boundary. @param points Input vector of 2D points, stored in std::vector\<\> or Mat */ CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); /** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle. The function finds the four vertices of a rotated rectangle. This function is useful to draw the rectangle. In C++, instead of using this function, you can directly use box.points() method. Please visit the [tutorial on bounding rectangle](http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html#bounding-rects-circles) for more information. @param box The input rotated rectangle. It may be the output of @param points The output array of four vertices of rectangles. */ CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points); /** @brief Finds a circle of the minimum area enclosing a 2D point set. The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. See the OpenCV sample minarea.cpp . @param points Input vector of 2D points, stored in std::vector\<\> or Mat @param center Output center of the circle. @param radius Output radius of the circle. */ CV_EXPORTS_W void minEnclosingCircle( InputArray points, CV_OUT Point2f& center, CV_OUT float& radius ); /** @example minarea.cpp */ /** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area. The function finds a triangle of minimum area enclosing the given set of 2D points and returns its area. The output for a given 2D point set is shown in the image below. 2D points are depicted in *red* and the enclosing triangle in *yellow*. ![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png) The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's @cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal enclosing triangle of a 2D convex polygon with n vertices. Since the minEnclosingTriangle function takes a 2D point set as input an additional preprocessing step of computing the convex hull of the 2D point set is required. The complexity of the convexHull function is \f$O(n log(n))\f$ which is higher than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$. @param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat @param triangle Output vector of three 2D points defining the vertices of the triangle. The depth of the OutputArray must be CV_32F. */ CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle ); /** @brief Compares two shapes. The function compares two shapes. All three implemented methods use the Hu invariants (see cv::HuMoments) @param contour1 First contour or grayscale image. @param contour2 Second contour or grayscale image. @param method Comparison method, see ::ShapeMatchModes @param parameter Method-specific parameter (not supported now). */ CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, int method, double parameter ); /** @example convexhull.cpp An example using the convexHull functionality */ /** @brief Finds the convex hull of a point set. The functions find the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82 that has *O(N logN)* complexity in the current implementation. See the OpenCV sample convexhull.cpp that demonstrates the usage of different function variants. @param points Input 2D point set, stored in std::vector or Mat. @param hull Output convex hull. It is either an integer vector of indices or vector of points. In the first case, the hull elements are 0-based indices of the convex hull points in the original array (since the set of convex hull points is a subset of the original point set). In the second case, hull elements are the convex hull points themselves. @param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise. Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing to the right, and its Y axis pointing upwards. @param returnPoints Operation flag. In case of a matrix, when the flag is true, the function returns convex hull points. Otherwise, it returns indices of the convex hull points. When the output array is std::vector, the flag is ignored, and the output depends on the type of the vector: std::vector\ implies returnPoints=true, std::vector\ implies returnPoints=false. */ CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, bool clockwise = false, bool returnPoints = true ); /** @brief Finds the convexity defects of a contour. The figure below displays convexity defects of a hand contour: ![image](pics/defects.png) @param contour Input contour. @param convexhull Convex hull obtained using convexHull that should contain indices of the contour points that make the hull. @param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java interface each convexity defect is represented as 4-element integer vector (a.k.a. cv::Vec4i): (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices in the original contour of the convexity defect beginning, end and the farthest point, and fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the farthest contour point and the hull. That is, to get the floating-point value of the depth will be fixpt_depth/256.0. */ CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); /** @brief Tests a contour convexity. The function tests whether the input contour is convex or not. The contour must be simple, that is, without self-intersections. Otherwise, the function output is undefined. @param contour Input vector of 2D points, stored in std::vector\<\> or Mat */ CV_EXPORTS_W bool isContourConvex( InputArray contour ); //! finds intersection of two convex polygons CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2, OutputArray _p12, bool handleNested = true ); /** @example fitellipse.cpp An example using the fitEllipse technique */ /** @brief Fits an ellipse around a set of 2D points. The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95 is used. Developer should keep in mind that it is possible that the returned ellipse/rotatedRect data contains negative indices, due to the data points being close to the border of the containing Mat element. @param points Input 2D point set, stored in std::vector\<\> or Mat */ CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); /** @brief Fits a line to a 2D or 3D point set. The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where \f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one of the following: - DIST_L2 \f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] - DIST_L1 \f[\rho (r) = r\f] - DIST_L12 \f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] - DIST_FAIR \f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] - DIST_WELSCH \f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] - DIST_HUBER \f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] The algorithm is based on the M-estimator ( ) technique that iteratively fits the line using the weighted least-squares algorithm. After each iteration the weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . @param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat. @param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements (like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line and (x0, y0, z0) is a point on the line. @param distType Distance used by the M-estimator, see cv::DistanceTypes @param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value is chosen. @param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). @param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. */ CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, double param, double reps, double aeps ); /** @brief Performs a point-in-contour test. The function determines whether the point is inside a contour, outside, or lies on an edge (or coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. Otherwise, the return value is a signed distance between the point and the nearest contour edge. See below a sample output of the function where each image pixel is tested against the contour: ![sample output](pics/pointpolygon.png) @param contour Input contour. @param pt Point tested against the contour. @param measureDist If true, the function estimates the signed distance from the point to the nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. */ CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); /** @brief Finds out if there is any intersection between two rotated rectangles. If there is then the vertices of the interesecting region are returned as well. Below are some examples of intersection configurations. The hatched pattern indicates the intersecting region and the red vertices are returned by the function. ![intersection examples](pics/intersection.png) @param rect1 First rectangle @param rect2 Second rectangle @param intersectingRegion The output array of the verticies of the intersecting region. It returns at most 8 vertices. Stored as std::vector\ or cv::Mat as Mx1 of type CV_32FC2. @returns One of cv::RectanglesIntersectTypes */ CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion ); //! @} imgproc_shape CV_EXPORTS_W Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122. //! Detects position only without traslation and rotation CV_EXPORTS Ptr createGeneralizedHoughBallard(); //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038. //! Detects position, traslation and rotation CV_EXPORTS Ptr createGeneralizedHoughGuil(); //! Performs linear blending of two images CV_EXPORTS void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst); //! @addtogroup imgproc_colormap //! @{ //! GNU Octave/MATLAB equivalent colormaps enum ColormapTypes { COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg) COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg) COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg) COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg) COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg) COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg) COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg) COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg) COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg) COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg) COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg) COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg) COLORMAP_PARULA = 12 //!< ![parula](pics/colormaps/colorscale_parula.jpg) }; /** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image. @param src The source image, grayscale or colored does not matter. @param dst The result is the colormapped source image. Note: Mat::create is called on dst. @param colormap The colormap to apply, see cv::ColormapTypes */ CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); //! @} imgproc_colormap //! @addtogroup imgproc_draw //! @{ /** @brief Draws a line segment connecting two points. The function line draws the line segment between pt1 and pt2 points in the image. The line is clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased lines are drawn using Gaussian filtering. @param img Image. @param pt1 First point of the line segment. @param pt2 Second point of the line segment. @param color Line color. @param thickness Line thickness. @param lineType Type of the line, see cv::LineTypes. @param shift Number of fractional bits in the point coordinates. */ CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @brief Draws a arrow segment pointing from the first point to the second one. The function arrowedLine draws an arrow between pt1 and pt2 points in the image. See also cv::line. @param img Image. @param pt1 The point the arrow starts from. @param pt2 The point the arrow points to. @param color Line color. @param thickness Line thickness. @param line_type Type of the line, see cv::LineTypes @param shift Number of fractional bits in the point coordinates. @param tipLength The length of the arrow tip in relation to the arrow length */ CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int line_type=8, int shift=0, double tipLength=0.1); /** @brief Draws a simple, thick, or filled up-right rectangle. The function rectangle draws a rectangle outline or a filled rectangle whose two opposite corners are pt1 and pt2. @param img Image. @param pt1 Vertex of the rectangle. @param pt2 Vertex of the rectangle opposite to pt1 . @param color Rectangle color or brightness (grayscale image). @param thickness Thickness of lines that make up the rectangle. Negative values, like CV_FILLED , mean that the function has to draw a filled rectangle. @param lineType Type of the line. See the line description. @param shift Number of fractional bits in the point coordinates. */ CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @overload use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and r.br()-Point(1,1)` are opposite corners */ CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @brief Draws a circle. The function circle draws a simple or filled circle with a given center and radius. @param img Image where the circle is drawn. @param center Center of the circle. @param radius Radius of the circle. @param color Circle color. @param thickness Thickness of the circle outline, if positive. Negative thickness means that a filled circle is to be drawn. @param lineType Type of the circle boundary. See the line description. @param shift Number of fractional bits in the coordinates of the center and in the radius value. */ CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @brief Draws a simple or thick elliptic arc or fills an ellipse sector. The functions ellipse with less parameters draw an ellipse outline, a filled ellipse, an elliptic arc, or a filled ellipse sector. A piecewise-linear curve is used to approximate the elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the curve using ellipse2Poly and then render it with polylines or fill it with fillPoly . If you use the first variant of the function and want to draw the whole ellipse, not an arc, pass startAngle=0 and endAngle=360 . The figure below explains the meaning of the parameters. ![Parameters of Elliptic Arc](pics/ellipse.png) @param img Image. @param center Center of the ellipse. @param axes Half of the size of the ellipse main axes. @param angle Ellipse rotation angle in degrees. @param startAngle Starting angle of the elliptic arc in degrees. @param endAngle Ending angle of the elliptic arc in degrees. @param color Ellipse color. @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that a filled ellipse sector is to be drawn. @param lineType Type of the ellipse boundary. See the line description. @param shift Number of fractional bits in the coordinates of the center and values of axes. */ CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @overload @param img Image. @param box Alternative ellipse representation via RotatedRect. This means that the function draws an ellipse inscribed in the rotated rectangle. @param color Ellipse color. @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that a filled ellipse sector is to be drawn. @param lineType Type of the ellipse boundary. See the line description. */ CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color, int thickness = 1, int lineType = LINE_8); /* ----------------------------------------------------------------------------------------- */ /* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */ /* ----------------------------------------------------------------------------------------- */ //! Possible set of marker types used for the cv::drawMarker function enum MarkerTypes { MARKER_CROSS = 0, //!< A crosshair marker shape MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross MARKER_DIAMOND = 3, //!< A diamond marker shape MARKER_SQUARE = 4, //!< A square marker shape MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape }; /** @brief Draws a marker on a predefined position in an image. The function drawMarker draws a marker on a given position in the image. For the moment several marker types are supported, see cv::MarkerTypes for more information. @param img Image. @param position The point where the crosshair is positioned. @param markerType The specific type of marker you want to use, see cv::MarkerTypes @param color Line color. @param thickness Line thickness. @param line_type Type of the line, see cv::LineTypes @param markerSize The length of the marker axis [default = 20 pixels] */ CV_EXPORTS_W void drawMarker(CV_IN_OUT Mat& img, Point position, const Scalar& color, int markerType = MARKER_CROSS, int markerSize=20, int thickness=1, int line_type=8); /* ----------------------------------------------------------------------------------------- */ /* END OF MARKER SECTION */ /* ----------------------------------------------------------------------------------------- */ /** @overload */ CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType = LINE_8, int shift = 0); /** @brief Fills a convex polygon. The function fillConvexPoly draws a filled convex polygon. This function is much faster than the function cv::fillPoly . It can fill not only convex polygons but any monotonic polygon without self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) twice at the most (though, its top-most and/or the bottom edge could be horizontal). @param img Image. @param points Polygon vertices. @param color Polygon color. @param lineType Type of the polygon boundaries. See the line description. @param shift Number of fractional bits in the vertex coordinates. */ CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points, const Scalar& color, int lineType = LINE_8, int shift = 0); /** @overload */ CV_EXPORTS void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int lineType = LINE_8, int shift = 0, Point offset = Point() ); /** @brief Fills the area bounded by one or more polygons. The function fillPoly fills an area bounded by several polygonal contours. The function can fill complex areas, for example, areas with holes, contours with self-intersections (some of their parts), and so forth. @param img Image. @param pts Array of polygons where each polygon is represented as an array of points. @param color Polygon color. @param lineType Type of the polygon boundaries. See the line description. @param shift Number of fractional bits in the vertex coordinates. @param offset Optional offset of all points of the contours. */ CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts, const Scalar& color, int lineType = LINE_8, int shift = 0, Point offset = Point() ); /** @overload */ CV_EXPORTS void polylines(Mat& img, const Point* const* pts, const int* npts, int ncontours, bool isClosed, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0 ); /** @brief Draws several polygonal curves. @param img Image. @param pts Array of polygonal curves. @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, the function draws a line from the last vertex of each curve to its first vertex. @param color Polyline color. @param thickness Thickness of the polyline edges. @param lineType Type of the line segments. See the line description. @param shift Number of fractional bits in the vertex coordinates. The function polylines draws one or more polygonal curves. */ CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts, bool isClosed, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0 ); /** @example contours2.cpp An example using the drawContour functionality */ /** @example segment_objects.cpp An example using drawContours to clean up a background segmentation result */ /** @brief Draws contours outlines or filled contours. The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve connected components from the binary image and label them: : @code #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" using namespace cv; using namespace std; int main( int argc, char** argv ) { Mat src; // the first command-line parameter must be a filename of the binary // (black-n-white) image if( argc != 2 || !(src=imread(argv[1], 0)).data) return -1; Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3); src = src > 1; namedWindow( "Source", 1 ); imshow( "Source", src ); vector > contours; vector hierarchy; findContours( src, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE ); // iterate through all the top-level contours, // draw each connected component with its own random color int idx = 0; for( ; idx >= 0; idx = hierarchy[idx][0] ) { Scalar color( rand()&255, rand()&255, rand()&255 ); drawContours( dst, contours, idx, color, FILLED, 8, hierarchy ); } namedWindow( "Components", 1 ); imshow( "Components", dst ); waitKey(0); } @endcode @param image Destination image. @param contours All the input contours. Each contour is stored as a point vector. @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. @param color Color of the contours. @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), the contour interiors are drawn. @param lineType Line connectivity. See cv::LineTypes. @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only some of the contours (see maxLevel ). @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is hierarchy available. @param offset Optional contour shift parameter. Shift all the drawn contours by the specified \f$\texttt{offset}=(dx,dy)\f$ . */ CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness = 1, int lineType = LINE_8, InputArray hierarchy = noArray(), int maxLevel = INT_MAX, Point offset = Point() ); /** @brief Clips the line against the image rectangle. The functions clipLine calculate a part of the line segment that is entirely within the specified rectangle. They return false if the line segment is completely outside the rectangle. Otherwise, they return true . @param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . @param pt1 First line point. @param pt2 Second line point. */ CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2); /** @overload @param imgRect Image rectangle. @param pt1 First line point. @param pt2 Second line point. */ CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2); /** @brief Approximates an elliptic arc with a polyline. The function ellipse2Poly computes the vertices of a polyline that approximates the specified elliptic arc. It is used by cv::ellipse. @param center Center of the arc. @param axes Half of the size of the ellipse main axes. See the ellipse for details. @param angle Rotation angle of the ellipse in degrees. See the ellipse for details. @param arcStart Starting angle of the elliptic arc in degrees. @param arcEnd Ending angle of the elliptic arc in degrees. @param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy. @param pts Output vector of polyline vertices. */ CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, CV_OUT std::vector& pts ); /** @brief Draws a text string. The function putText renders the specified text string in the image. Symbols that cannot be rendered using the specified font are replaced by question marks. See getTextSize for a text rendering code example. @param img Image. @param text Text string to be drawn. @param org Bottom-left corner of the text string in the image. @param fontFace Font type, see cv::HersheyFonts. @param fontScale Font scale factor that is multiplied by the font-specific base size. @param color Text color. @param thickness Thickness of the lines used to draw a text. @param lineType Line type. See the line for details. @param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner. */ CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org, int fontFace, double fontScale, Scalar color, int thickness = 1, int lineType = LINE_8, bool bottomLeftOrigin = false ); /** @brief Calculates the width and height of a text string. The function getTextSize calculates and returns the size of a box that contains the specified text. That is, the following code renders some text, the tight box surrounding it, and the baseline: : @code String text = "Funny text inside the box"; int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; double fontScale = 2; int thickness = 3; Mat img(600, 800, CV_8UC3, Scalar::all(0)); int baseline=0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; // center the text Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/2); // draw the box rectangle(img, textOrg + Point(0, baseline), textOrg + Point(textSize.width, -textSize.height), Scalar(0,0,255)); // ... and the baseline first line(img, textOrg + Point(0, thickness), textOrg + Point(textSize.width, thickness), Scalar(0, 0, 255)); // then put the text itself putText(img, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8); @endcode @param text Input text string. @param fontFace Font to use, see cv::HersheyFonts. @param fontScale Font scale factor that is multiplied by the font-specific base size. @param thickness Thickness of lines used to render the text. See putText for details. @param[out] baseLine y-coordinate of the baseline relative to the bottom-most text point. @return The size of a box that contains the specified text. @see cv::putText */ CV_EXPORTS_W Size getTextSize(const String& text, int fontFace, double fontScale, int thickness, CV_OUT int* baseLine); /** @brief Line iterator The class is used to iterate over all the pixels on the raster line segment connecting two specified points. The class LineIterator is used to get each pixel of a raster line. It can be treated as versatile implementation of the Bresenham algorithm where you can stop at each pixel and do some extra processing, for example, grab pixel values along the line or draw a line with an effect (for example, with XOR operation). The number of pixels along the line is stored in LineIterator::count. The method LineIterator::pos returns the current position in the image: @code{.cpp} // grabs pixels along the line (pt1, pt2) // from 8-bit 3-channel image to the buffer LineIterator it(img, pt1, pt2, 8); LineIterator it2 = it; vector buf(it.count); for(int i = 0; i < it.count; i++, ++it) buf[i] = *(const Vec3b)*it; // alternative way of iterating through the line for(int i = 0; i < it2.count; i++, ++it2) { Vec3b val = img.at(it2.pos()); CV_Assert(buf[i] == val); } @endcode */ class CV_EXPORTS LineIterator { public: /** @brief intializes the iterator creates iterators for the line connecting pt1 and pt2 the line will be clipped on the image boundaries the line is 8-connected or 4-connected If leftToRight=true, then the iteration is always done from the left-most point to the right most, not to depend on the ordering of pt1 and pt2 parameters */ LineIterator( const Mat& img, Point pt1, Point pt2, int connectivity = 8, bool leftToRight = false ); /** @brief returns pointer to the current pixel */ uchar* operator *(); /** @brief prefix increment operator (++it). shifts iterator to the next pixel */ LineIterator& operator ++(); /** @brief postfix increment operator (it++). shifts iterator to the next pixel */ LineIterator operator ++(int); /** @brief returns coordinates of the current pixel */ Point pos() const; uchar* ptr; const uchar* ptr0; int step, elemSize; int err, count; int minusDelta, plusDelta; int minusStep, plusStep; }; //! @cond IGNORED // === LineIterator implementation === inline uchar* LineIterator::operator *() { return ptr; } inline LineIterator& LineIterator::operator ++() { int mask = err < 0 ? -1 : 0; err += minusDelta + (plusDelta & mask); ptr += minusStep + (plusStep & mask); return *this; } inline LineIterator LineIterator::operator ++(int) { LineIterator it = *this; ++(*this); return it; } inline Point LineIterator::pos() const { Point p; p.y = (int)((ptr - ptr0)/step); p.x = (int)(((ptr - ptr0) - p.y*step)/elemSize); return p; } //! @endcond //! @} imgproc_draw //! @} imgproc } // cv #ifndef DISABLE_OPENCV_24_COMPATIBILITY #include "opencv2/imgproc/imgproc_c.h" #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/line_descriptor/descriptor.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Biagio Montesano, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_DESCRIPTOR_HPP__ #define __OPENCV_DESCRIPTOR_HPP__ #include #include #include #if defined _MSC_VER && _MSC_VER <= 1700 #include #else #include #endif #include #include #include "opencv2/core/utility.hpp" //#include "opencv2/core/private.hpp" #include #include #include #include "opencv2/core.hpp" /* define data types */ typedef uint64_t UINT64; typedef uint32_t UINT32; typedef uint16_t UINT16; typedef uint8_t UINT8; /* define constants */ #define UINT64_1 ((UINT64)0x01) #define UINT32_1 ((UINT32)0x01) namespace cv { namespace line_descriptor { //! @addtogroup line_descriptor //! @{ /** @brief A class to represent a line As aformentioned, it is been necessary to design a class that fully stores the information needed to characterize completely a line and plot it on image it was extracted from, when required. *KeyLine* class has been created for such goal; it is mainly inspired to Feature2d's KeyPoint class, since KeyLine shares some of *KeyPoint*'s fields, even if a part of them assumes a different meaning, when speaking about lines. In particular: - the *class_id* field is used to gather lines extracted from different octaves which refer to same line inside original image (such lines and the one they represent in original image share the same *class_id* value) - the *angle* field represents line's slope with respect to (positive) X axis - the *pt* field represents line's midpoint - the *response* field is computed as the ratio between the line's length and maximum between image's width and height - the *size* field is the area of the smallest rectangle containing line Apart from fields inspired to KeyPoint class, KeyLines stores information about extremes of line in original image and in octave it was extracted from, about line's length and number of pixels it covers. */ struct CV_EXPORTS KeyLine { public: /** orientation of the line */ float angle; /** object ID, that can be used to cluster keylines by the line they represent */ int class_id; /** octave (pyramid layer), from which the keyline has been extracted */ int octave; /** coordinates of the middlepoint */ Point2f pt; /** the response, by which the strongest keylines have been selected. It's represented by the ratio between line's length and maximum between image's width and height */ float response; /** minimum area containing line */ float size; /** lines's extremes in original image */ float startPointX; float startPointY; float endPointX; float endPointY; /** line's extremes in image it was extracted from */ float sPointInOctaveX; float sPointInOctaveY; float ePointInOctaveX; float ePointInOctaveY; /** the length of line */ float lineLength; /** number of pixels covered by the line */ int numOfPixels; /** Returns the start point of the line in the original image */ Point2f getStartPoint() const { return Point2f(startPointX, startPointY); } /** Returns the end point of the line in the original image */ Point2f getEndPoint() const { return Point2f(endPointX, endPointY); } /** Returns the start point of the line in the octave it was extracted from */ Point2f getStartPointInOctave() const { return Point2f(sPointInOctaveX, sPointInOctaveY); } /** Returns the end point of the line in the octave it was extracted from */ Point2f getEndPointInOctave() const { return Point2f(ePointInOctaveX, ePointInOctaveY); } /** constructor */ KeyLine() { } }; /** @brief Class implements both functionalities for detection of lines and computation of their binary descriptor. Class' interface is mainly based on the ones of classical detectors and extractors, such as Feature2d's @ref features2d_main and @ref features2d_match. Retrieved information about lines is stored in line_descriptor::KeyLine objects. */ class CV_EXPORTS BinaryDescriptor : public Algorithm { public: /** @brief List of BinaryDescriptor parameters: */ struct CV_EXPORTS Params { /*CV_WRAP*/ Params(); /** the number of image octaves (default = 1) */ int numOfOctave_; /** the width of band; (default: 7) */ int widthOfBand_; /** image's reduction ratio in construction of Gaussian pyramids */ int reductionRatio; int ksize_; /** read parameters from a FileNode object and store them (struct function) */ void read( const FileNode& fn ); /** store parameters to a FileStorage object (struct function) */ void write( FileStorage& fs ) const; }; /** @brief Constructor @param parameters configuration parameters BinaryDescriptor::Params If no argument is provided, constructor sets default values (see comments in the code snippet in previous section). Default values are strongly reccomended. */ BinaryDescriptor( const BinaryDescriptor::Params ¶meters = BinaryDescriptor::Params() ); /** @brief Create a BinaryDescriptor object with default parameters (or with the ones provided) and return a smart pointer to it */ static Ptr createBinaryDescriptor(); static Ptr createBinaryDescriptor( Params parameters ); /** destructor */ ~BinaryDescriptor(); /** @brief Get current number of octaves */ int getNumOfOctaves();/*CV_WRAP*/ /** @brief Set number of octaves @param octaves number of octaves */ void setNumOfOctaves( int octaves );/*CV_WRAP*/ /** @brief Get current width of bands */ int getWidthOfBand();/*CV_WRAP*/ /** @brief Set width of bands @param width width of bands */ void setWidthOfBand( int width );/*CV_WRAP*/ /** @brief Get current reduction ratio (used in Gaussian pyramids) */ int getReductionRatio();/*CV_WRAP*/ /** @brief Set reduction ratio (used in Gaussian pyramids) @param rRatio reduction ratio */ void setReductionRatio( int rRatio ); /** @brief Read parameters from a FileNode object and store them @param fn source FileNode file */ virtual void read( const cv::FileNode& fn ); /** @brief Store parameters to a FileStorage object @param fs output FileStorage file */ virtual void write( cv::FileStorage& fs ) const; /** @brief Requires line detection @param image input image @param keypoints vector that will store extracted lines for one or more images @param mask mask matrix to detect only KeyLines of interest */ void detect( const Mat& image, CV_OUT std::vector& keypoints, const Mat& mask = Mat() ); /** @overload @param images input images @param keylines set of vectors that will store extracted lines for one or more images @param masks vector of mask matrices to detect only KeyLines of interest from each input image */ void detect( const std::vector& images, std::vector >& keylines, const std::vector& masks = std::vector() ) const; /** @brief Requires descriptors computation @param image input image @param keylines vector containing lines for which descriptors must be computed @param descriptors @param returnFloatDescr flag (when set to true, original non-binary descriptors are returned) */ void compute( const Mat& image, CV_OUT CV_IN_OUT std::vector& keylines, CV_OUT Mat& descriptors, bool returnFloatDescr = false ) const; /** @overload @param images input images @param keylines set of vectors containing lines for which descriptors must be computed @param descriptors @param returnFloatDescr flag (when set to true, original non-binary descriptors are returned) */ void compute( const std::vector& images, std::vector >& keylines, std::vector& descriptors, bool returnFloatDescr = false ) const; /** @brief Return descriptor size */ int descriptorSize() const; /** @brief Return data type */ int descriptorType() const; /** returns norm mode */ /*CV_WRAP*/ int defaultNorm() const; /** @brief Define operator '()' to perform detection of KeyLines and computation of descriptors in a row. @param image input image @param mask mask matrix to select which lines in KeyLines must be accepted among the ones extracted (used when *keylines* is not empty) @param keylines vector that contains input lines (when filled, the detection part will be skipped and input lines will be passed as input to the algorithm computing descriptors) @param descriptors matrix that will store final descriptors @param useProvidedKeyLines flag (when set to true, detection phase will be skipped and only computation of descriptors will be executed, using lines provided in *keylines*) @param returnFloatDescr flag (when set to true, original non-binary descriptors are returned) */ virtual void operator()( InputArray image, InputArray mask, CV_OUT std::vector& keylines, OutputArray descriptors, bool useProvidedKeyLines = false, bool returnFloatDescr = false ) const; protected: /** implementation of line detection */ virtual void detectImpl( const Mat& imageSrc, std::vector& keylines, const Mat& mask = Mat() ) const; /** implementation of descriptors' computation */ virtual void computeImpl( const Mat& imageSrc, std::vector& keylines, Mat& descriptors, bool returnFloatDescr, bool useDetectionData ) const; private: /** struct to represent lines extracted from an octave */ struct OctaveLine { unsigned int octaveCount; //the octave which this line is detected unsigned int lineIDInOctave; //the line ID in that octave image unsigned int lineIDInScaleLineVec; //the line ID in Scale line vector float lineLength; //the length of line in original image scale }; // A 2D line (normal equation parameters). struct SingleLine { //note: rho and theta are based on coordinate origin, i.e. the top-left corner of image double rho; //unit: pixel length double theta; //unit: rad double linePointX; // = rho * cos(theta); double linePointY; // = rho * sin(theta); //for EndPoints, the coordinate origin is the top-left corner of image. double startPointX; double startPointY; double endPointX; double endPointY; //direction of a line, the angle between positive line direction (dark side is in the left) and positive X axis. double direction; //mean gradient magnitude double gradientMagnitude; //mean gray value of pixels in dark side of line double darkSideGrayValue; //mean gray value of pixels in light side of line double lightSideGrayValue; //the length of line double lineLength; //the width of line; double width; //number of pixels int numOfPixels; //the decriptor of line std::vector descriptor; }; // Specifies a vector of lines. typedef std::vector Lines_list; struct OctaveSingleLine { /*endPoints, the coordinate origin is the top-left corner of the original image. *startPointX = sPointInOctaveX * (factor)^octaveCount; */ float startPointX; float startPointY; float endPointX; float endPointY; //endPoints, the coordinate origin is the top-left corner of the octave image. float sPointInOctaveX; float sPointInOctaveY; float ePointInOctaveX; float ePointInOctaveY; //direction of a line, the angle between positive line direction (dark side is in the left) and positive X axis. float direction; //the summation of gradient magnitudes of pixels on lines float salience; //the length of line float lineLength; //number of pixels unsigned int numOfPixels; //the octave which this line is detected unsigned int octaveCount; //the decriptor of line std::vector descriptor; }; struct Pixel { unsigned int x; //X coordinate unsigned int y; //Y coordinate }; struct EdgeChains { std::vector xCors; //all the x coordinates of edge points std::vector yCors; //all the y coordinates of edge points std::vector sId; //the start index of each edge in the coordinate arrays unsigned int numOfEdges; //the number of edges whose length are larger than minLineLen; numOfEdges < sId.size; }; struct LineChains { std::vector xCors; //all the x coordinates of line points std::vector yCors; //all the y coordinates of line points std::vector sId; //the start index of each line in the coordinate arrays unsigned int numOfLines; //the number of lines whose length are larger than minLineLen; numOfLines < sId.size; }; typedef std::list PixelChain; //each edge is a pixel chain struct EDLineParam { int ksize; float sigma; float gradientThreshold; float anchorThreshold; int scanIntervals; int minLineLen; double lineFitErrThreshold; }; #define RELATIVE_ERROR_FACTOR 100.0 #define MLN10 2.30258509299404568402 #define log_gamma(x) ((x)>15.0?log_gamma_windschitl(x):log_gamma_lanczos(x)) /** This class is used to detect lines from input image. * First, edges are extracted from input image following the method presented in Cihan Topal and * Cuneyt Akinlar's paper:"Edge Drawing: A Heuristic Approach to Robust Real-Time Edge Detection", 2010. * Then, lines are extracted from the edge image following the method presented in Cuneyt Akinlar and * Cihan Topal's paper:"EDLines: A real-time line segment detector with a false detection control", 2011 * PS: The linking step of edge detection has a little bit difference with the Edge drawing algorithm * described in the paper. The edge chain doesn't stop when the pixel direction is changed. */ class EDLineDetector { public: EDLineDetector(); EDLineDetector( EDLineParam param ); ~EDLineDetector(); /*extract edges from image *image: In, gray image; *edges: Out, store the edges, each edge is a pixel chain *return -1: error happen */ int EdgeDrawing( cv::Mat &image, EdgeChains &edgeChains ); /*extract lines from image *image: In, gray image; *lines: Out, store the extracted lines, *return -1: error happen */ int EDline( cv::Mat &image, LineChains &lines ); /** extract line from image, and store them */ int EDline( cv::Mat &image ); cv::Mat dxImg_; //store the dxImg; cv::Mat dyImg_; //store the dyImg; cv::Mat gImgWO_; //store the gradient image without threshold; LineChains lines_; //store the detected line chains; //store the line Equation coefficients, vec3=[w1,w2,w3] for line w1*x + w2*y + w3=0; std::vector > lineEquations_; //store the line endpoints, [x1,y1,x2,y3] std::vector > lineEndpoints_; //store the line direction std::vector lineDirection_; //store the line salience, which is the summation of gradients of pixels on line std::vector lineSalience_; // image sizes unsigned int imageWidth; unsigned int imageHeight; /*The threshold of line fit error; *If lineFitErr is large than this threshold, then *the pixel chain is not accepted as a single line segment.*/ double lineFitErrThreshold_; /*the threshold of pixel gradient magnitude. *Only those pixel whose gradient magnitude are larger than this threshold will be *taken as possible edge points. Default value is 36*/ short gradienThreshold_; /*If the pixel's gradient value is bigger than both of its neighbors by a *certain threshold (ANCHOR_THRESHOLD), the pixel is marked to be an anchor. *Default value is 8*/ unsigned char anchorThreshold_; /*anchor testing can be performed at different scan intervals, i.e., *every row/column, every second row/column etc. *Default value is 2*/ unsigned int scanIntervals_; int minLineLen_; //minimal acceptable line length private: void InitEDLine_(); /*For an input edge chain, find the best fit line, the default chain length is minLineLen_ *xCors: In, pointer to the X coordinates of pixel chain; *yCors: In, pointer to the Y coordinates of pixel chain; *offsetS:In, start index of this chain in vector; *lineEquation: Out, [a,b] which are the coefficient of lines y=ax+b(horizontal) or x=ay+b(vertical); *return: line fit error; -1:error happens; */ double LeastSquaresLineFit_( unsigned int *xCors, unsigned int *yCors, unsigned int offsetS, std::vector &lineEquation ); /*For an input pixel chain, find the best fit line. Only do the update based on new points. *For A*x=v, Least square estimation of x = Inv(A^T * A) * (A^T * v); *If some new observations are added, i.e, [A; A'] * x = [v; v'], *then x' = Inv(A^T * A + (A')^T * A') * (A^T * v + (A')^T * v'); *xCors: In, pointer to the X coordinates of pixel chain; *yCors: In, pointer to the Y coordinates of pixel chain; *offsetS:In, start index of this chain in vector; *newOffsetS: In, start index of extended part; *offsetE:In, end index of this chain in vector; *lineEquation: Out, [a,b] which are the coefficient of lines y=ax+b(horizontal) or x=ay+b(vertical); *return: line fit error; -1:error happens; */ double LeastSquaresLineFit_( unsigned int *xCors, unsigned int *yCors, unsigned int offsetS, unsigned int newOffsetS, unsigned int offsetE, std::vector &lineEquation ); /** Validate line based on the Helmholtz principle, which basically states that * for a structure to be perceptually meaningful, the expectation of this structure * by chance must be very low. */ bool LineValidation_( unsigned int *xCors, unsigned int *yCors, unsigned int offsetS, unsigned int offsetE, std::vector &lineEquation, float &direction ); bool bValidate_; //flag to decide whether line will be validated int ksize_; //the size of Gaussian kernel: ksize X ksize, default value is 5. float sigma_; //the sigma of Gaussian kernal, default value is 1.0. /*For example, there two edges in the image: *edge1 = [(7,4), (8,5), (9,6),| (10,7)|, (11, 8), (12,9)] and *edge2 = [(14,9), (15,10), (16,11), (17,12),| (18, 13)|, (19,14)] ; then we store them as following: *pFirstPartEdgeX_ = [10, 11, 12, 18, 19];//store the first part of each edge[from middle to end] *pFirstPartEdgeY_ = [7, 8, 9, 13, 14]; *pFirstPartEdgeS_ = [0,3,5];// the index of start point of first part of each edge *pSecondPartEdgeX_ = [10, 9, 8, 7, 18, 17, 16, 15, 14];//store the second part of each edge[from middle to front] *pSecondPartEdgeY_ = [7, 6, 5, 4, 13, 12, 11, 10, 9];//anchor points(10, 7) and (18, 13) are stored again *pSecondPartEdgeS_ = [0, 4, 9];// the index of start point of second part of each edge *This type of storage order is because of the order of edge detection process. *For each edge, start from one anchor point, first go right, then go left or first go down, then go up*/ //store the X coordinates of the first part of the pixels for chains unsigned int *pFirstPartEdgeX_; //store the Y coordinates of the first part of the pixels for chains unsigned int *pFirstPartEdgeY_; //store the start index of every edge chain in the first part arrays unsigned int *pFirstPartEdgeS_; //store the X coordinates of the second part of the pixels for chains unsigned int *pSecondPartEdgeX_; //store the Y coordinates of the second part of the pixels for chains unsigned int *pSecondPartEdgeY_; //store the start index of every edge chain in the second part arrays unsigned int *pSecondPartEdgeS_; //store the X coordinates of anchors unsigned int *pAnchorX_; //store the Y coordinates of anchors unsigned int *pAnchorY_; //edges cv::Mat edgeImage_; cv::Mat gImg_; //store the gradient image; cv::Mat dirImg_; //store the direction image double logNT_; cv::Mat_ ATA; //the previous matrix of A^T * A; cv::Mat_ ATV; //the previous vector of A^T * V; cv::Mat_ fitMatT; //the matrix used in line fit function; cv::Mat_ fitVec; //the vector used in line fit function; cv::Mat_ tempMatLineFit; //the matrix used in line fit function; cv::Mat_ tempVecLineFit; //the vector used in line fit function; /** Compare doubles by relative error. The resulting rounding error after floating point computations depend on the specific operations done. The same number computed by different algorithms could present different rounding errors. For a useful comparison, an estimation of the relative rounding error should be considered and compared to a factor times EPS. The factor should be related to the accumulated rounding error in the chain of computation. Here, as a simplification, a fixed factor is used. */ static int double_equal( double a, double b ) { double abs_diff, aa, bb, abs_max; /* trivial case */ if( a == b ) return true; abs_diff = fabs( a - b ); aa = fabs( a ); bb = fabs( b ); abs_max = aa > bb ? aa : bb; /* DBL_MIN is the smallest normalized number, thus, the smallest number whose relative error is bounded by DBL_EPSILON. For smaller numbers, the same quantization steps as for DBL_MIN are used. Then, for smaller numbers, a meaningful "relative" error should be computed by dividing the difference by DBL_MIN. */ if( abs_max < DBL_MIN ) abs_max = DBL_MIN; /* equal if relative error <= factor x eps */ return ( abs_diff / abs_max ) <= ( RELATIVE_ERROR_FACTOR * DBL_EPSILON ); } /** Computes the natural logarithm of the absolute value of the gamma function of x using the Lanczos approximation. See http://www.rskey.org/gamma.htm The formula used is @f[ \Gamma(x) = \frac{ \sum_{n=0}^{N} q_n x^n }{ \Pi_{n=0}^{N} (x+n) } (x+5.5)^{x+0.5} e^{-(x+5.5)} @f] so @f[ \log\Gamma(x) = \log\left( \sum_{n=0}^{N} q_n x^n \right) + (x+0.5) \log(x+5.5) - (x+5.5) - \sum_{n=0}^{N} \log(x+n) @f] and q0 = 75122.6331530, q1 = 80916.6278952, q2 = 36308.2951477, q3 = 8687.24529705, q4 = 1168.92649479, q5 = 83.8676043424, q6 = 2.50662827511. */ static double log_gamma_lanczos( double x ) { static double q[7] = { 75122.6331530, 80916.6278952, 36308.2951477, 8687.24529705, 1168.92649479, 83.8676043424, 2.50662827511 }; double a = ( x + 0.5 ) * log( x + 5.5 ) - ( x + 5.5 ); double b = 0.0; int n; for ( n = 0; n < 7; n++ ) { a -= log( x + (double) n ); b += q[n] * pow( x, (double) n ); } return a + log( b ); } /** Computes the natural logarithm of the absolute value of the gamma function of x using Windschitl method. See http://www.rskey.org/gamma.htm The formula used is @f[ \Gamma(x) = \sqrt{\frac{2\pi}{x}} \left( \frac{x}{e} \sqrt{ x\sinh(1/x) + \frac{1}{810x^6} } \right)^x @f] so @f[ \log\Gamma(x) = 0.5\log(2\pi) + (x-0.5)\log(x) - x + 0.5x\log\left( x\sinh(1/x) + \frac{1}{810x^6} \right). @f] This formula is a good approximation when x > 15. */ static double log_gamma_windschitl( double x ) { return 0.918938533204673 + ( x - 0.5 ) * log( x ) - x + 0.5 * x * log( x * sinh( 1 / x ) + 1 / ( 810.0 * pow( x, 6.0 ) ) ); } /** Computes -log10(NFA). NFA stands for Number of False Alarms: @f[ \mathrm{NFA} = NT \cdot B(n,k,p) @f] - NT - number of tests - B(n,k,p) - tail of binomial distribution with parameters n,k and p: @f[ B(n,k,p) = \sum_{j=k}^n \left(\begin{array}{c}n\\j\end{array}\right) p^{j} (1-p)^{n-j} @f] The value -log10(NFA) is equivalent but more intuitive than NFA: - -1 corresponds to 10 mean false alarms - 0 corresponds to 1 mean false alarm - 1 corresponds to 0.1 mean false alarms - 2 corresponds to 0.01 mean false alarms - ... Used this way, the bigger the value, better the detection, and a logarithmic scale is used. @param n,k,p binomial parameters. @param logNT logarithm of Number of Tests The computation is based in the gamma function by the following relation: @f[ \left(\begin{array}{c}n\\k\end{array}\right) = \frac{ \Gamma(n+1) }{ \Gamma(k+1) \cdot \Gamma(n-k+1) }. @f] We use efficient algorithms to compute the logarithm of the gamma function. To make the computation faster, not all the sum is computed, part of the terms are neglected based on a bound to the error obtained (an error of 10% in the result is accepted). */ static double nfa( int n, int k, double p, double logNT ) { double tolerance = 0.1; /* an error of 10% in the result is accepted */ double log1term, term, bin_term, mult_term, bin_tail, err, p_term; int i; /* check parameters */ if( n < 0 || k < 0 || k > n || p <= 0.0 || p >= 1.0 ) { std::cout << "nfa: wrong n, k or p values." << std::endl; exit( 0 ); } /* trivial cases */ if( n == 0 || k == 0 ) return -logNT; if( n == k ) return -logNT - (double) n * log10( p ); /* probability term */ p_term = p / ( 1.0 - p ); /* compute the first term of the series */ /* binomial_tail(n,k,p) = sum_{i=k}^n bincoef(n,i) * p^i * (1-p)^{n-i} where bincoef(n,i) are the binomial coefficients. But bincoef(n,k) = gamma(n+1) / ( gamma(k+1) * gamma(n-k+1) ). We use this to compute the first term. Actually the log of it. */ log1term = log_gamma( (double) n + 1.0 )- log_gamma( (double ) k + 1.0 )- log_gamma( (double ) ( n - k ) + 1.0 ) + (double) k * log( p ) + (double) ( n - k ) * log( 1.0 - p ); term = exp( log1term ); /* in some cases no more computations are needed */ if( double_equal( term, 0.0 ) ) { /* the first term is almost zero */ if( (double) k > (double) n * p ) /* at begin or end of the tail? */ return -log1term / MLN10 - logNT; /* end: use just the first term */ else return -logNT; /* begin: the tail is roughly 1 */ } /* compute more terms if needed */ bin_tail = term; for ( i = k + 1; i <= n; i++ ) { /* As term_i = bincoef(n,i) * p^i * (1-p)^(n-i) and bincoef(n,i)/bincoef(n,i-1) = n-i+1 / i, then, term_i / term_i-1 = (n-i+1)/i * p/(1-p) and term_i = term_i-1 * (n-i+1)/i * p/(1-p). p/(1-p) is computed only once and stored in 'p_term'. */ bin_term = (double) ( n - i + 1 ) / (double) i; mult_term = bin_term * p_term; term *= mult_term; bin_tail += term; if( bin_term < 1.0 ) { /* When bin_term<1 then mult_term_ji. Then, the error on the binomial tail when truncated at the i term can be bounded by a geometric series of form term_i * sum mult_term_i^j. */ err = term * ( ( 1.0 - pow( mult_term, (double) ( n - i + 1 ) ) ) / ( 1.0 - mult_term ) - 1.0 ); /* One wants an error at most of tolerance*final_result, or: tolerance * abs(-log10(bin_tail)-logNT). Now, the error that can be accepted on bin_tail is given by tolerance*final_result divided by the derivative of -log10(x) when x=bin_tail. that is: tolerance * abs(-log10(bin_tail)-logNT) / (1/bin_tail) Finally, we truncate the tail if the error is less than: tolerance * abs(-log10(bin_tail)-logNT) * bin_tail */ if( err < tolerance * fabs( -log10( bin_tail ) - logNT ) * bin_tail ) break; } } return -log10( bin_tail ) - logNT; } }; // Specifies a vector of lines. typedef std::vector LinesVec; // each element in ScaleLines is a vector of lines // which corresponds the same line detected in different octave images. typedef std::vector ScaleLines; /* compute Gaussian pyramids */ void computeGaussianPyramid( const Mat& image, const int numOctaves ); /* compute Sobel's derivatives */ void computeSobel( const Mat& image, const int numOctaves ); /* conversion of an LBD descriptor to its binary representation */ unsigned char binaryConversion( float* f1, float* f2 ); /* compute LBD descriptors using EDLine extractor */ int computeLBD( ScaleLines &keyLines, bool useDetectionData = false ); /* gathers lines in groups using EDLine extractor. Each group contains the same line, detected in different octaves */ int OctaveKeyLines( cv::Mat& image, ScaleLines &keyLines ); /* the local gaussian coefficient applied to the orthogonal line direction within each band */ std::vector gaussCoefL_; /* the global gaussian coefficient applied to each row within line support region */ std::vector gaussCoefG_; /* descriptor parameters */ Params params; /* vector of sizes of downsampled and blurred images */ std::vector images_sizes; /*For each octave of image, we define an EDLineDetector, because we can get gradient images (dxImg, dyImg, gImg) *from the EDLineDetector class without extra computation cost. Another reason is that, if we use *a single EDLineDetector to detect lines in different octave of images, then we need to allocate and release *memory for gradient images (dxImg, dyImg, gImg) repeatedly for their varying size*/ std::vector > edLineVec_; /* Sobel's derivatives */ std::vector dxImg_vector, dyImg_vector; /* Gaussian pyramid */ std::vector octaveImages; }; /** Lines extraction methodology ---------------------------- The lines extraction methodology described in the following is mainly based on @cite EDL . The extraction starts with a Gaussian pyramid generated from an original image, downsampled N-1 times, blurred N times, to obtain N layers (one for each octave), with layer 0 corresponding to input image. Then, from each layer (octave) in the pyramid, lines are extracted using LSD algorithm. Differently from EDLine lines extractor used in original article, LSD furnishes information only about lines extremes; thus, additional information regarding slope and equation of line are computed via analytic methods. The number of pixels is obtained using *LineIterator*. Extracted lines are returned in the form of KeyLine objects, but since extraction is based on a method different from the one used in *BinaryDescriptor* class, data associated to a line's extremes in original image and in octave it was extracted from, coincide. KeyLine's field *class_id* is used as an index to indicate the order of extraction of a line inside a single octave. */ class CV_EXPORTS LSDDetector : public Algorithm { public: /* constructor */ /*CV_WRAP*/ LSDDetector() { } ; /** @brief Creates ad LSDDetector object, using smart pointers. */ static Ptr createLSDDetector(); /** @brief Detect lines inside an image. @param image input image @param keypoints vector that will store extracted lines for one or more images @param scale scale factor used in pyramids generation @param numOctaves number of octaves inside pyramid @param mask mask matrix to detect only KeyLines of interest */ void detect( const Mat& image, CV_OUT std::vector& keypoints, int scale, int numOctaves, const Mat& mask = Mat() ); /** @overload @param images input images @param keylines set of vectors that will store extracted lines for one or more images @param scale scale factor used in pyramids generation @param numOctaves number of octaves inside pyramid @param masks vector of mask matrices to detect only KeyLines of interest from each input image */ void detect( const std::vector& images, std::vector >& keylines, int scale, int numOctaves, const std::vector& masks = std::vector() ) const; private: /* compute Gaussian pyramid of input image */ void computeGaussianPyramid( const Mat& image, int numOctaves, int scale ); /* implementation of line detection */ void detectImpl( const Mat& imageSrc, std::vector& keylines, int numOctaves, int scale, const Mat& mask ) const; /* matrices for Gaussian pyramids */ std::vector gaussianPyrs; }; /** @brief furnishes all functionalities for querying a dataset provided by user or internal to class (that user must, anyway, populate) on the model of @ref features2d_match Once descriptors have been extracted from an image (both they represent lines and points), it becomes interesting to be able to match a descriptor with another one extracted from a different image and representing the same line or point, seen from a differente perspective or on a different scale. In reaching such goal, the main headache is designing an efficient search algorithm to associate a query descriptor to one extracted from a dataset. In the following, a matching modality based on *Multi-Index Hashing (MiHashing)* will be described. Multi-Index Hashing ------------------- The theory described in this section is based on @cite MIH . Given a dataset populated with binary codes, each code is indexed *m* times into *m* different hash tables, according to *m* substrings it has been divided into. Thus, given a query code, all the entries close to it at least in one substring are returned by search as *neighbor candidates*. Returned entries are then checked for validity by verifying that their full codes are not distant (in Hamming space) more than *r* bits from query code. In details, each binary code **h** composed of *b* bits is divided into *m* disjoint substrings \f$\mathbf{h}^{(1)}, ..., \mathbf{h}^{(m)}\f$, each with length \f$\lfloor b/m \rfloor\f$ or \f$\lceil b/m \rceil\f$ bits. Formally, when two codes **h** and **g** differ by at the most *r* bits, in at the least one of their *m* substrings they differ by at the most \f$\lfloor r/m \rfloor\f$ bits. In particular, when \f$||\mathbf{h}-\mathbf{g}||_H \le r\f$ (where \f$||.||_H\f$ is the Hamming norm), there must exist a substring *k* (with \f$1 \le k \le m\f$) such that \f[||\mathbf{h}^{(k)} - \mathbf{g}^{(k)}||_H \le \left\lfloor \frac{r}{m} \right\rfloor .\f] That means that if Hamming distance between each of the *m* substring is strictly greater than \f$\lfloor r/m \rfloor\f$, then \f$||\mathbf{h}-\mathbf{g}||_H\f$ must be larger that *r* and that is a contradiction. If the codes in dataset are divided into *m* substrings, then *m* tables will be built. Given a query **q** with substrings \f$\{\mathbf{q}^{(i)}\}^m_{i=1}\f$, *i*-th hash table is searched for entries distant at the most \f$\lfloor r/m \rfloor\f$ from \f$\mathbf{q}^{(i)}\f$ and a set of candidates \f$\mathcal{N}_i(\mathbf{q})\f$ is obtained. The union of sets \f$\mathcal{N}(\mathbf{q}) = \bigcup_i \mathcal{N}_i(\mathbf{q})\f$ is a superset of the *r*-neighbors of **q**. Then, last step of algorithm is computing the Hamming distance between **q** and each element in \f$\mathcal{N}(\mathbf{q})\f$, deleting the codes that are distant more that *r* from **q**. */ class CV_EXPORTS BinaryDescriptorMatcher : public Algorithm { public: /** @brief For every input query descriptor, retrieve the best matching one from a dataset provided from user or from the one internal to class @param queryDescriptors query descriptors @param trainDescriptors dataset of descriptors furnished by user @param matches vector to host retrieved matches @param mask mask to select which input descriptors must be matched to one in dataset */ void match( const Mat& queryDescriptors, const Mat& trainDescriptors, std::vector& matches, const Mat& mask = Mat() ) const; /** @overload @param queryDescriptors query descriptors @param matches vector to host retrieved matches @param masks vector of masks to select which input descriptors must be matched to one in dataset (the *i*-th mask in vector indicates whether each input query can be matched with descriptors in dataset relative to *i*-th image) */ void match( const Mat& queryDescriptors, std::vector& matches, const std::vector& masks = std::vector() ); /** @brief For every input query descriptor, retrieve the best *k* matching ones from a dataset provided from user or from the one internal to class @param queryDescriptors query descriptors @param trainDescriptors dataset of descriptors furnished by user @param matches vector to host retrieved matches @param k number of the closest descriptors to be returned for every input query @param mask mask to select which input descriptors must be matched to ones in dataset @param compactResult flag to obtain a compact result (if true, a vector that doesn't contain any matches for a given query is not inserted in final result) */ void knnMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, std::vector >& matches, int k, const Mat& mask = Mat(), bool compactResult = false ) const; /** @overload @param queryDescriptors query descriptors @param matches vector to host retrieved matches @param k number of the closest descriptors to be returned for every input query @param masks vector of masks to select which input descriptors must be matched to ones in dataset (the *i*-th mask in vector indicates whether each input query can be matched with descriptors in dataset relative to *i*-th image) @param compactResult flag to obtain a compact result (if true, a vector that doesn't contain any matches for a given query is not inserted in final result) */ void knnMatch( const Mat& queryDescriptors, std::vector >& matches, int k, const std::vector& masks = std::vector(), bool compactResult = false ); /** @brief For every input query descriptor, retrieve, from a dataset provided from user or from the one internal to class, all the descriptors that are not further than *maxDist* from input query @param queryDescriptors query descriptors @param trainDescriptors dataset of descriptors furnished by user @param matches vector to host retrieved matches @param maxDistance search radius @param mask mask to select which input descriptors must be matched to ones in dataset @param compactResult flag to obtain a compact result (if true, a vector that doesn't contain any matches for a given query is not inserted in final result) */ void radiusMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, std::vector >& matches, float maxDistance, const Mat& mask = Mat(), bool compactResult = false ) const; /** @overload @param queryDescriptors query descriptors @param matches vector to host retrieved matches @param maxDistance search radius @param masks vector of masks to select which input descriptors must be matched to ones in dataset (the *i*-th mask in vector indicates whether each input query can be matched with descriptors in dataset relative to *i*-th image) @param compactResult flag to obtain a compact result (if true, a vector that doesn't contain any matches for a given query is not inserted in final result) */ void radiusMatch( const Mat& queryDescriptors, std::vector >& matches, float maxDistance, const std::vector& masks = std::vector(), bool compactResult = false ); /** @brief Store locally new descriptors to be inserted in dataset, without updating dataset. @param descriptors matrices containing descriptors to be inserted into dataset @note Each matrix *i* in **descriptors** should contain descriptors relative to lines extracted from *i*-th image. */ void add( const std::vector& descriptors ); /** @brief Update dataset by inserting into it all descriptors that were stored locally by *add* function. @note Every time this function is invoked, current dataset is deleted and locally stored descriptors are inserted into dataset. The locally stored copy of just inserted descriptors is then removed. */ void train(); /** @brief Create a BinaryDescriptorMatcher object and return a smart pointer to it. */ static Ptr createBinaryDescriptorMatcher(); /** @brief Clear dataset and internal data */ void clear(); /** @brief Constructor. The BinaryDescriptorMatcher constructed is able to store and manage 256-bits long entries. */ BinaryDescriptorMatcher(); /** destructor */ ~BinaryDescriptorMatcher() { } private: class BucketGroup { public: /** constructor */ BucketGroup(); /** destructor */ ~BucketGroup(); /** insert data into the bucket */ void insert( int subindex, UINT32 data ); /** perform a query to the bucket */ UINT32* query( int subindex, int *size ); /** utility functions */ void insert_value( std::vector& vec, int index, UINT32 data ); void push_value( std::vector& vec, UINT32 Data ); /** data fields */ UINT32 empty; std::vector group; }; class SparseHashtable { private: /** Maximum bits per key before folding the table */ static const int MAX_B; /** Bins (each bin is an Array object for duplicates of the same key) */ BucketGroup *table; public: /** constructor */ SparseHashtable(); /** destructor */ ~SparseHashtable(); /** initializer */ int init( int _b ); /** insert data */ void insert( UINT64 index, UINT32 data ); /** query data */ UINT32* query( UINT64 index, int* size ); /** Bits per index */ int b; /** Number of bins */ UINT64 size; }; /** class defining a sequence of bits */ class bitarray { public: /** pointer to bits sequence and sequence's length */ UINT32 *arr; UINT32 length; /** constructor setting default values */ bitarray() { arr = NULL; length = 0; } /** constructor setting sequence's length */ bitarray( UINT64 _bits ) { init( _bits ); } /** initializer of private fields */ void init( UINT64 _bits ) { length = (UINT32) ceil( _bits / 32.00 ); arr = new UINT32[length]; erase(); } /** destructor */ ~bitarray() { if( arr ) delete[] arr; } inline void flip( UINT64 index ) { arr[index >> 5] ^= ( (UINT32) 0x01 ) << ( index % 32 ); } inline void set( UINT64 index ) { arr[index >> 5] |= ( (UINT32) 0x01 ) << ( index % 32 ); } inline UINT8 get( UINT64 index ) { return ( arr[index >> 5] & ( ( (UINT32) 0x01 ) << ( index % 32 ) ) ) != 0; } /** reserve menory for an UINT32 */ inline void erase() { memset( arr, 0, sizeof(UINT32) * length ); } }; class Mihasher { public: /** Bits per code */ int B; /** B/8 */ int B_over_8; /** Bits per chunk (must be less than 64) */ int b; /** Number of chunks */ int m; /** Number of chunks with b bits (have 1 bit more than others) */ int mplus; /** Maximum hamming search radius (we use B/2 by default) */ int D; /** Maximum hamming search radius per substring */ int d; /** Maximum results to return */ int K; /** Number of codes */ UINT64 N; /** Table of original full-length codes */ cv::Mat codes; /** Counter for eliminating duplicate results (it is not thread safe) */ bitarray *counter; /** Array of m hashtables */ SparseHashtable *H; /** Volume of a b-bit Hamming ball with radius s (for s = 0 to d) */ UINT32 *xornum; /** Used within generation of binary codes at a certain Hamming distance */ int power[100]; /** constructor */ Mihasher(); /** desctructor */ ~Mihasher(); /** constructor 2 */ Mihasher( int B, int m ); /** K setter */ void setK( int K ); /** populate tables */ void populate( cv::Mat & codes, UINT32 N, int dim1codes ); /** execute a batch query */ void batchquery( UINT32 * results, UINT32 *numres/*, qstat *stats*/, const cv::Mat & q, UINT32 numq, int dim1queries ); private: /** execute a single query */ void query( UINT32 * results, UINT32* numres/*, qstat *stats*/, UINT8 *q, UINT64 * chunks, UINT32 * res ); }; /** retrieve Hamming distances */ void checkKDistances( UINT32 * numres, int k, std::vector& k_distances, int row, int string_length ) const; /** matrix to store new descriptors */ Mat descriptorsMat; /** map storing where each bunch of descriptors benins in DS */ std::map indexesMap; /** internal MiHaser representing dataset */ Mihasher* dataset; /** index from which next added descriptors' bunch must begin */ int nextAddedIndex; /** number of images whose descriptors are stored in DS */ int numImages; /** number of descriptors in dataset */ int descrInDS; }; /* -------------------------------------------------------------------------------------------- UTILITY FUNCTIONS -------------------------------------------------------------------------------------------- */ /** struct for drawing options */ struct CV_EXPORTS DrawLinesMatchesFlags { enum { DEFAULT = 0, //!< Output image matrix will be created (Mat::create), //!< i.e. existing memory of output image may be reused. //!< Two source images, matches, and single keylines //!< will be drawn. DRAW_OVER_OUTIMG = 1,//!< Output image matrix will not be //!< created (using Mat::create). Matches will be drawn //!< on existing content of output image. NOT_DRAW_SINGLE_LINES = 2//!< Single keylines will not be drawn. }; }; /** @brief Draws the found matches of keylines from two images. @param img1 first image @param keylines1 keylines extracted from first image @param img2 second image @param keylines2 keylines extracted from second image @param matches1to2 vector of matches @param outImg output matrix to draw on @param matchColor drawing color for matches (chosen randomly in case of default value) @param singleLineColor drawing color for keylines (chosen randomly in case of default value) @param matchesMask mask to indicate which matches must be drawn @param flags drawing flags, see DrawLinesMatchesFlags @note If both *matchColor* and *singleLineColor* are set to their default values, function draws matched lines and line connecting them with same color */ CV_EXPORTS void drawLineMatches( const Mat& img1, const std::vector& keylines1, const Mat& img2, const std::vector& keylines2, const std::vector& matches1to2, Mat& outImg, const Scalar& matchColor = Scalar::all( -1 ), const Scalar& singleLineColor = Scalar::all( -1 ), const std::vector& matchesMask = std::vector(), int flags = DrawLinesMatchesFlags::DEFAULT ); /** @brief Draws keylines. @param image input image @param keylines keylines to be drawn @param outImage output image to draw on @param color color of lines to be drawn (if set to defaul value, color is chosen randomly) @param flags drawing flags */ CV_EXPORTS void drawKeylines( const Mat& image, const std::vector& keylines, Mat& outImage, const Scalar& color = Scalar::all( -1 ), int flags = DrawLinesMatchesFlags::DEFAULT ); //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/line_descriptor.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_LINE_DESCRIPTOR_HPP__ #define __OPENCV_LINE_DESCRIPTOR_HPP__ #include "opencv2/line_descriptor/descriptor.hpp" /** @defgroup line_descriptor Binary descriptors for lines extracted from an image Introduction ------------ One of the most challenging activities in computer vision is the extraction of useful information from a given image. Such information, usually comes in the form of points that preserve some kind of property (for instance, they are scale-invariant) and are actually representative of input image. The goal of this module is seeking a new kind of representative information inside an image and providing the functionalities for its extraction and representation. In particular, differently from previous methods for detection of relevant elements inside an image, lines are extracted in place of points; a new class is defined ad hoc to summarize a line's properties, for reuse and plotting purposes. Computation of binary descriptors --------------------------------- To obtatin a binary descriptor representing a certain line detected from a certain octave of an image, we first compute a non-binary descriptor as described in @cite LBD . Such algorithm works on lines extracted using EDLine detector, as explained in @cite EDL . Given a line, we consider a rectangular region centered at it and called *line support region (LSR)*. Such region is divided into a set of bands \f$\{B_1, B_2, ..., B_m\}\f$, whose length equals the one of line. If we indicate with \f$\bf{d}_L\f$ the direction of line, the orthogonal and clockwise direction to line \f$\bf{d}_{\perp}\f$ can be determined; these two directions, are used to construct a reference frame centered in the middle point of line. The gradients of pixels \f$\bf{g'}\f$ inside LSR can be projected to the newly determined frame, obtaining their local equivalent \f$\bf{g'} = (\bf{g}^T \cdot \bf{d}_{\perp}, \bf{g}^T \cdot \bf{d}_L)^T \triangleq (\bf{g'}_{d_{\perp}}, \bf{g'}_{d_L})^T\f$. Later on, a Gaussian function is applied to all LSR's pixels along \f$\bf{d}_\perp\f$ direction; first, we assign a global weighting coefficient \f$f_g(i) = (1/\sqrt{2\pi}\sigma_g)e^{-d^2_i/2\sigma^2_g}\f$ to *i*-th row in LSR, where \f$d_i\f$ is the distance of *i*-th row from the center row in LSR, \f$\sigma_g = 0.5(m \cdot w - 1)\f$ and \f$w\f$ is the width of bands (the same for every band). Secondly, considering a band \f$B_j\f$ and its neighbor bands \f$B_{j-1}, B_{j+1}\f$, we assign a local weighting \f$F_l(k) = (1/\sqrt{2\pi}\sigma_l)e^{-d'^2_k/2\sigma_l^2}\f$, where \f$d'_k\f$ is the distance of *k*-th row from the center row in \f$B_j\f$ and \f$\sigma_l = w\f$. Using the global and local weights, we obtain, at the same time, the reduction of role played by gradients far from line and of boundary effect, respectively. Each band \f$B_j\f$ in LSR has an associated *band descriptor(BD)* which is computed considering previous and next band (top and bottom bands are ignored when computing descriptor for first and last band). Once each band has been assignen its BD, the LBD descriptor of line is simply given by \f[LBD = (BD_1^T, BD_2^T, ... , BD^T_m)^T.\f] To compute a band descriptor \f$B_j\f$, each *k*-th row in it is considered and the gradients in such row are accumulated: \f[\begin{matrix} \bf{V1}^k_j = \lambda \sum\limits_{\bf{g}'_{d_\perp}>0}\bf{g}'_{d_\perp}, & \bf{V2}^k_j = \lambda \sum\limits_{\bf{g}'_{d_\perp}<0} -\bf{g}'_{d_\perp}, \\ \bf{V3}^k_j = \lambda \sum\limits_{\bf{g}'_{d_L}>0}\bf{g}'_{d_L}, & \bf{V4}^k_j = \lambda \sum\limits_{\bf{g}'_{d_L}<0} -\bf{g}'_{d_L}\end{matrix}.\f] with \f$\lambda = f_g(k)f_l(k)\f$. By stacking previous results, we obtain the *band description matrix (BDM)* \f[BDM_j = \left(\begin{matrix} \bf{V1}_j^1 & \bf{V1}_j^2 & \ldots & \bf{V1}_j^n \\ \bf{V2}_j^1 & \bf{V2}_j^2 & \ldots & \bf{V2}_j^n \\ \bf{V3}_j^1 & \bf{V3}_j^2 & \ldots & \bf{V3}_j^n \\ \bf{V4}_j^1 & \bf{V4}_j^2 & \ldots & \bf{V4}_j^n \end{matrix} \right) \in \mathbb{R}^{4\times n},\f] with \f$n\f$ the number of rows in band \f$B_j\f$: \f[n = \begin{cases} 2w, & j = 1||m; \\ 3w, & \mbox{else}. \end{cases}\f] Each \f$BD_j\f$ can be obtained using the standard deviation vector \f$S_j\f$ and mean vector \f$M_j\f$ of \f$BDM_J\f$. Thus, finally: \f[LBD = (M_1^T, S_1^T, M_2^T, S_2^T, \ldots, M_m^T, S_m^T)^T \in \mathbb{R}^{8m}\f] Once the LBD has been obtained, it must be converted into a binary form. For such purpose, we consider 32 possible pairs of BD inside it; each couple of BD is compared bit by bit and comparison generates an 8 bit string. Concatenating 32 comparison strings, we get the 256-bit final binary representation of a single LBD. */ #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/ml/ml.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/ml.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/ml.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_ML_HPP__ #define __OPENCV_ML_HPP__ #ifdef __cplusplus # include "opencv2/core.hpp" #endif #ifdef __cplusplus #include #include #include /** @defgroup ml Machine Learning The Machine Learning Library (MLL) is a set of classes and functions for statistical classification, regression, and clustering of data. Most of the classification and regression algorithms are implemented as C++ classes. As the algorithms have different sets of features (like an ability to handle missing measurements or categorical input variables), there is a little common ground between the classes. This common ground is defined by the class cv::ml::StatModel that all the other ML classes are derived from. See detailed overview here: @ref ml_intro. */ namespace cv { namespace ml { //! @addtogroup ml //! @{ /** @brief Variable types */ enum VariableTypes { VAR_NUMERICAL =0, //!< same as VAR_ORDERED VAR_ORDERED =0, //!< ordered variables VAR_CATEGORICAL =1 //!< categorical variables }; /** @brief %Error types */ enum ErrorTypes { TEST_ERROR = 0, TRAIN_ERROR = 1 }; /** @brief Sample types */ enum SampleTypes { ROW_SAMPLE = 0, //!< each training sample is a row of samples COL_SAMPLE = 1 //!< each training sample occupies a column of samples }; /** @brief The structure represents the logarithmic grid range of statmodel parameters. It is used for optimizing statmodel accuracy by varying model parameters, the accuracy estimate being computed by cross-validation. */ class CV_EXPORTS ParamGrid { public: /** @brief Default constructor */ ParamGrid(); /** @brief Constructor with parameters */ ParamGrid(double _minVal, double _maxVal, double _logStep); double minVal; //!< Minimum value of the statmodel parameter. Default value is 0. double maxVal; //!< Maximum value of the statmodel parameter. Default value is 0. /** @brief Logarithmic step for iterating the statmodel parameter. The grid determines the following iteration sequence of the statmodel parameter values: \f[(minVal, minVal*step, minVal*{step}^2, \dots, minVal*{logStep}^n),\f] where \f$n\f$ is the maximal index satisfying \f[\texttt{minVal} * \texttt{logStep} ^n < \texttt{maxVal}\f] The grid is logarithmic, so logStep must always be greater then 1. Default value is 1. */ double logStep; }; /** @brief Class encapsulating training data. Please note that the class only specifies the interface of training data, but not implementation. All the statistical model classes in _ml_ module accepts Ptr\ as parameter. In other words, you can create your own class derived from TrainData and pass smart pointer to the instance of this class into StatModel::train. @sa @ref ml_intro_data */ class CV_EXPORTS_W TrainData { public: static inline float missingValue() { return FLT_MAX; } virtual ~TrainData(); CV_WRAP virtual int getLayout() const = 0; CV_WRAP virtual int getNTrainSamples() const = 0; CV_WRAP virtual int getNTestSamples() const = 0; CV_WRAP virtual int getNSamples() const = 0; CV_WRAP virtual int getNVars() const = 0; CV_WRAP virtual int getNAllVars() const = 0; CV_WRAP virtual void getSample(InputArray varIdx, int sidx, float* buf) const = 0; CV_WRAP virtual Mat getSamples() const = 0; CV_WRAP virtual Mat getMissing() const = 0; /** @brief Returns matrix of train samples @param layout The requested layout. If it's different from the initial one, the matrix is transposed. See ml::SampleTypes. @param compressSamples if true, the function returns only the training samples (specified by sampleIdx) @param compressVars if true, the function returns the shorter training samples, containing only the active variables. In current implementation the function tries to avoid physical data copying and returns the matrix stored inside TrainData (unless the transposition or compression is needed). */ CV_WRAP virtual Mat getTrainSamples(int layout=ROW_SAMPLE, bool compressSamples=true, bool compressVars=true) const = 0; /** @brief Returns the vector of responses The function returns ordered or the original categorical responses. Usually it's used in regression algorithms. */ CV_WRAP virtual Mat getTrainResponses() const = 0; /** @brief Returns the vector of normalized categorical responses The function returns vector of responses. Each response is integer from `0` to `-1`. The actual label value can be retrieved then from the class label vector, see TrainData::getClassLabels. */ CV_WRAP virtual Mat getTrainNormCatResponses() const = 0; CV_WRAP virtual Mat getTestResponses() const = 0; CV_WRAP virtual Mat getTestNormCatResponses() const = 0; CV_WRAP virtual Mat getResponses() const = 0; CV_WRAP virtual Mat getNormCatResponses() const = 0; CV_WRAP virtual Mat getSampleWeights() const = 0; CV_WRAP virtual Mat getTrainSampleWeights() const = 0; CV_WRAP virtual Mat getTestSampleWeights() const = 0; CV_WRAP virtual Mat getVarIdx() const = 0; CV_WRAP virtual Mat getVarType() const = 0; CV_WRAP virtual int getResponseType() const = 0; CV_WRAP virtual Mat getTrainSampleIdx() const = 0; CV_WRAP virtual Mat getTestSampleIdx() const = 0; CV_WRAP virtual void getValues(int vi, InputArray sidx, float* values) const = 0; virtual void getNormCatValues(int vi, InputArray sidx, int* values) const = 0; CV_WRAP virtual Mat getDefaultSubstValues() const = 0; CV_WRAP virtual int getCatCount(int vi) const = 0; /** @brief Returns the vector of class labels The function returns vector of unique labels occurred in the responses. */ CV_WRAP virtual Mat getClassLabels() const = 0; CV_WRAP virtual Mat getCatOfs() const = 0; CV_WRAP virtual Mat getCatMap() const = 0; /** @brief Splits the training data into the training and test parts @sa TrainData::setTrainTestSplitRatio */ CV_WRAP virtual void setTrainTestSplit(int count, bool shuffle=true) = 0; /** @brief Splits the training data into the training and test parts The function selects a subset of specified relative size and then returns it as the training set. If the function is not called, all the data is used for training. Please, note that for each of TrainData::getTrain\* there is corresponding TrainData::getTest\*, so that the test subset can be retrieved and processed as well. @sa TrainData::setTrainTestSplit */ CV_WRAP virtual void setTrainTestSplitRatio(double ratio, bool shuffle=true) = 0; CV_WRAP virtual void shuffleTrainTest() = 0; CV_WRAP static Mat getSubVector(const Mat& vec, const Mat& idx); /** @brief Reads the dataset from a .csv file and returns the ready-to-use training data. @param filename The input file name @param headerLineCount The number of lines in the beginning to skip; besides the header, the function also skips empty lines and lines staring with `#` @param responseStartIdx Index of the first output variable. If -1, the function considers the last variable as the response @param responseEndIdx Index of the last output variable + 1. If -1, then there is single response variable at responseStartIdx. @param varTypeSpec The optional text string that specifies the variables' types. It has the format `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables from `n1 to n2` (inclusive range), `n3`, `n4 to n5` ... are considered ordered and `n6`, `n7 to n8` ... are considered as categorical. The range `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]` should cover all the variables. If varTypeSpec is not specified, then algorithm uses the following rules: - all input variables are considered ordered by default. If some column contains has non- numerical values, e.g. 'apple', 'pear', 'apple', 'apple', 'mango', the corresponding variable is considered categorical. - if there are several output variables, they are all considered as ordered. Error is reported when non-numerical values are used. - if there is a single output variable, then if its values are non-numerical or are all integers, then it's considered categorical. Otherwise, it's considered ordered. @param delimiter The character used to separate values in each line. @param missch The character used to specify missing measurements. It should not be a digit. Although it's a non-numerical value, it surely does not affect the decision of whether the variable ordered or categorical. @note If the dataset only contains input variables and no responses, use responseStartIdx = -2 and responseEndIdx = 0. The output variables vector will just contain zeros. */ static Ptr loadFromCSV(const String& filename, int headerLineCount, int responseStartIdx=-1, int responseEndIdx=-1, const String& varTypeSpec=String(), char delimiter=',', char missch='?'); /** @brief Creates training data from in-memory arrays. @param samples matrix of samples. It should have CV_32F type. @param layout see ml::SampleTypes. @param responses matrix of responses. If the responses are scalar, they should be stored as a single row or as a single column. The matrix should have type CV_32F or CV_32S (in the former case the responses are considered as ordered by default; in the latter case - as categorical) @param varIdx vector specifying which variables to use for training. It can be an integer vector (CV_32S) containing 0-based variable indices or byte vector (CV_8U) containing a mask of active variables. @param sampleIdx vector specifying which samples to use for training. It can be an integer vector (CV_32S) containing 0-based sample indices or byte vector (CV_8U) containing a mask of training samples. @param sampleWeights optional vector with weights for each sample. It should have CV_32F type. @param varType optional vector of type CV_8U and size ` + `, containing types of each input and output variable. See ml::VariableTypes. */ CV_WRAP static Ptr create(InputArray samples, int layout, InputArray responses, InputArray varIdx=noArray(), InputArray sampleIdx=noArray(), InputArray sampleWeights=noArray(), InputArray varType=noArray()); }; /** @brief Base class for statistical models in OpenCV ML. */ class CV_EXPORTS_W StatModel : public Algorithm { public: /** Predict options */ enum Flags { UPDATE_MODEL = 1, RAW_OUTPUT=1, //!< makes the method return the raw results (the sum), not the class label COMPRESSED_INPUT=2, PREPROCESSED_INPUT=4 }; /** @brief Returns the number of variables in training samples */ CV_WRAP virtual int getVarCount() const = 0; CV_WRAP virtual bool empty() const; /** @brief Returns true if the model is trained */ CV_WRAP virtual bool isTrained() const = 0; /** @brief Returns true if the model is classifier */ CV_WRAP virtual bool isClassifier() const = 0; /** @brief Trains the statistical model @param trainData training data that can be loaded from file using TrainData::loadFromCSV or created with TrainData::create. @param flags optional flags, depending on the model. Some of the models can be updated with the new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP). */ CV_WRAP virtual bool train( const Ptr& trainData, int flags=0 ); /** @brief Trains the statistical model @param samples training samples @param layout See ml::SampleTypes. @param responses vector of responses associated with the training samples. */ CV_WRAP virtual bool train( InputArray samples, int layout, InputArray responses ); /** @brief Computes error on the training or test dataset @param data the training data @param test if true, the error is computed over the test subset of the data, otherwise it's computed over the training subset of the data. Please note that if you loaded a completely different dataset to evaluate already trained classifier, you will probably want not to set the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so that the error is computed for the whole new set. Yes, this sounds a bit confusing. @param resp the optional output responses. The method uses StatModel::predict to compute the error. For regression models the error is computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%). */ CV_WRAP virtual float calcError( const Ptr& data, bool test, OutputArray resp ) const; /** @brief Predicts response(s) for the provided sample(s) @param samples The input samples, floating-point matrix @param results The optional output matrix of results. @param flags The optional flags, model-dependent. See cv::ml::StatModel::Flags. */ CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0; /** @brief Create and train model with default parameters The class must implement static `create()` method with no parameters or with all default parameter values */ template static Ptr<_Tp> train(const Ptr& data, int flags=0) { Ptr<_Tp> model = _Tp::create(); return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>(); } }; /****************************************************************************************\ * Normal Bayes Classifier * \****************************************************************************************/ /** @brief Bayes classifier for normally distributed data. @sa @ref ml_intro_bayes */ class CV_EXPORTS_W NormalBayesClassifier : public StatModel { public: /** @brief Predicts the response for sample(s). The method estimates the most probable classes for input vectors. Input vectors (one or more) are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one output vector outputs. The predicted class for a single input vector is returned by the method. The vector outputProbs contains the output probabilities corresponding to each element of result. */ CV_WRAP virtual float predictProb( InputArray inputs, OutputArray outputs, OutputArray outputProbs, int flags=0 ) const = 0; /** Creates empty model Use StatModel::train to train the model after creation. */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * K-Nearest Neighbour Classifier * \****************************************************************************************/ /** @brief The class implements K-Nearest Neighbors model @sa @ref ml_intro_knn */ class CV_EXPORTS_W KNearest : public StatModel { public: /** Default number of neighbors to use in predict method. */ /** @see setDefaultK */ CV_WRAP virtual int getDefaultK() const = 0; /** @copybrief getDefaultK @see getDefaultK */ CV_WRAP virtual void setDefaultK(int val) = 0; /** Whether classification or regression model should be trained. */ /** @see setIsClassifier */ CV_WRAP virtual bool getIsClassifier() const = 0; /** @copybrief getIsClassifier @see getIsClassifier */ CV_WRAP virtual void setIsClassifier(bool val) = 0; /** Parameter for KDTree implementation. */ /** @see setEmax */ CV_WRAP virtual int getEmax() const = 0; /** @copybrief getEmax @see getEmax */ CV_WRAP virtual void setEmax(int val) = 0; /** %Algorithm type, one of KNearest::Types. */ /** @see setAlgorithmType */ CV_WRAP virtual int getAlgorithmType() const = 0; /** @copybrief getAlgorithmType @see getAlgorithmType */ CV_WRAP virtual void setAlgorithmType(int val) = 0; /** @brief Finds the neighbors and predicts responses for input vectors. @param samples Input samples stored by rows. It is a single-precision floating-point matrix of ` * k` size. @param k Number of used nearest neighbors. Should be greater than 1. @param results Vector with results of prediction (regression or classification) for each input sample. It is a single-precision floating-point vector with `` elements. @param neighborResponses Optional output values for corresponding neighbors. It is a single- precision floating-point matrix of ` * k` size. @param dist Optional output distances from the input vectors to the corresponding neighbors. It is a single-precision floating-point matrix of ` * k` size. For each input vector (a row of the matrix samples), the method finds the k nearest neighbors. In case of regression, the predicted result is a mean value of the particular vector's neighbor responses. In case of classification, the class is determined by voting. For each input vector, the neighbors are sorted by their distances to the vector. In case of C++ interface you can use output pointers to empty matrices and the function will allocate memory itself. If only a single input vector is passed, all output matrices are optional and the predicted value is returned by the method. The function is parallelized with the TBB library. */ CV_WRAP virtual float findNearest( InputArray samples, int k, OutputArray results, OutputArray neighborResponses=noArray(), OutputArray dist=noArray() ) const = 0; /** @brief Implementations of KNearest algorithm */ enum Types { BRUTE_FORCE=1, KDTREE=2 }; /** @brief Creates the empty model The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method. */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Support Vector Machines * \****************************************************************************************/ /** @brief Support Vector Machines. @sa @ref ml_intro_svm */ class CV_EXPORTS_W SVM : public StatModel { public: class CV_EXPORTS Kernel : public Algorithm { public: virtual int getType() const = 0; virtual void calc( int vcount, int n, const float* vecs, const float* another, float* results ) = 0; }; /** Type of a %SVM formulation. See SVM::Types. Default value is SVM::C_SVC. */ /** @see setType */ CV_WRAP virtual int getType() const = 0; /** @copybrief getType @see getType */ CV_WRAP virtual void setType(int val) = 0; /** Parameter \f$\gamma\f$ of a kernel function. For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. */ /** @see setGamma */ CV_WRAP virtual double getGamma() const = 0; /** @copybrief getGamma @see getGamma */ CV_WRAP virtual void setGamma(double val) = 0; /** Parameter _coef0_ of a kernel function. For SVM::POLY or SVM::SIGMOID. Default value is 0.*/ /** @see setCoef0 */ CV_WRAP virtual double getCoef0() const = 0; /** @copybrief getCoef0 @see getCoef0 */ CV_WRAP virtual void setCoef0(double val) = 0; /** Parameter _degree_ of a kernel function. For SVM::POLY. Default value is 0. */ /** @see setDegree */ CV_WRAP virtual double getDegree() const = 0; /** @copybrief getDegree @see getDegree */ CV_WRAP virtual void setDegree(double val) = 0; /** Parameter _C_ of a %SVM optimization problem. For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. */ /** @see setC */ CV_WRAP virtual double getC() const = 0; /** @copybrief getC @see getC */ CV_WRAP virtual void setC(double val) = 0; /** Parameter \f$\nu\f$ of a %SVM optimization problem. For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. */ /** @see setNu */ CV_WRAP virtual double getNu() const = 0; /** @copybrief getNu @see getNu */ CV_WRAP virtual void setNu(double val) = 0; /** Parameter \f$\epsilon\f$ of a %SVM optimization problem. For SVM::EPS_SVR. Default value is 0. */ /** @see setP */ CV_WRAP virtual double getP() const = 0; /** @copybrief getP @see getP */ CV_WRAP virtual void setP(double val) = 0; /** Optional weights in the SVM::C_SVC problem, assigned to particular classes. They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. Thus these weights affect the misclassification penalty for different classes. The larger weight, the larger penalty on misclassification of data from the corresponding class. Default value is empty Mat. */ /** @see setClassWeights */ CV_WRAP virtual cv::Mat getClassWeights() const = 0; /** @copybrief getClassWeights @see getClassWeights */ CV_WRAP virtual void setClassWeights(const cv::Mat &val) = 0; /** Termination criteria of the iterative %SVM training procedure which solves a partial case of constrained quadratic optimization problem. You can specify tolerance and/or the maximum number of iterations. Default value is `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; */ /** @see setTermCriteria */ CV_WRAP virtual cv::TermCriteria getTermCriteria() const = 0; /** @copybrief getTermCriteria @see getTermCriteria */ CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; /** Type of a %SVM kernel. See SVM::KernelTypes. Default value is SVM::RBF. */ CV_WRAP virtual int getKernelType() const = 0; /** Initialize with one of predefined kernels. See SVM::KernelTypes. */ CV_WRAP virtual void setKernel(int kernelType) = 0; /** Initialize with custom kernel. See SVM::Kernel class for implementation details */ virtual void setCustomKernel(const Ptr &_kernel) = 0; //! %SVM type enum Types { /** C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), allows imperfect separation of classes with penalty multiplier C for outliers. */ C_SVC=100, /** \f$\nu\f$-Support Vector Classification. n-class classification with possible imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger the value, the smoother the decision boundary) is used instead of C. */ NU_SVC=101, /** Distribution Estimation (One-class %SVM). All the training data are from the same class, %SVM builds a boundary that separates the class from the rest of the feature space. */ ONE_CLASS=102, /** \f$\epsilon\f$-Support Vector Regression. The distance between feature vectors from the training set and the fitting hyper-plane must be less than p. For outliers the penalty multiplier C is used. */ EPS_SVR=103, /** \f$\nu\f$-Support Vector Regression. \f$\nu\f$ is used instead of p. See @cite LibSVM for details. */ NU_SVR=104 }; /** @brief %SVM kernel type A comparison of different kernels on the following 2D test case with four classes. Four SVM::C_SVC SVMs have been trained (one against rest) with auto_train. Evaluation on three different kernels (SVM::CHI2, SVM::INTER, SVM::RBF). The color depicts the class with max score. Bright means max-score \> 0, dark means max-score \< 0. ![image](pics/SVM_Comparison.png) */ enum KernelTypes { /** Returned by SVM::getKernelType in case when custom kernel has been set */ CUSTOM=-1, /** Linear kernel. No mapping is done, linear discrimination (or regression) is done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. */ LINEAR=0, /** Polynomial kernel: \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. */ POLY=1, /** Radial basis function (RBF), a good choice in most cases. \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. */ RBF=2, /** Sigmoid kernel: \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. */ SIGMOID=3, /** Exponential Chi2 kernel, similar to the RBF kernel: \f$K(x_i, x_j) = e^{-\gamma \chi^2(x_i,x_j)}, \chi^2(x_i,x_j) = (x_i-x_j)^2/(x_i+x_j), \gamma > 0\f$. */ CHI2=4, /** Histogram intersection kernel. A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. */ INTER=5 }; //! %SVM params type enum ParamTypes { C=0, GAMMA=1, P=2, NU=3, COEF=4, DEGREE=5 }; /** @brief Trains an %SVM with optimal parameters. @param data the training data that can be constructed using TrainData::create or TrainData::loadFromCSV. @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One subset is used to test the model, the others form the train set. So, the %SVM algorithm is executed kFold times. @param Cgrid grid for C @param gammaGrid grid for gamma @param pGrid grid for p @param nuGrid grid for nu @param coeffGrid grid for coeff @param degreeGrid grid for degree @param balanced If true and the problem is 2-class classification then the method creates more balanced cross-validation subsets that is proportions between classes in subsets are close to such proportion in the whole train dataset. The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, nu, coef0, degree. Parameters are considered optimal when the cross-validation estimate of the test set error is minimal. If there is no need to optimize a parameter, the corresponding grid step should be set to any value less than or equal to 1. For example, to avoid optimization in gamma, set `gammaGrid.step = 0`, `gammaGrid.minVal`, `gamma_grid.maxVal` as arbitrary numbers. In this case, the value `Gamma` is taken for gamma. And, finally, if the optimization in a parameter is required but the corresponding grid is unknown, you may call the function SVM::getDefaultGrid. To generate a grid, for example, for gamma, call `SVM::getDefaultGrid(SVM::GAMMA)`. This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and the usual %SVM with parameters specified in params is executed. */ virtual bool trainAuto( const Ptr& data, int kFold = 10, ParamGrid Cgrid = SVM::getDefaultGrid(SVM::C), ParamGrid gammaGrid = SVM::getDefaultGrid(SVM::GAMMA), ParamGrid pGrid = SVM::getDefaultGrid(SVM::P), ParamGrid nuGrid = SVM::getDefaultGrid(SVM::NU), ParamGrid coeffGrid = SVM::getDefaultGrid(SVM::COEF), ParamGrid degreeGrid = SVM::getDefaultGrid(SVM::DEGREE), bool balanced=false) = 0; /** @brief Retrieves all the support vectors The method returns all the support vectors as a floating-point matrix, where support vectors are stored as matrix rows. */ CV_WRAP virtual Mat getSupportVectors() const = 0; /** @brief Retrieves all the uncompressed support vectors of a linear %SVM The method returns all the uncompressed support vectors of a linear %SVM that the compressed support vector, used for prediction, was derived from. They are returned in a floating-point matrix, where the support vectors are stored as matrix rows. */ CV_WRAP Mat getUncompressedSupportVectors() const; /** @brief Retrieves the decision function @param i the index of the decision function. If the problem solved is regression, 1-class or 2-class classification, then there will be just one decision function and the index should always be 0. Otherwise, in the case of N-class classification, there will be \f$N(N-1)/2\f$ decision functions. @param alpha the optional output vector for weights, corresponding to different support vectors. In the case of linear %SVM all the alpha's will be 1's. @param svidx the optional output vector of indices of support vectors within the matrix of support vectors (which can be retrieved by SVM::getSupportVectors). In the case of linear %SVM each decision function consists of a single "compressed" support vector. The method returns rho parameter of the decision function, a scalar subtracted from the weighted sum of kernel responses. */ CV_WRAP virtual double getDecisionFunction(int i, OutputArray alpha, OutputArray svidx) const = 0; /** @brief Generates a grid for %SVM parameters. @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is generated for the parameter with this ID. The function generates a grid for the specified parameter of the %SVM algorithm. The grid may be passed to the function SVM::trainAuto. */ static ParamGrid getDefaultGrid( int param_id ); /** Creates empty model. Use StatModel::train to train the model. Since %SVM has several parameters, you may want to find the best parameters for your problem, it can be done with SVM::trainAuto. */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Expectation - Maximization * \****************************************************************************************/ /** @brief The class implements the Expectation Maximization algorithm. @sa @ref ml_intro_em */ class CV_EXPORTS_W EM : public StatModel { public: //! Type of covariation matrices enum Types { /** A scaled identity matrix \f$\mu_k * I\f$. There is the only parameter \f$\mu_k\f$ to be estimated for each matrix. The option may be used in special cases, when the constraint is relevant, or as a first step in the optimization (for example in case when the data is preprocessed with PCA). The results of such preliminary estimation may be passed again to the optimization procedure, this time with covMatType=EM::COV_MAT_DIAGONAL. */ COV_MAT_SPHERICAL=0, /** A diagonal matrix with positive diagonal elements. The number of free parameters is d for each matrix. This is most commonly used option yielding good estimation results. */ COV_MAT_DIAGONAL=1, /** A symmetric positively defined matrix. The number of free parameters in each matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless there is pretty accurate initial estimation of the parameters and/or a huge number of training samples. */ COV_MAT_GENERIC=2, COV_MAT_DEFAULT=COV_MAT_DIAGONAL }; //! Default parameters enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100}; //! The initial step enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0}; /** The number of mixture components in the Gaussian mixture model. Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. Some of %EM implementation could determine the optimal number of mixtures within a specified value range, but that is not the case in ML yet. */ /** @see setClustersNumber */ CV_WRAP virtual int getClustersNumber() const = 0; /** @copybrief getClustersNumber @see getClustersNumber */ CV_WRAP virtual void setClustersNumber(int val) = 0; /** Constraint on covariance matrices which defines type of matrices. See EM::Types. */ /** @see setCovarianceMatrixType */ CV_WRAP virtual int getCovarianceMatrixType() const = 0; /** @copybrief getCovarianceMatrixType @see getCovarianceMatrixType */ CV_WRAP virtual void setCovarianceMatrixType(int val) = 0; /** The termination criteria of the %EM algorithm. The %EM algorithm can be terminated by the number of iterations termCrit.maxCount (number of M-steps) or when relative change of likelihood logarithm is less than termCrit.epsilon. Default maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. */ /** @see setTermCriteria */ CV_WRAP virtual TermCriteria getTermCriteria() const = 0; /** @copybrief getTermCriteria @see getTermCriteria */ CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; /** @brief Returns weights of the mixtures Returns vector with the number of elements equal to the number of mixtures. */ CV_WRAP virtual Mat getWeights() const = 0; /** @brief Returns the cluster centers (means of the Gaussian mixture) Returns matrix with the number of rows equal to the number of mixtures and number of columns equal to the space dimensionality. */ CV_WRAP virtual Mat getMeans() const = 0; /** @brief Returns covariation matrices Returns vector of covariation matrices. Number of matrices is the number of gaussian mixtures, each matrix is a square floating-point matrix NxN, where N is the space dimensionality. */ CV_WRAP virtual void getCovs(CV_OUT std::vector& covs) const = 0; /** @brief Returns a likelihood logarithm value and an index of the most probable mixture component for the given sample. @param sample A sample for classification. It should be a one-channel matrix of \f$1 \times dims\f$ or \f$dims \times 1\f$ size. @param probs Optional output matrix that contains posterior probabilities of each component given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type. The method returns a two-element double vector. Zero element is a likelihood logarithm value for the sample. First element is an index of the most probable mixture component for the given sample. */ CV_WRAP virtual Vec2d predict2(InputArray sample, OutputArray probs) const = 0; /** @brief Estimate the Gaussian mixture parameters from a samples set. This variation starts with Expectation step. Initial values of the model parameters will be estimated by the k-means algorithm. Unlike many of the ML models, %EM is an unsupervised learning algorithm and it does not take responses (class labels or function values) as input. Instead, it computes the *Maximum Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the parameters inside the structure: \f$p_{i,k}\f$ in probs, \f$a_k\f$ in means , \f$S_k\f$ in covs[k], \f$\pi_k\f$ in weights , and optionally computes the output "class label" for each sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable mixture component for each sample). The trained model can be used further for prediction, just like any other classifier. The trained model is similar to the NormalBayesClassifier. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type it will be converted to the inner matrix of such type for the further computing. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. @param labels The optional output "class label" for each sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. @param probs The optional output matrix that contains posterior probabilities of each Gaussian mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and CV_64FC1 type. */ CV_WRAP virtual bool trainEM(InputArray samples, OutputArray logLikelihoods=noArray(), OutputArray labels=noArray(), OutputArray probs=noArray()) = 0; /** @brief Estimate the Gaussian mixture parameters from a samples set. This variation starts with Expectation step. You need to provide initial means \f$a_k\f$ of mixture components. Optionally you can pass initial weights \f$\pi_k\f$ and covariance matrices \f$S_k\f$ of mixture components. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type it will be converted to the inner matrix of such type for the further computing. @param means0 Initial means \f$a_k\f$ of mixture components. It is a one-channel matrix of \f$nclusters \times dims\f$ size. If the matrix does not have CV_64F type it will be converted to the inner matrix of such type for the further computing. @param covs0 The vector of initial covariance matrices \f$S_k\f$ of mixture components. Each of covariance matrices is a one-channel matrix of \f$dims \times dims\f$ size. If the matrices do not have CV_64F type they will be converted to the inner matrices of such type for the further computing. @param weights0 Initial weights \f$\pi_k\f$ of mixture components. It should be a one-channel floating-point matrix with \f$1 \times nclusters\f$ or \f$nclusters \times 1\f$ size. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. @param labels The optional output "class label" for each sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. @param probs The optional output matrix that contains posterior probabilities of each Gaussian mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and CV_64FC1 type. */ CV_WRAP virtual bool trainE(InputArray samples, InputArray means0, InputArray covs0=noArray(), InputArray weights0=noArray(), OutputArray logLikelihoods=noArray(), OutputArray labels=noArray(), OutputArray probs=noArray()) = 0; /** @brief Estimate the Gaussian mixture parameters from a samples set. This variation starts with Maximization step. You need to provide initial probabilities \f$p_{i,k}\f$ to use this option. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type it will be converted to the inner matrix of such type for the further computing. @param probs0 @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. @param labels The optional output "class label" for each sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. @param probs The optional output matrix that contains posterior probabilities of each Gaussian mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and CV_64FC1 type. */ CV_WRAP virtual bool trainM(InputArray samples, InputArray probs0, OutputArray logLikelihoods=noArray(), OutputArray labels=noArray(), OutputArray probs=noArray()) = 0; /** Creates empty %EM model. The model should be trained then using StatModel::train(traindata, flags) method. Alternatively, you can use one of the EM::train\* methods or load it from file using Algorithm::load\(filename). */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Decision Tree * \****************************************************************************************/ /** @brief The class represents a single decision tree or a collection of decision trees. The current public interface of the class allows user to train only a single decision tree, however the class is capable of storing multiple decision trees and using them for prediction (by summing responses or using a voting schemes), and the derived from DTrees classes (such as RTrees and Boost) use this capability to implement decision tree ensembles. @sa @ref ml_intro_trees */ class CV_EXPORTS_W DTrees : public StatModel { public: /** Predict options */ enum Flags { PREDICT_AUTO=0, PREDICT_SUM=(1<<8), PREDICT_MAX_VOTE=(2<<8), PREDICT_MASK=(3<<8) }; /** Cluster possible values of a categorical variable into K\<=maxCategories clusters to find a suboptimal split. If a discrete variable, on which the training procedure tries to make a split, takes more than maxCategories values, the precise best subset estimation may take a very long time because the algorithm is exponential. Instead, many decision trees engines (including our implementation) try to find sub-optimal split in this case by clustering all the samples into maxCategories clusters that is some categories are merged together. The clustering is applied only in n \> 2-class classification problems for categorical variables with N \> max_categories possible values. In case of regression and 2-class classification the optimal split can be found efficiently without employing clustering, thus the parameter is not used in these cases. Default value is 10.*/ /** @see setMaxCategories */ CV_WRAP virtual int getMaxCategories() const = 0; /** @copybrief getMaxCategories @see getMaxCategories */ CV_WRAP virtual void setMaxCategories(int val) = 0; /** The maximum possible depth of the tree. That is the training algorithms attempts to split a node while its depth is less than maxDepth. The root node has zero depth. The actual depth may be smaller if the other termination criteria are met (see the outline of the training procedure @ref ml_intro_trees "here"), and/or if the tree is pruned. Default value is INT_MAX.*/ /** @see setMaxDepth */ CV_WRAP virtual int getMaxDepth() const = 0; /** @copybrief getMaxDepth @see getMaxDepth */ CV_WRAP virtual void setMaxDepth(int val) = 0; /** If the number of samples in a node is less than this parameter then the node will not be split. Default value is 10.*/ /** @see setMinSampleCount */ CV_WRAP virtual int getMinSampleCount() const = 0; /** @copybrief getMinSampleCount @see getMinSampleCount */ CV_WRAP virtual void setMinSampleCount(int val) = 0; /** If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold cross-validation procedure where K is equal to CVFolds. Default value is 10.*/ /** @see setCVFolds */ CV_WRAP virtual int getCVFolds() const = 0; /** @copybrief getCVFolds @see getCVFolds */ CV_WRAP virtual void setCVFolds(int val) = 0; /** If true then surrogate splits will be built. These splits allow to work with missing data and compute variable importance correctly. Default value is false. @note currently it's not implemented.*/ /** @see setUseSurrogates */ CV_WRAP virtual bool getUseSurrogates() const = 0; /** @copybrief getUseSurrogates @see getUseSurrogates */ CV_WRAP virtual void setUseSurrogates(bool val) = 0; /** If true then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate. Default value is true.*/ /** @see setUse1SERule */ CV_WRAP virtual bool getUse1SERule() const = 0; /** @copybrief getUse1SERule @see getUse1SERule */ CV_WRAP virtual void setUse1SERule(bool val) = 0; /** If true then pruned branches are physically removed from the tree. Otherwise they are retained and it is possible to get results from the original unpruned (or pruned less aggressively) tree. Default value is true.*/ /** @see setTruncatePrunedTree */ CV_WRAP virtual bool getTruncatePrunedTree() const = 0; /** @copybrief getTruncatePrunedTree @see getTruncatePrunedTree */ CV_WRAP virtual void setTruncatePrunedTree(bool val) = 0; /** Termination criteria for regression trees. If all absolute differences between an estimated value in a node and values of train samples in this node are less than this parameter then the node will not be split further. Default value is 0.01f*/ /** @see setRegressionAccuracy */ CV_WRAP virtual float getRegressionAccuracy() const = 0; /** @copybrief getRegressionAccuracy @see getRegressionAccuracy */ CV_WRAP virtual void setRegressionAccuracy(float val) = 0; /** @brief The array of a priori class probabilities, sorted by the class label value. The parameter can be used to tune the decision tree preferences toward a certain class. For example, if you want to detect some rare anomaly occurrence, the training base will likely contain much more normal cases than anomalies, so a very good classification performance will be achieved just by considering every case as normal. To avoid this, the priors can be specified, where the anomaly probability is artificially increased (up to 0.5 or even greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is adjusted properly. You can also think about this parameter as weights of prediction categories which determine relative weights that you give to misclassification. That is, if the weight of the first category is 1 and the weight of the second category is 10, then each mistake in predicting the second category is equivalent to making 10 mistakes in predicting the first category. Default value is empty Mat.*/ /** @see setPriors */ CV_WRAP virtual cv::Mat getPriors() const = 0; /** @copybrief getPriors @see getPriors */ CV_WRAP virtual void setPriors(const cv::Mat &val) = 0; /** @brief The class represents a decision tree node. */ class CV_EXPORTS Node { public: Node(); double value; //!< Value at the node: a class label in case of classification or estimated //!< function value in case of regression. int classIdx; //!< Class index normalized to 0..class_count-1 range and assigned to the //!< node. It is used internally in classification trees and tree ensembles. int parent; //!< Index of the parent node int left; //!< Index of the left child node int right; //!< Index of right child node int defaultDir; //!< Default direction where to go (-1: left or +1: right). It helps in the //!< case of missing values. int split; //!< Index of the first split }; /** @brief The class represents split in a decision tree. */ class CV_EXPORTS Split { public: Split(); int varIdx; //!< Index of variable on which the split is created. bool inversed; //!< If true, then the inverse split rule is used (i.e. left and right //!< branches are exchanged in the rule expressions below). float quality; //!< The split quality, a positive number. It is used to choose the best split. int next; //!< Index of the next split in the list of splits for the node float c; /**< The threshold value in case of split on an ordered variable. The rule is: @code{.none} if var_value < c then next_node <- left else next_node <- right @endcode */ int subsetOfs; /**< Offset of the bitset used by the split on a categorical variable. The rule is: @code{.none} if bitset[var_value] == 1 then next_node <- left else next_node <- right @endcode */ }; /** @brief Returns indices of root nodes */ virtual const std::vector& getRoots() const = 0; /** @brief Returns all the nodes all the node indices are indices in the returned vector */ virtual const std::vector& getNodes() const = 0; /** @brief Returns all the splits all the split indices are indices in the returned vector */ virtual const std::vector& getSplits() const = 0; /** @brief Returns all the bitsets for categorical splits Split::subsetOfs is an offset in the returned vector */ virtual const std::vector& getSubsets() const = 0; /** @brief Creates the empty model The static method creates empty decision tree with the specified parameters. It should be then trained using train method (see StatModel::train). Alternatively, you can load the model from file using Algorithm::load\(filename). */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Random Trees Classifier * \****************************************************************************************/ /** @brief The class implements the random forest predictor. @sa @ref ml_intro_rtrees */ class CV_EXPORTS_W RTrees : public DTrees { public: /** If true then variable importance will be calculated and then it can be retrieved by RTrees::getVarImportance. Default value is false.*/ /** @see setCalculateVarImportance */ CV_WRAP virtual bool getCalculateVarImportance() const = 0; /** @copybrief getCalculateVarImportance @see getCalculateVarImportance */ CV_WRAP virtual void setCalculateVarImportance(bool val) = 0; /** The size of the randomly selected subset of features at each tree node and that are used to find the best split(s). If you set it to 0 then the size will be set to the square root of the total number of features. Default value is 0.*/ /** @see setActiveVarCount */ CV_WRAP virtual int getActiveVarCount() const = 0; /** @copybrief getActiveVarCount @see getActiveVarCount */ CV_WRAP virtual void setActiveVarCount(int val) = 0; /** The termination criteria that specifies when the training algorithm stops. Either when the specified number of trees is trained and added to the ensemble or when sufficient accuracy (measured as OOB error) is achieved. Typically the more trees you have the better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes pass a certain number of trees. Also to keep in mind, the number of tree increases the prediction time linearly. Default value is TermCriteria(TermCriteria::MAX_ITERS + TermCriteria::EPS, 50, 0.1)*/ /** @see setTermCriteria */ CV_WRAP virtual TermCriteria getTermCriteria() const = 0; /** @copybrief getTermCriteria @see getTermCriteria */ CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; /** Returns the variable importance array. The method returns the variable importance vector, computed at the training stage when CalculateVarImportance is set to true. If this flag was set to false, the empty matrix is returned. */ CV_WRAP virtual Mat getVarImportance() const = 0; /** Creates the empty model. Use StatModel::train to train the model, StatModel::train to create and train the model, Algorithm::load to load the pre-trained model. */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Boosted tree classifier * \****************************************************************************************/ /** @brief Boosted tree classifier derived from DTrees @sa @ref ml_intro_boost */ class CV_EXPORTS_W Boost : public DTrees { public: /** Type of the boosting algorithm. See Boost::Types. Default value is Boost::REAL. */ /** @see setBoostType */ CV_WRAP virtual int getBoostType() const = 0; /** @copybrief getBoostType @see getBoostType */ CV_WRAP virtual void setBoostType(int val) = 0; /** The number of weak classifiers. Default value is 100. */ /** @see setWeakCount */ CV_WRAP virtual int getWeakCount() const = 0; /** @copybrief getWeakCount @see getWeakCount */ CV_WRAP virtual void setWeakCount(int val) = 0; /** A threshold between 0 and 1 used to save computational time. Samples with summary weight \f$\leq 1 - weight_trim_rate\f$ do not participate in the *next* iteration of training. Set this parameter to 0 to turn off this functionality. Default value is 0.95.*/ /** @see setWeightTrimRate */ CV_WRAP virtual double getWeightTrimRate() const = 0; /** @copybrief getWeightTrimRate @see getWeightTrimRate */ CV_WRAP virtual void setWeightTrimRate(double val) = 0; /** Boosting type. Gentle AdaBoost and Real AdaBoost are often the preferable choices. */ enum Types { DISCRETE=0, //!< Discrete AdaBoost. REAL=1, //!< Real AdaBoost. It is a technique that utilizes confidence-rated predictions //!< and works well with categorical data. LOGIT=2, //!< LogitBoost. It can produce good regression fits. GENTLE=3 //!< Gentle AdaBoost. It puts less weight on outlier data points and for that //!(filename) to load the pre-trained model. */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Gradient Boosted Trees * \****************************************************************************************/ /*class CV_EXPORTS_W GBTrees : public DTrees { public: struct CV_EXPORTS_W_MAP Params : public DTrees::Params { CV_PROP_RW int weakCount; CV_PROP_RW int lossFunctionType; CV_PROP_RW float subsamplePortion; CV_PROP_RW float shrinkage; Params(); Params( int lossFunctionType, int weakCount, float shrinkage, float subsamplePortion, int maxDepth, bool useSurrogates ); }; enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS}; virtual void setK(int k) = 0; virtual float predictSerial( InputArray samples, OutputArray weakResponses, int flags) const = 0; static Ptr create(const Params& p); };*/ /****************************************************************************************\ * Artificial Neural Networks (ANN) * \****************************************************************************************/ /////////////////////////////////// Multi-Layer Perceptrons ////////////////////////////// /** @brief Artificial Neural Networks - Multi-Layer Perceptrons. Unlike many other models in ML that are constructed and trained at once, in the MLP model these steps are separated. First, a network with the specified topology is created using the non-default constructor or the method ANN_MLP::create. All the weights are set to zeros. Then, the network is trained using a set of input and output vectors. The training procedure can be repeated more than once, that is, the weights can be adjusted based on the new training data. Additional flags for StatModel::train are available: ANN_MLP::TrainFlags. @sa @ref ml_intro_ann */ class CV_EXPORTS_W ANN_MLP : public StatModel { public: /** Available training methods */ enum TrainingMethods { BACKPROP=0, //!< The back-propagation algorithm. RPROP=1 //!< The RPROP algorithm. See @cite RPROP93 for details. }; /** Sets training method and common parameters. @param method Default value is ANN_MLP::RPROP. See ANN_MLP::TrainingMethods. @param param1 passed to setRpropDW0 for ANN_MLP::RPROP and to setBackpropWeightScale for ANN_MLP::BACKPROP @param param2 passed to setRpropDWMin for ANN_MLP::RPROP and to setBackpropMomentumScale for ANN_MLP::BACKPROP. */ CV_WRAP virtual void setTrainMethod(int method, double param1 = 0, double param2 = 0) = 0; /** Returns current training method */ CV_WRAP virtual int getTrainMethod() const = 0; /** Initialize the activation function for each neuron. Currently the default and the only fully supported activation function is ANN_MLP::SIGMOID_SYM. @param type The type of activation function. See ANN_MLP::ActivationFunctions. @param param1 The first parameter of the activation function, \f$\alpha\f$. Default value is 0. @param param2 The second parameter of the activation function, \f$\beta\f$. Default value is 0. */ CV_WRAP virtual void setActivationFunction(int type, double param1 = 0, double param2 = 0) = 0; /** Integer vector specifying the number of neurons in each layer including the input and output layers. The very first element specifies the number of elements in the input layer. The last element - number of elements in the output layer. Default value is empty Mat. @sa getLayerSizes */ CV_WRAP virtual void setLayerSizes(InputArray _layer_sizes) = 0; /** Integer vector specifying the number of neurons in each layer including the input and output layers. The very first element specifies the number of elements in the input layer. The last element - number of elements in the output layer. @sa setLayerSizes */ CV_WRAP virtual cv::Mat getLayerSizes() const = 0; /** Termination criteria of the training algorithm. You can specify the maximum number of iterations (maxCount) and/or how much the error could change between the iterations to make the algorithm continue (epsilon). Default value is TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.01).*/ /** @see setTermCriteria */ CV_WRAP virtual TermCriteria getTermCriteria() const = 0; /** @copybrief getTermCriteria @see getTermCriteria */ CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; /** BPROP: Strength of the weight gradient term. The recommended value is about 0.1. Default value is 0.1.*/ /** @see setBackpropWeightScale */ CV_WRAP virtual double getBackpropWeightScale() const = 0; /** @copybrief getBackpropWeightScale @see getBackpropWeightScale */ CV_WRAP virtual void setBackpropWeightScale(double val) = 0; /** BPROP: Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough. Default value is 0.1.*/ /** @see setBackpropMomentumScale */ CV_WRAP virtual double getBackpropMomentumScale() const = 0; /** @copybrief getBackpropMomentumScale @see getBackpropMomentumScale */ CV_WRAP virtual void setBackpropMomentumScale(double val) = 0; /** RPROP: Initial value \f$\Delta_0\f$ of update-values \f$\Delta_{ij}\f$. Default value is 0.1.*/ /** @see setRpropDW0 */ CV_WRAP virtual double getRpropDW0() const = 0; /** @copybrief getRpropDW0 @see getRpropDW0 */ CV_WRAP virtual void setRpropDW0(double val) = 0; /** RPROP: Increase factor \f$\eta^+\f$. It must be \>1. Default value is 1.2.*/ /** @see setRpropDWPlus */ CV_WRAP virtual double getRpropDWPlus() const = 0; /** @copybrief getRpropDWPlus @see getRpropDWPlus */ CV_WRAP virtual void setRpropDWPlus(double val) = 0; /** RPROP: Decrease factor \f$\eta^-\f$. It must be \<1. Default value is 0.5.*/ /** @see setRpropDWMinus */ CV_WRAP virtual double getRpropDWMinus() const = 0; /** @copybrief getRpropDWMinus @see getRpropDWMinus */ CV_WRAP virtual void setRpropDWMinus(double val) = 0; /** RPROP: Update-values lower limit \f$\Delta_{min}\f$. It must be positive. Default value is FLT_EPSILON.*/ /** @see setRpropDWMin */ CV_WRAP virtual double getRpropDWMin() const = 0; /** @copybrief getRpropDWMin @see getRpropDWMin */ CV_WRAP virtual void setRpropDWMin(double val) = 0; /** RPROP: Update-values upper limit \f$\Delta_{max}\f$. It must be \>1. Default value is 50.*/ /** @see setRpropDWMax */ CV_WRAP virtual double getRpropDWMax() const = 0; /** @copybrief getRpropDWMax @see getRpropDWMax */ CV_WRAP virtual void setRpropDWMax(double val) = 0; /** possible activation functions */ enum ActivationFunctions { /** Identity function: \f$f(x)=x\f$ */ IDENTITY = 0, /** Symmetrical sigmoid: \f$f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x}\f$ @note If you are using the default sigmoid activation function with the default parameter values fparam1=0 and fparam2=0 then the function used is y = 1.7159\*tanh(2/3 \* x), so the output will range from [-1.7159, 1.7159], instead of [0,1].*/ SIGMOID_SYM = 1, /** Gaussian function: \f$f(x)=\beta e^{-\alpha x*x}\f$ */ GAUSSIAN = 2 }; /** Train options */ enum TrainFlags { /** Update the network weights, rather than compute them from scratch. In the latter case the weights are initialized using the Nguyen-Widrow algorithm. */ UPDATE_WEIGHTS = 1, /** Do not normalize the input vectors. If this flag is not set, the training algorithm normalizes each input feature independently, shifting its mean value to 0 and making the standard deviation equal to 1. If the network is assumed to be updated frequently, the new training data could be much different from original one. In this case, you should take care of proper normalization. */ NO_INPUT_SCALE = 2, /** Do not normalize the output vectors. If the flag is not set, the training algorithm normalizes each output feature independently, by transforming it to the certain range depending on the used activation function. */ NO_OUTPUT_SCALE = 4 }; CV_WRAP virtual Mat getWeights(int layerIdx) const = 0; /** @brief Creates empty model Use StatModel::train to train the model, Algorithm::load\(filename) to load the pre-trained model. Note that the train method has optional flags: ANN_MLP::TrainFlags. */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Logistic Regression * \****************************************************************************************/ /** @brief Implements Logistic Regression classifier. @sa @ref ml_intro_lr */ class CV_EXPORTS_W LogisticRegression : public StatModel { public: /** Learning rate. */ /** @see setLearningRate */ CV_WRAP virtual double getLearningRate() const = 0; /** @copybrief getLearningRate @see getLearningRate */ CV_WRAP virtual void setLearningRate(double val) = 0; /** Number of iterations. */ /** @see setIterations */ CV_WRAP virtual int getIterations() const = 0; /** @copybrief getIterations @see getIterations */ CV_WRAP virtual void setIterations(int val) = 0; /** Kind of regularization to be applied. See LogisticRegression::RegKinds. */ /** @see setRegularization */ CV_WRAP virtual int getRegularization() const = 0; /** @copybrief getRegularization @see getRegularization */ CV_WRAP virtual void setRegularization(int val) = 0; /** Kind of training method used. See LogisticRegression::Methods. */ /** @see setTrainMethod */ CV_WRAP virtual int getTrainMethod() const = 0; /** @copybrief getTrainMethod @see getTrainMethod */ CV_WRAP virtual void setTrainMethod(int val) = 0; /** Specifies the number of training samples taken in each step of Mini-Batch Gradient Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. It has to take values less than the total number of training samples. */ /** @see setMiniBatchSize */ CV_WRAP virtual int getMiniBatchSize() const = 0; /** @copybrief getMiniBatchSize @see getMiniBatchSize */ CV_WRAP virtual void setMiniBatchSize(int val) = 0; /** Termination criteria of the algorithm. */ /** @see setTermCriteria */ CV_WRAP virtual TermCriteria getTermCriteria() const = 0; /** @copybrief getTermCriteria @see getTermCriteria */ CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; //! Regularization kinds enum RegKinds { REG_DISABLE = -1, //!< Regularization disabled REG_L1 = 0, //!< %L1 norm REG_L2 = 1 //!< %L2 norm }; //! Training methods enum Methods { BATCH = 0, MINI_BATCH = 1 //!< Set MiniBatchSize to a positive integer when using this method. }; /** @brief Predicts responses for input samples and returns a float type. @param samples The input data for the prediction algorithm. Matrix [m x n], where each row contains variables (features) of one object being classified. Should have data type CV_32F. @param results Predicted labels as a column matrix of type CV_32S. @param flags Not used. */ CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0; /** @brief This function returns the trained paramters arranged across rows. For a two class classifcation problem, it returns a row matrix. It returns learnt paramters of the Logistic Regression as a matrix of type CV_32F. */ CV_WRAP virtual Mat get_learnt_thetas() const = 0; /** @brief Creates empty model. Creates Logistic Regression model with parameters given. */ CV_WRAP static Ptr create(); }; /****************************************************************************************\ * Auxilary functions declarations * \****************************************************************************************/ /** @brief Generates _sample_ from multivariate normal distribution @param mean an average row vector @param cov symmetric covariation matrix @param nsamples returned samples count @param samples returned samples array */ CV_EXPORTS void randMVNormal( InputArray mean, InputArray cov, int nsamples, OutputArray samples); /** @brief Creates test set */ CV_EXPORTS void createConcentricSpheresTestSet( int nsamples, int nfeatures, int nclasses, OutputArray samples, OutputArray responses); //! @} ml } } #endif // __cplusplus #endif // __OPENCV_ML_HPP__ /* End of file. */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/objdetect/detection_based_tracker.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OBJDETECT_DBT_HPP__ #define __OPENCV_OBJDETECT_DBT_HPP__ // After this condition removal update blacklist for bindings: modules/python/common.cmake #if defined(__linux__) || defined(LINUX) || defined(__APPLE__) || defined(__ANDROID__) || \ (defined(__cplusplus) && __cplusplus > 201103L) || (defined(_MSC_VER) && _MSC_VER >= 1700) #include namespace cv { //! @addtogroup objdetect //! @{ class CV_EXPORTS DetectionBasedTracker { public: struct Parameters { int maxTrackLifetime; int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0 Parameters(); }; class IDetector { public: IDetector(): minObjSize(96, 96), maxObjSize(INT_MAX, INT_MAX), minNeighbours(2), scaleFactor(1.1f) {} virtual void detect(const cv::Mat& image, std::vector& objects) = 0; void setMinObjectSize(const cv::Size& min) { minObjSize = min; } void setMaxObjectSize(const cv::Size& max) { maxObjSize = max; } cv::Size getMinObjectSize() const { return minObjSize; } cv::Size getMaxObjectSize() const { return maxObjSize; } float getScaleFactor() { return scaleFactor; } void setScaleFactor(float value) { scaleFactor = value; } int getMinNeighbours() { return minNeighbours; } void setMinNeighbours(int value) { minNeighbours = value; } virtual ~IDetector() {} protected: cv::Size minObjSize; cv::Size maxObjSize; int minNeighbours; float scaleFactor; }; DetectionBasedTracker(cv::Ptr mainDetector, cv::Ptr trackingDetector, const Parameters& params); virtual ~DetectionBasedTracker(); virtual bool run(); virtual void stop(); virtual void resetTracking(); virtual void process(const cv::Mat& imageGray); bool setParameters(const Parameters& params); const Parameters& getParameters() const; typedef std::pair Object; virtual void getObjects(std::vector& result) const; virtual void getObjects(std::vector& result) const; enum ObjectStatus { DETECTED_NOT_SHOWN_YET, DETECTED, DETECTED_TEMPORARY_LOST, WRONG_OBJECT }; struct ExtObject { int id; cv::Rect location; ObjectStatus status; ExtObject(int _id, cv::Rect _location, ObjectStatus _status) :id(_id), location(_location), status(_status) { } }; virtual void getObjects(std::vector& result) const; virtual int addObject(const cv::Rect& location); //returns id of the new object protected: class SeparateDetectionWork; cv::Ptr separateDetectionWork; friend void* workcycleObjectDetectorFunction(void* p); struct InnerParameters { int numLastPositionsToTrack; int numStepsToWaitBeforeFirstShow; int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown; int numStepsToShowWithoutDetecting; float coeffTrackingWindowSize; float coeffObjectSizeToTrack; float coeffObjectSpeedUsingInPrediction; InnerParameters(); }; Parameters parameters; InnerParameters innerParameters; struct TrackedObject { typedef std::vector PositionsVector; PositionsVector lastPositions; int numDetectedFrames; int numFramesNotDetected; int id; TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0) { lastPositions.push_back(rect); id=getNextId(); }; static int getNextId() { static int _id=0; return _id++; } }; int numTrackedSteps; std::vector trackedObjects; std::vector weightsPositionsSmoothing; std::vector weightsSizesSmoothing; cv::Ptr cascadeForTracking; void updateTrackedObjects(const std::vector& detectedObjects); cv::Rect calcTrackedObjectPositionToShow(int i) const; cv::Rect calcTrackedObjectPositionToShow(int i, ObjectStatus& status) const; void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector& detectedObjectsInRegions); }; //! @} objdetect } //end of cv namespace #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/objdetect/objdetect.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/objdetect.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/objdetect/objdetect_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OBJDETECT_C_H__ #define __OPENCV_OBJDETECT_C_H__ #include "opencv2/core/core_c.h" #ifdef __cplusplus #include #include extern "C" { #endif /** @addtogroup objdetect_c @{ */ /****************************************************************************************\ * Haar-like Object Detection functions * \****************************************************************************************/ #define CV_HAAR_MAGIC_VAL 0x42500000 #define CV_TYPE_NAME_HAAR "opencv-haar-classifier" #define CV_IS_HAAR_CLASSIFIER( haar ) \ ((haar) != NULL && \ (((const CvHaarClassifierCascade*)(haar))->flags & CV_MAGIC_MASK)==CV_HAAR_MAGIC_VAL) #define CV_HAAR_FEATURE_MAX 3 typedef struct CvHaarFeature { int tilted; struct { CvRect r; float weight; } rect[CV_HAAR_FEATURE_MAX]; } CvHaarFeature; typedef struct CvHaarClassifier { int count; CvHaarFeature* haar_feature; float* threshold; int* left; int* right; float* alpha; } CvHaarClassifier; typedef struct CvHaarStageClassifier { int count; float threshold; CvHaarClassifier* classifier; int next; int child; int parent; } CvHaarStageClassifier; typedef struct CvHidHaarClassifierCascade CvHidHaarClassifierCascade; typedef struct CvHaarClassifierCascade { int flags; int count; CvSize orig_window_size; CvSize real_window_size; double scale; CvHaarStageClassifier* stage_classifier; CvHidHaarClassifierCascade* hid_cascade; } CvHaarClassifierCascade; typedef struct CvAvgComp { CvRect rect; int neighbors; } CvAvgComp; /* Loads haar classifier cascade from a directory. It is obsolete: convert your cascade to xml and use cvLoad instead */ CVAPI(CvHaarClassifierCascade*) cvLoadHaarClassifierCascade( const char* directory, CvSize orig_window_size); CVAPI(void) cvReleaseHaarClassifierCascade( CvHaarClassifierCascade** cascade ); #define CV_HAAR_DO_CANNY_PRUNING 1 #define CV_HAAR_SCALE_IMAGE 2 #define CV_HAAR_FIND_BIGGEST_OBJECT 4 #define CV_HAAR_DO_ROUGH_SEARCH 8 CVAPI(CvSeq*) cvHaarDetectObjects( const CvArr* image, CvHaarClassifierCascade* cascade, CvMemStorage* storage, double scale_factor CV_DEFAULT(1.1), int min_neighbors CV_DEFAULT(3), int flags CV_DEFAULT(0), CvSize min_size CV_DEFAULT(cvSize(0,0)), CvSize max_size CV_DEFAULT(cvSize(0,0))); /* sets images for haar classifier cascade */ CVAPI(void) cvSetImagesForHaarClassifierCascade( CvHaarClassifierCascade* cascade, const CvArr* sum, const CvArr* sqsum, const CvArr* tilted_sum, double scale ); /* runs the cascade on the specified window */ CVAPI(int) cvRunHaarClassifierCascade( const CvHaarClassifierCascade* cascade, CvPoint pt, int start_stage CV_DEFAULT(0)); /** @} objdetect_c */ #ifdef __cplusplus } CV_EXPORTS CvSeq* cvHaarDetectObjectsForROC( const CvArr* image, CvHaarClassifierCascade* cascade, CvMemStorage* storage, std::vector& rejectLevels, std::vector& levelWeightds, double scale_factor = 1.1, int min_neighbors = 3, int flags = 0, CvSize min_size = cvSize(0, 0), CvSize max_size = cvSize(0, 0), bool outputRejectLevels = false ); #endif #endif /* __OPENCV_OBJDETECT_C_H__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/objdetect.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OBJDETECT_HPP__ #define __OPENCV_OBJDETECT_HPP__ #include "opencv2/core.hpp" /** @defgroup objdetect Object Detection Haar Feature-based Cascade Classifier for Object Detection ---------------------------------------------------------- The object detector described below has been initially proposed by Paul Viola @cite Viola01 and improved by Rainer Lienhart @cite Lienhart02 . First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is trained with a few hundred sample views of a particular object (i.e., a face or a car), called positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary images of the same size. After a classifier is trained, it can be applied to a region of interest (of the same size as used during the training) in an input image. The classifier outputs a "1" if the region is likely to show the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can move the search window across the image and check every location using the classifier. The classifier is designed so that it can be easily "resized" in order to be able to find the objects of interest at different sizes, which is more efficient than resizing the image itself. So, to find an object of an unknown size in the image the scan procedure should be done several times at different scales. The word "cascade" in the classifier name means that the resultant classifier consists of several simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some stage the candidate is rejected or all the stages are passed. The word "boosted" means that the classifiers at every stage of the cascade are complex themselves and they are built out of basic classifiers using one of four different boosting techniques (weighted voting). Currently Discrete Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic classifiers, and are calculated as described below. The current algorithm uses the following Haar-like features: ![image](pics/haarfeatures.png) The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within the region of interest and the scale (this scale is not the same as the scale used at the detection stage, though these two scales are multiplied). For example, in the case of the third line feature (2c) the response is calculated as the difference between the sum of image pixels under the rectangle covering the whole feature (including the two white stripes and the black stripe in the middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to compensate for the differences in the size of areas. The sums of pixel values over a rectangular regions are calculated rapidly using integral images (see below and the integral description). To see the object detector at work, have a look at the facedetect demo: The following reference is for the detection part only. There is a separate application called opencv_traincascade that can train a cascade of boosted classifiers from a set of samples. @note In the new C++ interface it is also possible to use LBP (local binary pattern) features in addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at @{ @defgroup objdetect_c C API @} */ typedef struct CvHaarClassifierCascade CvHaarClassifierCascade; namespace cv { //! @addtogroup objdetect //! @{ ///////////////////////////// Object Detection //////////////////////////// //! class for grouping object candidates, detected by Cascade Classifier, HOG etc. //! instance of the class is to be passed to cv::partition (see cxoperations.hpp) class CV_EXPORTS SimilarRects { public: SimilarRects(double _eps) : eps(_eps) {} inline bool operator()(const Rect& r1, const Rect& r2) const { double delta = eps*(std::min(r1.width, r2.width) + std::min(r1.height, r2.height))*0.5; return std::abs(r1.x - r2.x) <= delta && std::abs(r1.y - r2.y) <= delta && std::abs(r1.x + r1.width - r2.x - r2.width) <= delta && std::abs(r1.y + r1.height - r2.y - r2.height) <= delta; } double eps; }; /** @brief Groups the object candidate rectangles. @param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.) @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. @param eps Relative difference between sides of the rectangles to merge them into a group. The function is a wrapper for the generic function partition . It clusters all the input rectangles using the rectangle equivalence criteria that combines rectangles with similar sizes and similar locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If \f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small clusters containing less than or equal to groupThreshold rectangles are rejected. In each other cluster, the average rectangle is computed and put into the output rectangle list. */ CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, double eps = 0.2); /** @overload */ CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector& rectList, CV_OUT std::vector& weights, int groupThreshold, double eps = 0.2); /** @overload */ CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, double eps, std::vector* weights, std::vector* levelWeights ); /** @overload */ CV_EXPORTS void groupRectangles(std::vector& rectList, std::vector& rejectLevels, std::vector& levelWeights, int groupThreshold, double eps = 0.2); /** @overload */ CV_EXPORTS void groupRectangles_meanshift(std::vector& rectList, std::vector& foundWeights, std::vector& foundScales, double detectThreshold = 0.0, Size winDetSize = Size(64, 128)); template<> CV_EXPORTS void DefaultDeleter::operator ()(CvHaarClassifierCascade* obj) const; enum { CASCADE_DO_CANNY_PRUNING = 1, CASCADE_SCALE_IMAGE = 2, CASCADE_FIND_BIGGEST_OBJECT = 4, CASCADE_DO_ROUGH_SEARCH = 8 }; class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm { public: virtual ~BaseCascadeClassifier(); virtual bool empty() const = 0; virtual bool load( const String& filename ) = 0; virtual void detectMultiScale( InputArray image, CV_OUT std::vector& objects, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize ) = 0; virtual void detectMultiScale( InputArray image, CV_OUT std::vector& objects, CV_OUT std::vector& numDetections, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize ) = 0; virtual void detectMultiScale( InputArray image, CV_OUT std::vector& objects, CV_OUT std::vector& rejectLevels, CV_OUT std::vector& levelWeights, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize, bool outputRejectLevels ) = 0; virtual bool isOldFormatCascade() const = 0; virtual Size getOriginalWindowSize() const = 0; virtual int getFeatureType() const = 0; virtual void* getOldCascade() = 0; class CV_EXPORTS MaskGenerator { public: virtual ~MaskGenerator() {} virtual Mat generateMask(const Mat& src)=0; virtual void initializeMask(const Mat& /*src*/) { } }; virtual void setMaskGenerator(const Ptr& maskGenerator) = 0; virtual Ptr getMaskGenerator() = 0; }; /** @brief Cascade classifier class for object detection. */ class CV_EXPORTS_W CascadeClassifier { public: CV_WRAP CascadeClassifier(); /** @brief Loads a classifier from a file. @param filename Name of the file from which the classifier is loaded. */ CV_WRAP CascadeClassifier(const String& filename); ~CascadeClassifier(); /** @brief Checks whether the classifier has been loaded. */ CV_WRAP bool empty() const; /** @brief Loads a classifier from a file. @param filename Name of the file from which the classifier is loaded. The file may contain an old HAAR classifier trained by the haartraining application or a new cascade classifier trained by the traincascade application. */ CV_WRAP bool load( const String& filename ); /** @brief Reads a classifier from a FileStorage node. @note The file may contain a new cascade classifier (trained traincascade application) only. */ CV_WRAP bool read( const FileNode& node ); /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles. @param image Matrix of the type CV_8U containing an image where objects are detected. @param objects Vector of rectangles where each rectangle contains the detected object, the rectangles may be partially outside the original image. @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have to retain it. @param flags Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. It is not used for a new cascade. @param minSize Minimum possible object size. Objects smaller than that are ignored. @param maxSize Maximum possible object size. Objects larger than that are ignored. The function is parallelized with the TBB library. @note - (Python) A face detection example using cascade classifiers can be found at opencv_source_code/samples/python/facedetect.py */ CV_WRAP void detectMultiScale( InputArray image, CV_OUT std::vector& objects, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size() ); /** @overload @param image Matrix of the type CV_8U containing an image where objects are detected. @param objects Vector of rectangles where each rectangle contains the detected object, the rectangles may be partially outside the original image. @param numDetections Vector of detection numbers for the corresponding objects. An object's number of detections is the number of neighboring positively classified rectangles that were joined together to form the object. @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have to retain it. @param flags Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. It is not used for a new cascade. @param minSize Minimum possible object size. Objects smaller than that are ignored. @param maxSize Maximum possible object size. Objects larger than that are ignored. */ CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image, CV_OUT std::vector& objects, CV_OUT std::vector& numDetections, double scaleFactor=1.1, int minNeighbors=3, int flags=0, Size minSize=Size(), Size maxSize=Size() ); /** @overload if `outputRejectLevels` is `true` returns `rejectLevels` and `levelWeights` */ CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image, CV_OUT std::vector& objects, CV_OUT std::vector& rejectLevels, CV_OUT std::vector& levelWeights, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size(), bool outputRejectLevels = false ); CV_WRAP bool isOldFormatCascade() const; CV_WRAP Size getOriginalWindowSize() const; CV_WRAP int getFeatureType() const; void* getOldCascade(); CV_WRAP static bool convert(const String& oldcascade, const String& newcascade); void setMaskGenerator(const Ptr& maskGenerator); Ptr getMaskGenerator(); Ptr cc; }; CV_EXPORTS Ptr createFaceDetectionMaskGenerator(); //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// //! struct for detection region of interest (ROI) struct DetectionROI { //! scale(size) of the bounding box double scale; //! set of requrested locations to be evaluated std::vector locations; //! vector that will contain confidence values for each location std::vector confidences; }; struct CV_EXPORTS_W HOGDescriptor { public: enum { L2Hys = 0 }; enum { DEFAULT_NLEVELS = 64 }; CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8), cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false) {} CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride, Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1, int _histogramNormType=HOGDescriptor::L2Hys, double _L2HysThreshold=0.2, bool _gammaCorrection=false, int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false) : winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize), nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma), histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold), gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient) {} CV_WRAP HOGDescriptor(const String& filename) { load(filename); } HOGDescriptor(const HOGDescriptor& d) { d.copyTo(*this); } virtual ~HOGDescriptor() {} CV_WRAP size_t getDescriptorSize() const; CV_WRAP bool checkDetectorSize() const; CV_WRAP double getWinSigma() const; CV_WRAP virtual void setSVMDetector(InputArray _svmdetector); virtual bool read(FileNode& fn); virtual void write(FileStorage& fs, const String& objname) const; CV_WRAP virtual bool load(const String& filename, const String& objname = String()); CV_WRAP virtual void save(const String& filename, const String& objname = String()) const; virtual void copyTo(HOGDescriptor& c) const; CV_WRAP virtual void compute(InputArray img, CV_OUT std::vector& descriptors, Size winStride = Size(), Size padding = Size(), const std::vector& locations = std::vector()) const; //! with found weights output CV_WRAP virtual void detect(const Mat& img, CV_OUT std::vector& foundLocations, CV_OUT std::vector& weights, double hitThreshold = 0, Size winStride = Size(), Size padding = Size(), const std::vector& searchLocations = std::vector()) const; //! without found weights output virtual void detect(const Mat& img, CV_OUT std::vector& foundLocations, double hitThreshold = 0, Size winStride = Size(), Size padding = Size(), const std::vector& searchLocations=std::vector()) const; //! with result weights output CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, CV_OUT std::vector& foundWeights, double hitThreshold = 0, Size winStride = Size(), Size padding = Size(), double scale = 1.05, double finalThreshold = 2.0,bool useMeanshiftGrouping = false) const; //! without found weights output virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, double hitThreshold = 0, Size winStride = Size(), Size padding = Size(), double scale = 1.05, double finalThreshold = 2.0, bool useMeanshiftGrouping = false) const; CV_WRAP virtual void computeGradient(const Mat& img, CV_OUT Mat& grad, CV_OUT Mat& angleOfs, Size paddingTL = Size(), Size paddingBR = Size()) const; CV_WRAP static std::vector getDefaultPeopleDetector(); CV_WRAP static std::vector getDaimlerPeopleDetector(); CV_PROP Size winSize; CV_PROP Size blockSize; CV_PROP Size blockStride; CV_PROP Size cellSize; CV_PROP int nbins; CV_PROP int derivAperture; CV_PROP double winSigma; CV_PROP int histogramNormType; CV_PROP double L2HysThreshold; CV_PROP bool gammaCorrection; CV_PROP std::vector svmDetector; UMat oclSvmDetector; float free_coef; CV_PROP int nlevels; CV_PROP bool signedGradient; //! evaluate specified ROI and return confidence value for each location virtual void detectROI(const cv::Mat& img, const std::vector &locations, CV_OUT std::vector& foundLocations, CV_OUT std::vector& confidences, double hitThreshold = 0, cv::Size winStride = Size(), cv::Size padding = Size()) const; //! evaluate specified ROI and return confidence value for each location in multiple scales virtual void detectMultiScaleROI(const cv::Mat& img, CV_OUT std::vector& foundLocations, std::vector& locations, double hitThreshold = 0, int groupThreshold = 0) const; //! read/parse Dalal's alt model file void readALTModel(String modelfile); void groupRectangles(std::vector& rectList, std::vector& weights, int groupThreshold, double eps) const; }; //! @} objdetect } #include "opencv2/objdetect/detection_based_tracker.hpp" #ifndef DISABLE_OPENCV_24_COMPATIBILITY #include "opencv2/objdetect/objdetect_c.h" #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/opencv.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_ALL_HPP__ #define __OPENCV_ALL_HPP__ #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/photo.hpp" #include "opencv2/video.hpp" #include "opencv2/features2d.hpp" #include "opencv2/objdetect.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/ml.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/opencv_modules.hpp ================================================ /* * ** File generated automatically, do not modify ** * * This file defines the list of modules available in current build configuration * * */ #define HAVE_OPENCV_ARUCO #define HAVE_OPENCV_BGSEGM #define HAVE_OPENCV_BIOINSPIRED #define HAVE_OPENCV_CALIB3D #define HAVE_OPENCV_CCALIB #define HAVE_OPENCV_CORE #define HAVE_OPENCV_DATASETS #define HAVE_OPENCV_DNN #define HAVE_OPENCV_DPM #define HAVE_OPENCV_FACE #define HAVE_OPENCV_FEATURES2D #define HAVE_OPENCV_FLANN #define HAVE_OPENCV_FUZZY #define HAVE_OPENCV_HIGHGUI #define HAVE_OPENCV_IMGCODECS #define HAVE_OPENCV_IMGPROC #define HAVE_OPENCV_LINE_DESCRIPTOR #define HAVE_OPENCV_ML #define HAVE_OPENCV_OBJDETECT #define HAVE_OPENCV_OPTFLOW #define HAVE_OPENCV_PHOTO #define HAVE_OPENCV_PLOT #define HAVE_OPENCV_REG #define HAVE_OPENCV_RGBD #define HAVE_OPENCV_SALIENCY #define HAVE_OPENCV_SHAPE #define HAVE_OPENCV_STEREO #define HAVE_OPENCV_STITCHING #define HAVE_OPENCV_STRUCTURED_LIGHT #define HAVE_OPENCV_SUPERRES #define HAVE_OPENCV_SURFACE_MATCHING #define HAVE_OPENCV_TEXT #define HAVE_OPENCV_TRACKING #define HAVE_OPENCV_VIDEO #define HAVE_OPENCV_VIDEOIO #define HAVE_OPENCV_VIDEOSTAB #define HAVE_OPENCV_XFEATURES2D #define HAVE_OPENCV_XIMGPROC #define HAVE_OPENCV_XOBJDETECT #define HAVE_OPENCV_XPHOTO ================================================ FILE: src/3rdparty/opencv/include/opencv2/optflow/motempl.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_OPTFLOW_MOTEMPL_HPP__ #define __OPENCV_OPTFLOW_MOTEMPL_HPP__ #include "opencv2/core.hpp" namespace cv { namespace motempl { //! @addtogroup optflow //! @{ /** @brief Updates the motion history image by a moving silhouette. @param silhouette Silhouette mask that has non-zero pixels where the motion occurs. @param mhi Motion history image that is updated by the function (single-channel, 32-bit floating-point). @param timestamp Current time in milliseconds or other units. @param duration Maximal duration of the motion track in the same units as timestamp . The function updates the motion history image as follows: \f[\texttt{mhi} (x,y)= \forkthree{\texttt{timestamp}}{if \(\texttt{silhouette}(x,y) \ne 0\)}{0}{if \(\texttt{silhouette}(x,y) = 0\) and \(\texttt{mhi} < (\texttt{timestamp} - \texttt{duration})\)}{\texttt{mhi}(x,y)}{otherwise}\f] That is, MHI pixels where the motion occurs are set to the current timestamp , while the pixels where the motion happened last time a long time ago are cleared. The function, together with calcMotionGradient and calcGlobalOrientation , implements a motion templates technique described in @cite Davis97 and @cite Bradski00 . */ CV_EXPORTS_W void updateMotionHistory( InputArray silhouette, InputOutputArray mhi, double timestamp, double duration ); /** @brief Calculates a gradient orientation of a motion history image. @param mhi Motion history single-channel floating-point image. @param mask Output mask image that has the type CV_8UC1 and the same size as mhi . Its non-zero elements mark pixels where the motion gradient data is correct. @param orientation Output motion gradient orientation image that has the same type and the same size as mhi . Each pixel of the image is a motion orientation, from 0 to 360 degrees. @param delta1 Minimal (or maximal) allowed difference between mhi values within a pixel neighborhood. @param delta2 Maximal (or minimal) allowed difference between mhi values within a pixel neighborhood. That is, the function finds the minimum ( \f$m(x,y)\f$ ) and maximum ( \f$M(x,y)\f$ ) mhi values over \f$3 \times 3\f$ neighborhood of each pixel and marks the motion orientation at \f$(x, y)\f$ as valid only if \f[\min ( \texttt{delta1} , \texttt{delta2} ) \le M(x,y)-m(x,y) \le \max ( \texttt{delta1} , \texttt{delta2} ).\f] @param apertureSize Aperture size of the Sobel operator. The function calculates a gradient orientation at each pixel \f$(x, y)\f$ as: \f[\texttt{orientation} (x,y)= \arctan{\frac{d\texttt{mhi}/dy}{d\texttt{mhi}/dx}}\f] In fact, fastAtan2 and phase are used so that the computed angle is measured in degrees and covers the full range 0..360. Also, the mask is filled to indicate pixels where the computed angle is valid. @note - (Python) An example on how to perform a motion template technique can be found at opencv_source_code/samples/python2/motempl.py */ CV_EXPORTS_W void calcMotionGradient( InputArray mhi, OutputArray mask, OutputArray orientation, double delta1, double delta2, int apertureSize = 3 ); /** @brief Calculates a global motion orientation in a selected region. @param orientation Motion gradient orientation image calculated by the function calcMotionGradient @param mask Mask image. It may be a conjunction of a valid gradient mask, also calculated by calcMotionGradient , and the mask of a region whose direction needs to be calculated. @param mhi Motion history image calculated by updateMotionHistory . @param timestamp Timestamp passed to updateMotionHistory . @param duration Maximum duration of a motion track in milliseconds, passed to updateMotionHistory The function calculates an average motion direction in the selected region and returns the angle between 0 degrees and 360 degrees. The average direction is computed from the weighted orientation histogram, where a recent motion has a larger weight and the motion occurred in the past has a smaller weight, as recorded in mhi . */ CV_EXPORTS_W double calcGlobalOrientation( InputArray orientation, InputArray mask, InputArray mhi, double timestamp, double duration ); /** @brief Splits a motion history image into a few parts corresponding to separate independent motions (for example, left hand, right hand). @param mhi Motion history image. @param segmask Image where the found mask should be stored, single-channel, 32-bit floating-point. @param boundingRects Vector containing ROIs of motion connected components. @param timestamp Current time in milliseconds or other units. @param segThresh Segmentation threshold that is recommended to be equal to the interval between motion history "steps" or greater. The function finds all of the motion segments and marks them in segmask with individual values (1,2,...). It also computes a vector with ROIs of motion connected components. After that the motion direction for every component can be calculated with calcGlobalOrientation using the extracted mask of the particular component. */ CV_EXPORTS_W void segmentMotion( InputArray mhi, OutputArray segmask, CV_OUT std::vector& boundingRects, double timestamp, double segThresh ); //! @} } } #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/optflow.hpp ================================================ /* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_OPTFLOW_HPP__ #define __OPENCV_OPTFLOW_HPP__ #include "opencv2/core.hpp" #include "opencv2/video.hpp" /** @defgroup optflow Optical Flow Algorithms Dense optical flow algorithms compute motion for each point: - cv::optflow::calcOpticalFlowSF - cv::optflow::createOptFlow_DeepFlow Motion templates is alternative technique for detecting motion and computing its direction. See samples/motempl.py. - cv::motempl::updateMotionHistory - cv::motempl::calcMotionGradient - cv::motempl::calcGlobalOrientation - cv::motempl::segmentMotion Functions reading and writing .flo files in "Middlebury" format, see: - cv::optflow::readOpticalFlow - cv::optflow::writeOpticalFlow */ namespace cv { namespace optflow { //! @addtogroup optflow //! @{ /** @overload */ CV_EXPORTS_W void calcOpticalFlowSF( InputArray from, InputArray to, OutputArray flow, int layers, int averaging_block_size, int max_flow); /** @brief Calculate an optical flow using "SimpleFlow" algorithm. @param from First 8-bit 3-channel image. @param to Second 8-bit 3-channel image of the same size as prev @param flow computed flow image that has the same size as prev and type CV_32FC2 @param layers Number of layers @param averaging_block_size Size of block through which we sum up when calculate cost function for pixel @param max_flow maximal flow that we search at each level @param sigma_dist vector smooth spatial sigma parameter @param sigma_color vector smooth color sigma parameter @param postprocess_window window size for postprocess cross bilateral filter @param sigma_dist_fix spatial sigma for postprocess cross bilateralf filter @param sigma_color_fix color sigma for postprocess cross bilateral filter @param occ_thr threshold for detecting occlusions @param upscale_averaging_radius window size for bilateral upscale operation @param upscale_sigma_dist spatial sigma for bilateral upscale operation @param upscale_sigma_color color sigma for bilateral upscale operation @param speed_up_thr threshold to detect point with irregular flow - where flow should be recalculated after upscale See @cite Tao2012 . And site of project - . @note - An example using the simpleFlow algorithm can be found at samples/simpleflow_demo.cpp */ CV_EXPORTS_W void calcOpticalFlowSF( InputArray from, InputArray to, OutputArray flow, int layers, int averaging_block_size, int max_flow, double sigma_dist, double sigma_color, int postprocess_window, double sigma_dist_fix, double sigma_color_fix, double occ_thr, int upscale_averaging_radius, double upscale_sigma_dist, double upscale_sigma_color, double speed_up_thr ); /** @brief Fast dense optical flow based on PyrLK sparse matches interpolation. @param from first 8-bit 3-channel or 1-channel image. @param to second 8-bit 3-channel or 1-channel image of the same size as from @param flow computed flow image that has the same size as from and CV_32FC2 type @param grid_step stride used in sparse match computation. Lower values usually result in higher quality but slow down the algorithm. @param k number of nearest-neighbor matches considered, when fitting a locally affine model. Lower values can make the algorithm noticeably faster at the cost of some quality degradation. @param sigma parameter defining how fast the weights decrease in the locally-weighted affine fitting. Higher values can help preserve fine details, lower values can help to get rid of the noise in the output flow. @param use_post_proc defines whether the ximgproc::fastGlobalSmootherFilter() is used for post-processing after interpolation @param fgs_lambda see the respective parameter of the ximgproc::fastGlobalSmootherFilter() @param fgs_sigma see the respective parameter of the ximgproc::fastGlobalSmootherFilter() */ CV_EXPORTS_W void calcOpticalFlowSparseToDense ( InputArray from, InputArray to, OutputArray flow, int grid_step = 8, int k = 128, float sigma = 0.05f, bool use_post_proc = true, float fgs_lambda = 500.0f, float fgs_sigma = 1.5f ); /** @brief Read a .flo file @param path Path to the file to be loaded The function readOpticalFlow loads a flow field from a file and returns it as a single matrix. Resulting Mat has a type CV_32FC2 - floating-point, 2-channel. First channel corresponds to the flow in the horizontal direction (u), second - vertical (v). */ CV_EXPORTS_W Mat readOpticalFlow( const String& path ); /** @brief Write a .flo to disk @param path Path to the file to be written @param flow Flow field to be stored The function stores a flow field in a file, returns true on success, false otherwise. The flow field must be a 2-channel, floating-point matrix (CV_32FC2). First channel corresponds to the flow in the horizontal direction (u), second - vertical (v). */ CV_EXPORTS_W bool writeOpticalFlow( const String& path, InputArray flow ); /** @brief DeepFlow optical flow algorithm implementation. The class implements the DeepFlow optical flow algorithm described in @cite Weinzaepfel2013 . See also . Parameters - class fields - that may be modified after creating a class instance: - member float alpha Smoothness assumption weight - member float delta Color constancy assumption weight - member float gamma Gradient constancy weight - member float sigma Gaussian smoothing parameter - member int minSize Minimal dimension of an image in the pyramid (next, smaller images in the pyramid are generated until one of the dimensions reaches this size) - member float downscaleFactor Scaling factor in the image pyramid (must be \< 1) - member int fixedPointIterations How many iterations on each level of the pyramid - member int sorIterations Iterations of Succesive Over-Relaxation (solver) - member float omega Relaxation factor in SOR */ CV_EXPORTS_W Ptr createOptFlow_DeepFlow(); //! Additional interface to the SimpleFlow algorithm - calcOpticalFlowSF() CV_EXPORTS_W Ptr createOptFlow_SimpleFlow(); //! Additional interface to the Farneback's algorithm - calcOpticalFlowFarneback() CV_EXPORTS_W Ptr createOptFlow_Farneback(); //! Additional interface to the SparseToDenseFlow algorithm - calcOpticalFlowSparseToDense() CV_EXPORTS_W Ptr createOptFlow_SparseToDense(); //! @} } //optflow } #include "opencv2/optflow/motempl.hpp" #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/photo/cuda.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_PHOTO_CUDA_HPP__ #define __OPENCV_PHOTO_CUDA_HPP__ #include "opencv2/core/cuda.hpp" namespace cv { namespace cuda { //! @addtogroup photo_denoise //! @{ /** @brief Performs pure non local means denoising without any simplification, and thus it is not fast. @param src Source image. Supports only CV_8UC1, CV_8UC2 and CV_8UC3. @param dst Destination image. @param h Filter sigma regulating filter strength for color. @param search_window Size of search window. @param block_size Size of block used for computing weights. @param borderMode Border type. See borderInterpolate for details. BORDER_REFLECT101 , BORDER_REPLICATE , BORDER_CONSTANT , BORDER_REFLECT and BORDER_WRAP are supported for now. @param stream Stream for the asynchronous version. @sa fastNlMeansDenoising */ CV_EXPORTS void nonLocalMeans(InputArray src, OutputArray dst, float h, int search_window = 21, int block_size = 7, int borderMode = BORDER_DEFAULT, Stream& stream = Stream::Null()); /** @brief Perform image denoising using Non-local Means Denoising algorithm with several computational optimizations. Noise expected to be a gaussian white noise @param src Input 8-bit 1-channel, 2-channel or 3-channel image. @param dst Output image with the same size and type as src . @param h Parameter regulating filter strength. Big h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise @param search_window Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater search_window - greater denoising time. Recommended value 21 pixels @param block_size Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param stream Stream for the asynchronous invocations. This function expected to be applied to grayscale images. For colored images look at FastNonLocalMeansDenoising::labMethod. @sa fastNlMeansDenoising */ CV_EXPORTS void fastNlMeansDenoising(InputArray src, OutputArray dst, float h, int search_window = 21, int block_size = 7, Stream& stream = Stream::Null()); /** @brief Modification of fastNlMeansDenoising function for colored images @param src Input 8-bit 3-channel image. @param dst Output image with the same size and type as src . @param h_luminance Parameter regulating filter strength. Big h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise @param photo_render float The same as h but for color components. For most images value equals 10 will be enough to remove colored noise and do not distort colors @param search_window Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater search_window - greater denoising time. Recommended value 21 pixels @param block_size Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param stream Stream for the asynchronous invocations. The function converts image to CIELAB colorspace and then separately denoise L and AB components with given h parameters using FastNonLocalMeansDenoising::simpleMethod function. @sa fastNlMeansDenoisingColored */ CV_EXPORTS void fastNlMeansDenoisingColored(InputArray src, OutputArray dst, float h_luminance, float photo_render, int search_window = 21, int block_size = 7, Stream& stream = Stream::Null()); //! @} photo }} // namespace cv { namespace cuda { #endif /* __OPENCV_PHOTO_CUDA_HPP__ */ ================================================ FILE: src/3rdparty/opencv/include/opencv2/photo/photo.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __OPENCV_BUILD #error this is a compatibility header which should not be used inside the OpenCV library #endif #include "opencv2/photo.hpp" ================================================ FILE: src/3rdparty/opencv/include/opencv2/photo/photo_c.h ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_PHOTO_C_H__ #define __OPENCV_PHOTO_C_H__ #include "opencv2/core/core_c.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup photo_c @{ */ /* Inpainting algorithms */ enum InpaintingModes { CV_INPAINT_NS =0, CV_INPAINT_TELEA =1 }; /* Inpaints the selected region in the image */ CVAPI(void) cvInpaint( const CvArr* src, const CvArr* inpaint_mask, CvArr* dst, double inpaintRange, int flags ); /** @} */ #ifdef __cplusplus } //extern "C" #endif #endif //__OPENCV_PHOTO_C_H__ ================================================ FILE: src/3rdparty/opencv/include/opencv2/photo.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_PHOTO_HPP__ #define __OPENCV_PHOTO_HPP__ #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" /** @defgroup photo Computational Photography @{ @defgroup photo_denoise Denoising @defgroup photo_hdr HDR imaging This section describes high dynamic range imaging algorithms namely tonemapping, exposure alignment, camera calibration with multiple exposures and exposure fusion. @defgroup photo_clone Seamless Cloning @defgroup photo_render Non-Photorealistic Rendering @defgroup photo_c C API @} */ namespace cv { //! @addtogroup photo //! @{ //! the inpainting algorithm enum { INPAINT_NS = 0, // Navier-Stokes algorithm INPAINT_TELEA = 1 // A. Telea algorithm }; enum { NORMAL_CLONE = 1, MIXED_CLONE = 2, MONOCHROME_TRANSFER = 3 }; enum { RECURS_FILTER = 1, NORMCONV_FILTER = 2 }; /** @brief Restores the selected region in an image using the region neighborhood. @param src Input 8-bit 1-channel or 3-channel image. @param inpaintMask Inpainting mask, 8-bit 1-channel image. Non-zero pixels indicate the area that needs to be inpainted. @param dst Output image with the same size and type as src . @param inpaintRadius Radius of a circular neighborhood of each point inpainted that is considered by the algorithm. @param flags Inpainting method that could be one of the following: - **INPAINT_NS** Navier-Stokes based method [Navier01] - **INPAINT_TELEA** Method by Alexandru Telea @cite Telea04 . The function reconstructs the selected image area from the pixel near the area boundary. The function may be used to remove dust and scratches from a scanned photo, or to remove undesirable objects from still images or video. See for more details. @note - An example using the inpainting technique can be found at opencv_source_code/samples/cpp/inpaint.cpp - (Python) An example using the inpainting technique can be found at opencv_source_code/samples/python/inpaint.py */ CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask, OutputArray dst, double inpaintRadius, int flags ); //! @addtogroup photo_denoise //! @{ /** @brief Perform image denoising using Non-local Means Denoising algorithm with several computational optimizations. Noise expected to be a gaussian white noise @param src Input 8-bit 1-channel, 2-channel, 3-channel or 4-channel image. @param dst Output image with the same size and type as src . @param templateWindowSize Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param searchWindowSize Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels @param h Parameter regulating filter strength. Big h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise This function expected to be applied to grayscale images. For colored images look at fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting image to CIELAB colorspace and then separately denoise L and AB components with different h parameter. */ CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21); /** @brief Perform image denoising using Non-local Means Denoising algorithm with several computational optimizations. Noise expected to be a gaussian white noise @param src Input 8-bit or 16-bit (only with NORM_L1) 1-channel, 2-channel, 3-channel or 4-channel image. @param dst Output image with the same size and type as src . @param templateWindowSize Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param searchWindowSize Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels @param h Array of parameters regulating filter strength, either one parameter applied to all channels or one per channel in dst. Big h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise @param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 This function expected to be applied to grayscale images. For colored images look at fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting image to CIELAB colorspace and then separately denoise L and AB components with different h parameter. */ CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, const std::vector& h, int templateWindowSize = 7, int searchWindowSize = 21, int normType = NORM_L2); /** @brief Modification of fastNlMeansDenoising function for colored images @param src Input 8-bit 3-channel image. @param dst Output image with the same size and type as src . @param templateWindowSize Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param searchWindowSize Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels @param h Parameter regulating filter strength for luminance component. Bigger h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise @param hColor The same as h but for color components. For most images value equals 10 will be enough to remove colored noise and do not distort colors The function converts image to CIELAB colorspace and then separately denoise L and AB components with given h parameters using fastNlMeansDenoising function. */ CV_EXPORTS_W void fastNlMeansDenoisingColored( InputArray src, OutputArray dst, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21); /** @brief Modification of fastNlMeansDenoising function for images sequence where consequtive images have been captured in small period of time. For example video. This version of the function is for grayscale images or for manual manipulation with colorspaces. For more details see @param srcImgs Input 8-bit 1-channel, 2-channel, 3-channel or 4-channel images sequence. All images should have the same type and size. @param imgToDenoiseIndex Target image to denoise index in srcImgs sequence @param temporalWindowSize Number of surrounding images to use for target image denoising. Should be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to imgToDenoiseIndex - temporalWindowSize / 2 from srcImgs will be used to denoise srcImgs[imgToDenoiseIndex] image. @param dst Output image with the same size and type as srcImgs images. @param templateWindowSize Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param searchWindowSize Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels @param h Parameter regulating filter strength. Bigger h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise */ CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21); /** @brief Modification of fastNlMeansDenoising function for images sequence where consequtive images have been captured in small period of time. For example video. This version of the function is for grayscale images or for manual manipulation with colorspaces. For more details see @param srcImgs Input 8-bit or 16-bit (only with NORM_L1) 1-channel, 2-channel, 3-channel or 4-channel images sequence. All images should have the same type and size. @param imgToDenoiseIndex Target image to denoise index in srcImgs sequence @param temporalWindowSize Number of surrounding images to use for target image denoising. Should be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to imgToDenoiseIndex - temporalWindowSize / 2 from srcImgs will be used to denoise srcImgs[imgToDenoiseIndex] image. @param dst Output image with the same size and type as srcImgs images. @param templateWindowSize Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param searchWindowSize Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels @param h Array of parameters regulating filter strength, either one parameter applied to all channels or one per channel in dst. Big h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise @param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 */ CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, int imgToDenoiseIndex, int temporalWindowSize, const std::vector& h, int templateWindowSize = 7, int searchWindowSize = 21, int normType = NORM_L2); /** @brief Modification of fastNlMeansDenoisingMulti function for colored images sequences @param srcImgs Input 8-bit 3-channel images sequence. All images should have the same type and size. @param imgToDenoiseIndex Target image to denoise index in srcImgs sequence @param temporalWindowSize Number of surrounding images to use for target image denoising. Should be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to imgToDenoiseIndex - temporalWindowSize / 2 from srcImgs will be used to denoise srcImgs[imgToDenoiseIndex] image. @param dst Output image with the same size and type as srcImgs images. @param templateWindowSize Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels @param searchWindowSize Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels @param h Parameter regulating filter strength for luminance component. Bigger h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise. @param hColor The same as h but for color components. The function converts images to CIELAB colorspace and then separately denoise L and AB components with given h parameters using fastNlMeansDenoisingMulti function. */ CV_EXPORTS_W void fastNlMeansDenoisingColoredMulti( InputArrayOfArrays srcImgs, OutputArray dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21); /** @brief Primal-dual algorithm is an algorithm for solving special types of variational problems (that is, finding a function to minimize some functional). As the image denoising, in particular, may be seen as the variational problem, primal-dual algorithm then can be used to perform denoising and this is exactly what is implemented. It should be noted, that this implementation was taken from the July 2013 blog entry @cite MA13 , which also contained (slightly more general) ready-to-use source code on Python. Subsequently, that code was rewritten on C++ with the usage of openCV by Vadim Pisarevsky at the end of July 2013 and finally it was slightly adapted by later authors. Although the thorough discussion and justification of the algorithm involved may be found in @cite ChambolleEtAl, it might make sense to skim over it here, following @cite MA13 . To begin with, we consider the 1-byte gray-level images as the functions from the rectangular domain of pixels (it may be seen as set \f$\left\{(x,y)\in\mathbb{N}\times\mathbb{N}\mid 1\leq x\leq n,\;1\leq y\leq m\right\}\f$ for some \f$m,\;n\in\mathbb{N}\f$) into \f$\{0,1,\dots,255\}\f$. We shall denote the noised images as \f$f_i\f$ and with this view, given some image \f$x\f$ of the same size, we may measure how bad it is by the formula \f[\left\|\left\|\nabla x\right\|\right\| + \lambda\sum_i\left\|\left\|x-f_i\right\|\right\|\f] \f$\|\|\cdot\|\|\f$ here denotes \f$L_2\f$-norm and as you see, the first addend states that we want our image to be smooth (ideally, having zero gradient, thus being constant) and the second states that we want our result to be close to the observations we've got. If we treat \f$x\f$ as a function, this is exactly the functional what we seek to minimize and here the Primal-Dual algorithm comes into play. @param observations This array should contain one or more noised versions of the image that is to be restored. @param result Here the denoised image will be stored. There is no need to do pre-allocation of storage space, as it will be automatically allocated, if necessary. @param lambda Corresponds to \f$\lambda\f$ in the formulas above. As it is enlarged, the smooth (blurred) images are treated more favorably than detailed (but maybe more noised) ones. Roughly speaking, as it becomes smaller, the result will be more blur but more sever outliers will be removed. @param niters Number of iterations that the algorithm will run. Of course, as more iterations as better, but it is hard to quantitatively refine this statement, so just use the default and increase it if the results are poor. */ CV_EXPORTS_W void denoise_TVL1(const std::vector& observations,Mat& result, double lambda=1.0, int niters=30); //! @} photo_denoise //! @addtogroup photo_hdr //! @{ enum { LDR_SIZE = 256 }; /** @brief Base class for tonemapping algorithms - tools that are used to map HDR image to 8-bit range. */ class CV_EXPORTS_W Tonemap : public Algorithm { public: /** @brief Tonemaps image @param src source image - 32-bit 3-channel Mat @param dst destination image - 32-bit 3-channel Mat with values in [0, 1] range */ CV_WRAP virtual void process(InputArray src, OutputArray dst) = 0; CV_WRAP virtual float getGamma() const = 0; CV_WRAP virtual void setGamma(float gamma) = 0; }; /** @brief Creates simple linear mapper with gamma correction @param gamma positive value for gamma correction. Gamma value of 1.0 implies no correction, gamma equal to 2.2f is suitable for most displays. Generally gamma \> 1 brightens the image and gamma \< 1 darkens it. */ CV_EXPORTS_W Ptr createTonemap(float gamma = 1.0f); /** @brief Adaptive logarithmic mapping is a fast global tonemapping algorithm that scales the image in logarithmic domain. Since it's a global operator the same function is applied to all the pixels, it is controlled by the bias parameter. Optional saturation enhancement is possible as described in @cite FL02 . For more information see @cite DM03 . */ class CV_EXPORTS_W TonemapDrago : public Tonemap { public: CV_WRAP virtual float getSaturation() const = 0; CV_WRAP virtual void setSaturation(float saturation) = 0; CV_WRAP virtual float getBias() const = 0; CV_WRAP virtual void setBias(float bias) = 0; }; /** @brief Creates TonemapDrago object @param gamma gamma value for gamma correction. See createTonemap @param saturation positive saturation enhancement value. 1.0 preserves saturation, values greater than 1 increase saturation and values less than 1 decrease it. @param bias value for bias function in [0, 1] range. Values from 0.7 to 0.9 usually give best results, default value is 0.85. */ CV_EXPORTS_W Ptr createTonemapDrago(float gamma = 1.0f, float saturation = 1.0f, float bias = 0.85f); /** @brief This algorithm decomposes image into two layers: base layer and detail layer using bilateral filter and compresses contrast of the base layer thus preserving all the details. This implementation uses regular bilateral filter from opencv. Saturation enhancement is possible as in ocvTonemapDrago. For more information see @cite DD02 . */ class CV_EXPORTS_W TonemapDurand : public Tonemap { public: CV_WRAP virtual float getSaturation() const = 0; CV_WRAP virtual void setSaturation(float saturation) = 0; CV_WRAP virtual float getContrast() const = 0; CV_WRAP virtual void setContrast(float contrast) = 0; CV_WRAP virtual float getSigmaSpace() const = 0; CV_WRAP virtual void setSigmaSpace(float sigma_space) = 0; CV_WRAP virtual float getSigmaColor() const = 0; CV_WRAP virtual void setSigmaColor(float sigma_color) = 0; }; /** @brief Creates TonemapDurand object @param gamma gamma value for gamma correction. See createTonemap @param contrast resulting contrast on logarithmic scale, i. e. log(max / min), where max and min are maximum and minimum luminance values of the resulting image. @param saturation saturation enhancement value. See createTonemapDrago @param sigma_space bilateral filter sigma in color space @param sigma_color bilateral filter sigma in coordinate space */ CV_EXPORTS_W Ptr createTonemapDurand(float gamma = 1.0f, float contrast = 4.0f, float saturation = 1.0f, float sigma_space = 2.0f, float sigma_color = 2.0f); /** @brief This is a global tonemapping operator that models human visual system. Mapping function is controlled by adaptation parameter, that is computed using light adaptation and color adaptation. For more information see @cite RD05 . */ class CV_EXPORTS_W TonemapReinhard : public Tonemap { public: CV_WRAP virtual float getIntensity() const = 0; CV_WRAP virtual void setIntensity(float intensity) = 0; CV_WRAP virtual float getLightAdaptation() const = 0; CV_WRAP virtual void setLightAdaptation(float light_adapt) = 0; CV_WRAP virtual float getColorAdaptation() const = 0; CV_WRAP virtual void setColorAdaptation(float color_adapt) = 0; }; /** @brief Creates TonemapReinhard object @param gamma gamma value for gamma correction. See createTonemap @param intensity result intensity in [-8, 8] range. Greater intensity produces brighter results. @param light_adapt light adaptation in [0, 1] range. If 1 adaptation is based only on pixel value, if 0 it's global, otherwise it's a weighted mean of this two cases. @param color_adapt chromatic adaptation in [0, 1] range. If 1 channels are treated independently, if 0 adaptation level is the same for each channel. */ CV_EXPORTS_W Ptr createTonemapReinhard(float gamma = 1.0f, float intensity = 0.0f, float light_adapt = 1.0f, float color_adapt = 0.0f); /** @brief This algorithm transforms image to contrast using gradients on all levels of gaussian pyramid, transforms contrast values to HVS response and scales the response. After this the image is reconstructed from new contrast values. For more information see @cite MM06 . */ class CV_EXPORTS_W TonemapMantiuk : public Tonemap { public: CV_WRAP virtual float getScale() const = 0; CV_WRAP virtual void setScale(float scale) = 0; CV_WRAP virtual float getSaturation() const = 0; CV_WRAP virtual void setSaturation(float saturation) = 0; }; /** @brief Creates TonemapMantiuk object @param gamma gamma value for gamma correction. See createTonemap @param scale contrast scale factor. HVS response is multiplied by this parameter, thus compressing dynamic range. Values from 0.6 to 0.9 produce best results. @param saturation saturation enhancement value. See createTonemapDrago */ CV_EXPORTS_W Ptr createTonemapMantiuk(float gamma = 1.0f, float scale = 0.7f, float saturation = 1.0f); /** @brief The base class for algorithms that align images of the same scene with different exposures */ class CV_EXPORTS_W AlignExposures : public Algorithm { public: /** @brief Aligns images @param src vector of input images @param dst vector of aligned images @param times vector of exposure time values for each image @param response 256x1 matrix with inverse camera response function for each pixel value, it should have the same number of channels as images. */ CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, InputArray times, InputArray response) = 0; }; /** @brief This algorithm converts images to median threshold bitmaps (1 for pixels brighter than median luminance and 0 otherwise) and than aligns the resulting bitmaps using bit operations. It is invariant to exposure, so exposure values and camera response are not necessary. In this implementation new image regions are filled with zeros. For more information see @cite GW03 . */ class CV_EXPORTS_W AlignMTB : public AlignExposures { public: CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, InputArray times, InputArray response) = 0; /** @brief Short version of process, that doesn't take extra arguments. @param src vector of input images @param dst vector of aligned images */ CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst) = 0; /** @brief Calculates shift between two images, i. e. how to shift the second image to correspond it with the first. @param img0 first image @param img1 second image */ CV_WRAP virtual Point calculateShift(InputArray img0, InputArray img1) = 0; /** @brief Helper function, that shift Mat filling new regions with zeros. @param src input image @param dst result image @param shift shift value */ CV_WRAP virtual void shiftMat(InputArray src, OutputArray dst, const Point shift) = 0; /** @brief Computes median threshold and exclude bitmaps of given image. @param img input image @param tb median threshold bitmap @param eb exclude bitmap */ CV_WRAP virtual void computeBitmaps(InputArray img, OutputArray tb, OutputArray eb) = 0; CV_WRAP virtual int getMaxBits() const = 0; CV_WRAP virtual void setMaxBits(int max_bits) = 0; CV_WRAP virtual int getExcludeRange() const = 0; CV_WRAP virtual void setExcludeRange(int exclude_range) = 0; CV_WRAP virtual bool getCut() const = 0; CV_WRAP virtual void setCut(bool value) = 0; }; /** @brief Creates AlignMTB object @param max_bits logarithm to the base 2 of maximal shift in each dimension. Values of 5 and 6 are usually good enough (31 and 63 pixels shift respectively). @param exclude_range range for exclusion bitmap that is constructed to suppress noise around the median value. @param cut if true cuts images, otherwise fills the new regions with zeros. */ CV_EXPORTS_W Ptr createAlignMTB(int max_bits = 6, int exclude_range = 4, bool cut = true); /** @brief The base class for camera response calibration algorithms. */ class CV_EXPORTS_W CalibrateCRF : public Algorithm { public: /** @brief Recovers inverse camera response. @param src vector of input images @param dst 256x1 matrix with inverse camera response function @param times vector of exposure time values for each image */ CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; }; /** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective function as linear system. Objective function is constructed using pixel values on the same position in all images, extra term is added to make the result smoother. For more information see @cite DM97 . */ class CV_EXPORTS_W CalibrateDebevec : public CalibrateCRF { public: CV_WRAP virtual float getLambda() const = 0; CV_WRAP virtual void setLambda(float lambda) = 0; CV_WRAP virtual int getSamples() const = 0; CV_WRAP virtual void setSamples(int samples) = 0; CV_WRAP virtual bool getRandom() const = 0; CV_WRAP virtual void setRandom(bool random) = 0; }; /** @brief Creates CalibrateDebevec object @param samples number of pixel locations to use @param lambda smoothness term weight. Greater values produce smoother results, but can alter the response. @param random if true sample pixel locations are chosen at random, otherwise the form a rectangular grid. */ CV_EXPORTS_W Ptr createCalibrateDebevec(int samples = 70, float lambda = 10.0f, bool random = false); /** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective function as linear system. This algorithm uses all image pixels. For more information see @cite RB99 . */ class CV_EXPORTS_W CalibrateRobertson : public CalibrateCRF { public: CV_WRAP virtual int getMaxIter() const = 0; CV_WRAP virtual void setMaxIter(int max_iter) = 0; CV_WRAP virtual float getThreshold() const = 0; CV_WRAP virtual void setThreshold(float threshold) = 0; CV_WRAP virtual Mat getRadiance() const = 0; }; /** @brief Creates CalibrateRobertson object @param max_iter maximal number of Gauss-Seidel solver iterations. @param threshold target difference between results of two successive steps of the minimization. */ CV_EXPORTS_W Ptr createCalibrateRobertson(int max_iter = 30, float threshold = 0.01f); /** @brief The base class algorithms that can merge exposure sequence to a single image. */ class CV_EXPORTS_W MergeExposures : public Algorithm { public: /** @brief Merges images. @param src vector of input images @param dst result image @param times vector of exposure time values for each image @param response 256x1 matrix with inverse camera response function for each pixel value, it should have the same number of channels as images. */ CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times, InputArray response) = 0; }; /** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure values and camera response. For more information see @cite DM97 . */ class CV_EXPORTS_W MergeDebevec : public MergeExposures { public: CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times, InputArray response) = 0; CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; }; /** @brief Creates MergeDebevec object */ CV_EXPORTS_W Ptr createMergeDebevec(); /** @brief Pixels are weighted using contrast, saturation and well-exposedness measures, than images are combined using laplacian pyramids. The resulting image weight is constructed as weighted average of contrast, saturation and well-exposedness measures. The resulting image doesn't require tonemapping and can be converted to 8-bit image by multiplying by 255, but it's recommended to apply gamma correction and/or linear tonemapping. For more information see @cite MK07 . */ class CV_EXPORTS_W MergeMertens : public MergeExposures { public: CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times, InputArray response) = 0; /** @brief Short version of process, that doesn't take extra arguments. @param src vector of input images @param dst result image */ CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst) = 0; CV_WRAP virtual float getContrastWeight() const = 0; CV_WRAP virtual void setContrastWeight(float contrast_weiht) = 0; CV_WRAP virtual float getSaturationWeight() const = 0; CV_WRAP virtual void setSaturationWeight(float saturation_weight) = 0; CV_WRAP virtual float getExposureWeight() const = 0; CV_WRAP virtual void setExposureWeight(float exposure_weight) = 0; }; /** @brief Creates MergeMertens object @param contrast_weight contrast measure weight. See MergeMertens. @param saturation_weight saturation measure weight @param exposure_weight well-exposedness measure weight */ CV_EXPORTS_W Ptr createMergeMertens(float contrast_weight = 1.0f, float saturation_weight = 1.0f, float exposure_weight = 0.0f); /** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure values and camera response. For more information see @cite RB99 . */ class CV_EXPORTS_W MergeRobertson : public MergeExposures { public: CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times, InputArray response) = 0; CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; }; /** @brief Creates MergeRobertson object */ CV_EXPORTS_W Ptr createMergeRobertson(); //! @} photo_hdr /** @brief Transforms a color image to a grayscale image. It is a basic tool in digital printing, stylized black-and-white photograph rendering, and in many single channel image processing applications @cite CL12 . @param src Input 8-bit 3-channel image. @param grayscale Output 8-bit 1-channel image. @param color_boost Output 8-bit 3-channel image. This function is to be applied on color images. */ CV_EXPORTS_W void decolor( InputArray src, OutputArray grayscale, OutputArray color_boost); //! @addtogroup photo_clone //! @{ /** @brief Image editing tasks concern either global changes (color/intensity corrections, filters, deformations) or local changes concerned to a selection. Here we are interested in achieving local changes, ones that are restricted to a region manually selected (ROI), in a seamless and effortless manner. The extent of the changes ranges from slight distortions to complete replacement by novel content @cite PM03 . @param src Input 8-bit 3-channel image. @param dst Input 8-bit 3-channel image. @param mask Input 8-bit 1 or 3-channel image. @param p Point in dst image where object is placed. @param blend Output image with the same size and type as dst. @param flags Cloning method that could be one of the following: - **NORMAL_CLONE** The power of the method is fully expressed when inserting objects with complex outlines into a new background - **MIXED_CLONE** The classic method, color-based selection and alpha masking might be time consuming and often leaves an undesirable halo. Seamless cloning, even averaged with the original image, is not effective. Mixed seamless cloning based on a loose selection proves effective. - **FEATURE_EXCHANGE** Feature exchange allows the user to easily replace certain features of one object by alternative features. */ CV_EXPORTS_W void seamlessClone( InputArray src, InputArray dst, InputArray mask, Point p, OutputArray blend, int flags); /** @brief Given an original color image, two differently colored versions of this image can be mixed seamlessly. @param src Input 8-bit 3-channel image. @param mask Input 8-bit 1 or 3-channel image. @param dst Output image with the same size and type as src . @param red_mul R-channel multiply factor. @param green_mul G-channel multiply factor. @param blue_mul B-channel multiply factor. Multiplication factor is between .5 to 2.5. */ CV_EXPORTS_W void colorChange(InputArray src, InputArray mask, OutputArray dst, float red_mul = 1.0f, float green_mul = 1.0f, float blue_mul = 1.0f); /** @brief Applying an appropriate non-linear transformation to the gradient field inside the selection and then integrating back with a Poisson solver, modifies locally the apparent illumination of an image. @param src Input 8-bit 3-channel image. @param mask Input 8-bit 1 or 3-channel image. @param dst Output image with the same size and type as src. @param alpha Value ranges between 0-2. @param beta Value ranges between 0-2. This is useful to highlight under-exposed foreground objects or to reduce specular reflections. */ CV_EXPORTS_W void illuminationChange(InputArray src, InputArray mask, OutputArray dst, float alpha = 0.2f, float beta = 0.4f); /** @brief By retaining only the gradients at edge locations, before integrating with the Poisson solver, one washes out the texture of the selected region, giving its contents a flat aspect. Here Canny Edge Detector is used. @param src Input 8-bit 3-channel image. @param mask Input 8-bit 1 or 3-channel image. @param dst Output image with the same size and type as src. @param low_threshold Range from 0 to 100. @param high_threshold Value \> 100. @param kernel_size The size of the Sobel kernel to be used. **NOTE:** The algorithm assumes that the color of the source image is close to that of the destination. This assumption means that when the colors don't match, the source image color gets tinted toward the color of the destination image. */ CV_EXPORTS_W void textureFlattening(InputArray src, InputArray mask, OutputArray dst, float low_threshold = 30, float high_threshold = 45, int kernel_size = 3); //! @} photo_clone //! @addtogroup photo_render //! @{ /** @brief Filtering is the fundamental operation in image and video processing. Edge-preserving smoothing filters are used in many different applications @cite EM11 . @param src Input 8-bit 3-channel image. @param dst Output 8-bit 3-channel image. @param flags Edge preserving filters: - **RECURS_FILTER** = 1 - **NORMCONV_FILTER** = 2 @param sigma_s Range between 0 to 200. @param sigma_r Range between 0 to 1. */ CV_EXPORTS_W void edgePreservingFilter(InputArray src, OutputArray dst, int flags = 1, float sigma_s = 60, float sigma_r = 0.4f); /** @brief This filter enhances the details of a particular image. @param src Input 8-bit 3-channel image. @param dst Output image with the same size and type as src. @param sigma_s Range between 0 to 200. @param sigma_r Range between 0 to 1. */ CV_EXPORTS_W void detailEnhance(InputArray src, OutputArray dst, float sigma_s = 10, float sigma_r = 0.15f); /** @brief Pencil-like non-photorealistic line drawing @param src Input 8-bit 3-channel image. @param dst1 Output 8-bit 1-channel image. @param dst2 Output image with the same size and type as src. @param sigma_s Range between 0 to 200. @param sigma_r Range between 0 to 1. @param shade_factor Range between 0 to 0.1. */ CV_EXPORTS_W void pencilSketch(InputArray src, OutputArray dst1, OutputArray dst2, float sigma_s = 60, float sigma_r = 0.07f, float shade_factor = 0.02f); /** @brief Stylization aims to produce digital imagery with a wide variety of effects not focused on photorealism. Edge-aware filters are ideal for stylization, as they can abstract regions of low contrast while preserving, or enhancing, high-contrast features. @param src Input 8-bit 3-channel image. @param dst Output image with the same size and type as src. @param sigma_s Range between 0 to 200. @param sigma_r Range between 0 to 1. */ CV_EXPORTS_W void stylization(InputArray src, OutputArray dst, float sigma_s = 60, float sigma_r = 0.45f); //! @} photo_render //! @} photo } // cv #ifndef DISABLE_OPENCV_24_COMPATIBILITY #include "opencv2/photo/photo_c.h" #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/plot.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2012, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ //################################################################################ // // Created by Nuno Moutinho // //################################################################################ #ifndef _OPENCV_PLOT_H_ #define _OPENCV_PLOT_H_ #ifdef __cplusplus #include /** @defgroup plot Plot function for Mat data */ namespace cv { namespace plot { class CV_EXPORTS_W Plot2d : public Algorithm { public: CV_WRAP virtual void setMinX(double _plotMinX) = 0; CV_WRAP virtual void setMinY(double _plotMinY) = 0; CV_WRAP virtual void setMaxX(double _plotMaxX) = 0; CV_WRAP virtual void setMaxY(double _plotMaxY) = 0; CV_WRAP virtual void setPlotLineWidth(int _plotLineWidth) = 0; CV_WRAP virtual void setPlotLineColor(Scalar _plotLineColor) = 0; CV_WRAP virtual void setPlotBackgroundColor(Scalar _plotBackgroundColor) = 0; CV_WRAP virtual void setPlotAxisColor(Scalar _plotAxisColor) = 0; CV_WRAP virtual void setPlotGridColor(Scalar _plotGridColor) = 0; CV_WRAP virtual void setPlotTextColor(Scalar _plotTextColor) = 0; CV_WRAP virtual void setPlotSize(int _plotSizeWidth, int _plotSizeHeight) = 0; CV_WRAP virtual void render(Mat &_plotResult) = 0; }; CV_EXPORTS_W Ptr createPlot2d(Mat data); CV_EXPORTS_W Ptr createPlot2d(Mat dataX, Mat dataY); } } #endif #endif ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/map.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAP_H_ #define MAP_H_ #include // Basic OpenCV structures (cv::Mat, Scalar) /** @defgroup reg Image Registration The Registration module implements parametric image registration. The implemented method is direct alignment, that is, it uses directly the pixel values for calculating the registration between a pair of images, as opposed to feature-based registration. The implementation follows essentially the corresponding part of @cite Szeliski06 . Feature based methods have some advantages over pixel based methods when we are trying to register pictures that have been shoot under different lighting conditions or exposition times, or when the images overlap only partially. On the other hand, the main advantage of pixel-based methods when compared to feature based methods is their better precision for some pictures (those shoot under similar lighting conditions and that have a significative overlap), due to the fact that we are using all the information available in the image, which allows us to achieve subpixel accuracy. This is particularly important for certain applications like multi-frame denoising or super-resolution. In fact, pixel and feature registration methods can complement each other: an application could first obtain a coarse registration using features and then refine the registration using a pixel based method on the overlapping area of the images. The code developed allows this use case. The module implements classes derived from the abstract classes cv::reg::Map or cv::reg::Mapper. The former models a coordinate transformation between two reference frames, while the later encapsulates a way of invoking a method that calculates a Map between two images. Although the objective has been to implement pixel based methods, the module can be extended to support other methods that can calculate transformations between images (feature methods, optical flow, etc.). Each class derived from Map implements a motion model, as follows: - MapShift: Models a simple translation - MapAffine: Models an affine transformation - MapProjec: Models a projective transformation MapProject can also be used to model affine motion or translations, but some operations on it are more costly, and that is the reason for defining the other two classes. The classes derived from Mapper are - MapperGradShift: Gradient based alignment for calculating translations. It produces a MapShift (two parameters that correspond to the shift vector). - MapperGradEuclid: Gradient based alignment for euclidean motions, that is, rotations and translations. It calculates three parameters (angle and shift vector), although the result is stored in a MapAffine object for convenience. - MapperGradSimilar: Gradient based alignment for calculating similarities, which adds scaling to the euclidean motion. It calculates four parameters (two for the anti-symmetric matrix and two for the shift vector), although the result is stored in a MapAffine object for better convenience. - MapperGradAffine: Gradient based alignment for an affine motion model. The number of parameters is six and the result is stored in a MapAffine object. - MapperGradProj: Gradient based alignment for calculating projective transformations. The number of parameters is eight and the result is stored in a MapProject object. - MapperPyramid: It implements hyerarchical motion estimation using a Gaussian pyramid. Its constructor accepts as argument any other object that implements the Mapper interface, and it is that mapper the one called by MapperPyramid for each scale of the pyramid. If the motion between the images is not very small, the normal way of using these classes is to create a MapperGrad\* object and use it as input to create a MapperPyramid, which in turn is called to perform the calculation. However, if the motion between the images is small enough, we can use directly the MapperGrad\* classes. Another possibility is to use first a feature based method to perform a coarse registration and then do a refinement through MapperPyramid or directly a MapperGrad\* object. The "calculate" method of the mappers accepts an initial estimation of the motion as input. When deciding which MapperGrad to use we must take into account that mappers with more parameters can handle more complex motions, but involve more calculations and are therefore slower. Also, if we are confident on the motion model that is followed by the sequence, increasing the number of parameters beyond what we need will decrease the accuracy: it is better to use the least number of degrees of freedom that we can. In the module tests there are examples that show how to register a pair of images using any of the implemented mappers. */ namespace cv { namespace reg { //! @addtogroup reg //! @{ /** @brief Base class for modelling a Map between two images. The class is only used to define the common interface for any possible map. */ class CV_EXPORTS Map { public: /*! * Virtual destructor */ virtual ~Map(void); /*! * Warps image to a new coordinate frame. The calculation is img2(x)=img1(T^{-1}(x)), as we * have to apply the inverse transformation to the points to move them to were the values * of img2 are. * \param[in] img1 Original image * \param[out] img2 Warped image */ virtual void warp(const cv::Mat& img1, cv::Mat& img2) const; /*! * Warps image to a new coordinate frame. The calculation is img2(x)=img1(T(x)), so in fact * this is the inverse warping as we are taking the value of img1 with the forward * transformation of the points. * \param[in] img1 Original image * \param[out] img2 Warped image */ virtual void inverseWarp(const cv::Mat& img1, cv::Mat& img2) const = 0; /*! * Calculates the inverse map * \return Inverse map */ virtual cv::Ptr inverseMap(void) const = 0; /*! * Changes the map composing the current transformation with the one provided in the call. * The order is first the current transformation, then the input argument. * \param[in] map Transformation to compose with. */ virtual void compose(const Map& map) = 0; /*! * Scales the map by a given factor as if the coordinates system is expanded/compressed * by that factor. * \param[in] factor Expansion if bigger than one, compression if smaller than one */ virtual void scale(double factor) = 0; }; //! @} }} // namespace cv::reg #endif // MAP_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mapaffine.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPAFFINE_H_ #define MAPAFFINE_H_ #include "map.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Defines an affine transformation */ class CV_EXPORTS MapAffine : public Map { public: /*! * Default constructor builds an identity map */ MapAffine(void); /*! * Constructor providing explicit values * \param[in] linTr Linear part of the affine transformation * \param[in] shift Displacement part of the affine transformation */ MapAffine(const cv::Matx& linTr, const cv::Vec& shift); /*! * Destructor */ ~MapAffine(void); void inverseWarp(const cv::Mat& img1, cv::Mat& img2) const; cv::Ptr inverseMap(void) const; void compose(const Map& map); void scale(double factor); /*! * Return linear part of the affine transformation * \return Linear part of the affine transformation */ const cv::Matx& getLinTr() const { return linTr_; } /*! * Return displacement part of the affine transformation * \return Displacement part of the affine transformation */ const cv::Vec& getShift() const { return shift_; } private: cv::Matx linTr_; cv::Vec shift_; }; //! @} }} // namespace cv::reg #endif // MAPAFFINE_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mapper.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPER_H_ #define MAPPER_H_ #include // Basic OpenCV structures (cv::Mat, Scalar) #include "map.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /** @brief Base class for modelling an algorithm for calculating a The class is only used to define the common interface for any possible mapping algorithm. */ class CV_EXPORTS Mapper { public: virtual ~Mapper(void) {} /* * Calculate mapping between two images * \param[in] img1 Reference image * \param[in] img2 Warped image * \param[in,out] res Map from img1 to img2, stored in a smart pointer. If present as input, * it is an initial rough estimation that the mapper will try to refine. */ virtual void calculate(const cv::Mat& img1, const cv::Mat& img2, cv::Ptr& res) const = 0; /* * Returns a map compatible with the Mapper class * \return Pointer to identity Map */ virtual cv::Ptr getMap(void) const = 0; protected: /* * Calculates gradient and difference between images * \param[in] img1 Image one * \param[in] img2 Image two * \param[out] Ix Gradient x-coordinate * \param[out] Iy Gradient y-coordinate * \param[out] It Difference of images */ void gradient(const cv::Mat& img1, const cv::Mat& img2, cv::Mat& Ix, cv::Mat& Iy, cv::Mat& It) const; /* * Fills matrices with pixel coordinates of an image * \param[in] img Image * \param[out] grid_r Row (y-coordinate) * \param[out] grid_c Column (x-coordinate) */ void grid(const Mat& img, Mat& grid_r, Mat& grid_c) const; /* * Per-element square of a matrix * \param[in] mat1 Input matrix * \return mat1[i,j]^2 */ cv::Mat sqr(const cv::Mat& mat1) const { cv::Mat res; res.create(mat1.size(), mat1.type()); res = mat1.mul(mat1); return res; } }; //! @} }} // namespace cv::reg #endif // MAPPER_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mappergradaffine.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPERGRADAFFINE_H_ #define MAPPERGRADAFFINE_H_ #include "mapper.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Mapper for affine motion */ class CV_EXPORTS MapperGradAffine: public Mapper { public: MapperGradAffine(void); ~MapperGradAffine(void); virtual void calculate(const cv::Mat& img1, const cv::Mat& img2, cv::Ptr& res) const; cv::Ptr getMap(void) const; }; //! @} }} // namespace cv::reg #endif // MAPPERGRADAFFINE_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mappergradeuclid.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPERGRADEUCLID_H_ #define MAPPERGRADEUCLID_H_ #include "mapper.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Mapper for euclidean motion: rotation plus shift */ class CV_EXPORTS MapperGradEuclid: public Mapper { public: MapperGradEuclid(void); ~MapperGradEuclid(void); virtual void calculate(const cv::Mat& img1, const cv::Mat& img2, cv::Ptr& res) const; cv::Ptr getMap(void) const; }; //! @} }} // namespace cv::reg #endif // MAPPERGRADEUCLID_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mappergradproj.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPERGRADPROJ_H_ #define MAPPERGRADPROJ_H_ #include "mapper.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Gradient mapper for a projective transformation */ class CV_EXPORTS MapperGradProj: public Mapper { public: MapperGradProj(void); ~MapperGradProj(void); virtual void calculate(const cv::Mat& img1, const cv::Mat& img2, cv::Ptr& res) const; cv::Ptr getMap(void) const; }; //! @} }} // namespace cv::reg #endif // MAPPERGRADPROJ_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mappergradshift.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPERGRADSHIFT_H_ #define MAPPERGRADSHIFT_H_ #include "mapper.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Gradient mapper for a translation */ class CV_EXPORTS MapperGradShift: public Mapper { public: MapperGradShift(void); virtual ~MapperGradShift(void); virtual void calculate(const cv::Mat& img1, const cv::Mat& img2, cv::Ptr& res) const; cv::Ptr getMap(void) const; }; //! @} }} // namespace cv::reg #endif // MAPPERGRADSHIFT_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mappergradsimilar.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPERGRADSIMILAR_H_ #define MAPPERGRADSIMILAR_H_ #include "mapper.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Calculates a similarity transformation between to images (scale, rotation, and shift) */ class CV_EXPORTS MapperGradSimilar: public Mapper { public: MapperGradSimilar(void); ~MapperGradSimilar(void); virtual void calculate(const cv::Mat& img1, const cv::Mat& img2, cv::Ptr& res) const; cv::Ptr getMap(void) const; }; //! @} }} // namespace cv::reg #endif // MAPPERGRADSIMILAR_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mapperpyramid.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPERPYRAMID_H_ #define MAPPERPYRAMID_H_ #include "mapper.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Calculates a map using a gaussian pyramid */ class CV_EXPORTS MapperPyramid: public Mapper { public: /* * Constructor * \param[in] baseMapper Base mapper used for the refinements */ MapperPyramid(const Mapper& baseMapper); void calculate(const cv::Mat& img1, const cv::Mat& img2, cv::Ptr& res) const; cv::Ptr getMap(void) const; unsigned numLev_; /*!< Number of levels of the pyramid */ unsigned numIterPerScale_; /*!< Number of iterations at a given scale of the pyramid */ private: MapperPyramid& operator=(const MapperPyramid&); const Mapper& baseMapper_; /*!< Mapper used in inner level */ }; //! @} }} // namespace cv::reg #endif // MAPPERPYRAMID_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mapprojec.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPPROJEC_H_ #define MAPPROJEC_H_ #include "map.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Defines an transformation that consists on a projective transformation */ class CV_EXPORTS MapProjec : public Map { public: /*! * Default constructor builds an identity map */ MapProjec(void); /*! * Constructor providing explicit values * \param[in] projTr Projective transformation */ MapProjec(const cv::Matx& projTr); /*! * Destructor */ ~MapProjec(void); void inverseWarp(const cv::Mat& img1, cv::Mat& img2) const; cv::Ptr inverseMap(void) const; void compose(const Map& map); void scale(double factor); /*! * Returns projection matrix * \return Projection matrix */ const cv::Matx& getProjTr() const { return projTr_; } /*! * Normalizes object's homography */ void normalize(void) { double z = 1./projTr_(2, 2); for(size_t v_i = 0; v_i < sizeof(projTr_.val)/sizeof(projTr_.val[0]); ++v_i) projTr_.val[v_i] *= z; } private: cv::Matx projTr_; /*< Projection matrix */ }; //! @} }} // namespace cv::reg #endif // MAPPROJEC_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/reg/mapshift.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef MAPSHIFT_H_ #define MAPSHIFT_H_ #include "map.hpp" namespace cv { namespace reg { //! @addtogroup reg //! @{ /*! * Defines an transformation that consists on a simple displacement */ class CV_EXPORTS MapShift : public Map { public: /*! * Default constructor builds an identity map */ MapShift(void); /*! * Constructor providing explicit values * \param[in] shift Displacement */ MapShift(const cv::Vec& shift); /*! * Destructor */ ~MapShift(void); void inverseWarp(const cv::Mat& img1, cv::Mat& img2) const; cv::Ptr inverseMap(void) const; void compose(const Map& map); void scale(double factor); /*! * Return displacement * \return Displacement */ const cv::Vec& getShift() const { return shift_; } private: cv::Vec shift_; /*< Displacement */ }; //! @} }} // namespace cv::reg #endif // MAPSHIFT_H_ ================================================ FILE: src/3rdparty/opencv/include/opencv2/rgbd/linemod.hpp ================================================ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) 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 of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_OBJDETECT_LINEMOD_HPP__ #define __OPENCV_OBJDETECT_LINEMOD_HPP__ #include "opencv2/core.hpp" #include /****************************************************************************************\ * LINE-MOD * \****************************************************************************************/ namespace cv { namespace linemod { //! @addtogroup rgbd //! @{ /** * \brief Discriminant feature described by its location and label. */ struct CV_EXPORTS Feature { int x; ///< x offset int y; ///< y offset int label; ///< Quantization Feature() : x(0), y(0), label(0) {} Feature(int x, int y, int label); void read(const FileNode& fn); void write(FileStorage& fs) const; }; inline Feature::Feature(int _x, int _y, int _label) : x(_x), y(_y), label(_label) {} struct CV_EXPORTS Template { int width; int height; int pyramid_level; std::vector features; void read(const FileNode& fn); void write(FileStorage& fs) const; }; /** * \brief Represents a modality operating over an image pyramid. */ class QuantizedPyramid { public: // Virtual destructor virtual ~QuantizedPyramid() {} /** * \brief Compute quantized image at current pyramid level for online detection. * * \param[out] dst The destination 8-bit image. For each pixel at most one bit is set, * representing its classification. */ virtual void quantize(Mat& dst) const =0; /** * \brief Extract most discriminant features at current pyramid level to form a new template. * * \param[out] templ The new template. */ virtual bool extractTemplate(Template& templ) const =0; /** * \brief Go to the next pyramid level. * * \todo Allow pyramid scale factor other than 2 */ virtual void pyrDown() =0; protected: /// Candidate feature with a score struct Candidate { Candidate(int x, int y, int label, float score); /// Sort candidates with high score to the front bool operator<(const Candidate& rhs) const { return score > rhs.score; } Feature f; float score; }; /** * \brief Choose candidate features so that they are not bunched together. * * \param[in] candidates Candidate features sorted by score. * \param[out] features Destination vector of selected features. * \param[in] num_features Number of candidates to select. * \param[in] distance Hint for desired distance between features. */ static void selectScatteredFeatures(const std::vector& candidates, std::vector& features, size_t num_features, float distance); }; inline QuantizedPyramid::Candidate::Candidate(int x, int y, int label, float _score) : f(x, y, label), score(_score) {} /** * \brief Interface for modalities that plug into the LINE template matching representation. * * \todo Max response, to allow optimization of summing (255/MAX) features as uint8 */ class CV_EXPORTS Modality { public: // Virtual destructor virtual ~Modality() {} /** * \brief Form a quantized image pyramid from a source image. * * \param[in] src The source image. Type depends on the modality. * \param[in] mask Optional mask. If not empty, unmasked pixels are set to zero * in quantized image and cannot be extracted as features. */ Ptr process(const Mat& src, const Mat& mask = Mat()) const { return processImpl(src, mask); } virtual String name() const =0; virtual void read(const FileNode& fn) =0; virtual void write(FileStorage& fs) const =0; /** * \brief Create modality by name. * * The following modality types are supported: * - "ColorGradient" * - "DepthNormal" */ static Ptr create(const String& modality_type); /** * \brief Load a modality from file. */ static Ptr create(const FileNode& fn); protected: // Indirection is because process() has a default parameter. virtual Ptr processImpl(const Mat& src, const Mat& mask) const =0; }; /** * \brief Modality that computes quantized gradient orientations from a color image. */ class CV_EXPORTS ColorGradient : public Modality { public: /** * \brief Default constructor. Uses reasonable default parameter values. */ ColorGradient(); /** * \brief Constructor. * * \param weak_threshold When quantizing, discard gradients with magnitude less than this. * \param num_features How many features a template must contain. * \param strong_threshold Consider as candidate features only gradients whose norms are * larger than this. */ ColorGradient(float weak_threshold, size_t num_features, float strong_threshold); virtual String name() const; virtual void read(const FileNode& fn); virtual void write(FileStorage& fs) const; float weak_threshold; size_t num_features; float strong_threshold; protected: virtual Ptr processImpl(const Mat& src, const Mat& mask) const; }; /** * \brief Modality that computes quantized surface normals from a dense depth map. */ class CV_EXPORTS DepthNormal : public Modality { public: /** * \brief Default constructor. Uses reasonable default parameter values. */ DepthNormal(); /** * \brief Constructor. * * \param distance_threshold Ignore pixels beyond this distance. * \param difference_threshold When computing normals, ignore contributions of pixels whose * depth difference with the central pixel is above this threshold. * \param num_features How many features a template must contain. * \param extract_threshold Consider as candidate feature only if there are no differing * orientations within a distance of extract_threshold. */ DepthNormal(int distance_threshold, int difference_threshold, size_t num_features, int extract_threshold); virtual String name() const; virtual void read(const FileNode& fn); virtual void write(FileStorage& fs) const; int distance_threshold; int difference_threshold; size_t num_features; int extract_threshold; protected: virtual Ptr processImpl(const Mat& src, const Mat& mask) const; }; /** * \brief Debug function to colormap a quantized image for viewing. */ void colormap(const Mat& quantized, Mat& dst); /** * \brief Represents a successful template match. */ struct CV_EXPORTS Match { Match() { } Match(int x, int y, float similarity, const String& class_id, int template_id); /// Sort matches with high similarity to the front bool operator<(const Match& rhs) const { // Secondarily sort on template_id for the sake of duplicate removal if (similarity != rhs.similarity) return similarity > rhs.similarity; else return template_id < rhs.template_id; } bool operator==(const Match& rhs) const { return x == rhs.x && y == rhs.y && similarity == rhs.similarity && class_id == rhs.class_id; } int x; int y; float similarity; String class_id; int template_id; }; inline Match::Match(int _x, int _y, float _similarity, const String& _class_id, int _template_id) : x(_x), y(_y), similarity(_similarity), class_id(_class_id), template_id(_template_id) {} /** * \brief Object detector using the LINE template matching algorithm with any set of * modalities. */ class CV_EXPORTS Detector { public: /** * \brief Empty constructor, initialize with read(). */ Detector(); /** * \brief Constructor. * * \param modalities Modalities to use (color gradients, depth normals, ...). * \param T_pyramid Value of the sampling step T at each pyramid level. The * number of pyramid levels is T_pyramid.size(). */ Detector(const std::vector< Ptr >& modalities, const std::vector& T_pyramid); /** * \brief Detect objects by template matching. * * Matches globally at the lowest pyramid level, then refines locally stepping up the pyramid. * * \param sources Source images, one for each modality. * \param threshold Similarity threshold, a percentage between 0 and 100. * \param[out] matches Template matches, sorted by similarity score. * \param class_ids If non-empty, only search for the desired object classes. * \param[out] quantized_images Optionally return vector of quantized images. * \param masks The masks for consideration during matching. The masks should be CV_8UC1 * where 255 represents a valid pixel. If non-empty, the vector must be * the same size as sources. Each element must be * empty or the same size as its corresponding source. */ void match(const std::vector& sources, float threshold, std::vector& matches, const std::vector& class_ids = std::vector(), OutputArrayOfArrays quantized_images = noArray(), const std::vector& masks = std::vector()) const; /** * \brief Add new object template. * * \param sources Source images, one for each modality. * \param class_id Object class ID. * \param object_mask Mask separating object from background. * \param[out] bounding_box Optionally return bounding box of the extracted features. * * \return Template ID, or -1 if failed to extract a valid template. */ int addTemplate(const std::vector& sources, const String& class_id, const Mat& object_mask, Rect* bounding_box = NULL); /** * \brief Add a new object template computed by external means. */ int addSyntheticTemplate(const std::vector