Class: OpenCV::CvMat

Inherits:
Object
  • Object
show all
Defined in:
ext/opencv/cvmat.cpp,
ext/opencv/iplimage.cpp

Direct Known Subclasses

IplImage

Constant Summary collapse

DRAWING_OPTION =
drawing_option
GOOD_FEATURES_TO_TRACK_OPTION =
good_features_to_track_option
FLOOD_FILL_OPTION =
flood_fill_option
FIND_CONTOURS_OPTION =
find_contours_option
OPTICAL_FLOW_HS_OPTION =
optical_flow_hs_option
OPTICAL_FLOW_BM_OPTION =
optical_flow_bm_option
FIND_FUNDAMENTAL_MAT_OPTION =
find_fundamental_matrix_option

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object

nodoc



322
323
324
325
326
327
328
329
330
331
# File 'ext/opencv/cvmat.cpp', line 322

VALUE
rb_method_missing(int argc, VALUE *argv, VALUE self)
{
  VALUE name, args, method;
  rb_scan_args(argc, argv, "1*", &name, &args);
  method = rb_funcall(name, rb_intern("to_s"), 0);
  if (RARRAY_LEN(args) != 0 || !rb_respond_to(rb_module_opencv(), rb_intern(StringValuePtr(method))))
    return rb_call_super(argc, argv);
  return rb_funcall(rb_module_opencv(), rb_intern(StringValuePtr(method)), 1, self);
}

Class Method Details

.add_weighted(src1, alpha, src2, beta, gamma) ⇒ CvMat

Computes the weighted sum of two arrays. This function calculates the weighted sum of two arrays as follows:

dst(I) = src1(I) * alpha + src2(I) * beta + gamma

Parameters:

  • src1 (CvMat)

    The first source array.

  • alpha (Number)

    Weight for the first array elements.

  • src2 (CvMat)

    The second source array.

  • beta (Number)

    Weight for the second array elements.

  • gamma (Number)

    Scalar added to each sum.

Returns:

  • (CvMat)

    Result array



1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
# File 'ext/opencv/cvmat.cpp', line 1783

VALUE
rb_add_weighted(VALUE klass, VALUE src1, VALUE alpha, VALUE src2, VALUE beta, VALUE gamma)
{
  CvArr* src1_ptr = CVARR_WITH_CHECK(src1);
  VALUE dst = new_mat_kind_object(cvGetSize(src1_ptr), src1);
  try {
    cvAddWeighted(src1_ptr, NUM2DBL(alpha),
		  CVARR_WITH_CHECK(src2), NUM2DBL(beta),
		  NUM2DBL(gamma), CVARR(dst));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dst;
}

.compute_correspond_epilines(points, which_image, fundamental_matrix) ⇒ Object

For points in one image of stereo pair computes the corresponding epilines in the other image. Finds equation of a line that contains the corresponding point (i.e. projection of the same 3D point) in the other image. Each line is encoded by a vector of 3 elements l=T, so that:

lT*[x, y, 1]T=0,

or

a*x + b*y + c = 0

From the fundamental matrix definition (see cvFindFundamentalMatrix discussion), line l2 for a point p1 in the first image (which_image=1) can be computed as:

l2=F*p1

and the line l1 for a point p2 in the second image (which_image=1) can be computed as:

l1=FT*p2

Line coefficients are defined up to a scale. They are normalized (a2+b2=1) are stored into correspondent_lines.



5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
# File 'ext/opencv/cvmat.cpp', line 5626

VALUE
rb_compute_correspond_epilines(VALUE klass, VALUE points, VALUE which_image, VALUE fundamental_matrix)
{
  VALUE correspondent_lines;
  CvMat* points_ptr = CVMAT_WITH_CHECK(points);
  int n;
  if (points_ptr->cols <= 3 && points_ptr->rows >= 7)
    n = points_ptr->rows;
  else if (points_ptr->rows <= 3 && points_ptr->cols >= 7)
    n = points_ptr->cols;
  else
    rb_raise(rb_eArgError, "input points should 2xN, Nx2 or 3xN, Nx3 matrix(N >= 7).");
  
  correspondent_lines = cCvMat::new_object(n, 3, CV_MAT_DEPTH(points_ptr->type));
  try {
    cvComputeCorrespondEpilines(points_ptr, NUM2INT(which_image), CVMAT_WITH_CHECK(fundamental_matrix),
				CVMAT(correspondent_lines));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return correspondent_lines;
}

.decode_image(buf, iscolor = 1) ⇒ CvMat

Reads an image from a buffer in memory.

Parameters:

  • buf (CvMat, Array, String)

    Input array of bytes

  • iscolor (Integer)

    Flags specifying the color type of a decoded image (the same flags as CvMat#load)

Returns:

  • (CvMat)

    Loaded matrix



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'ext/opencv/cvmat.cpp', line 300

VALUE
rb_decode_imageM(int argc, VALUE *argv, VALUE self)
{
  int iscolor, need_release;
  CvMat* buff = prepare_decoding(argc, argv, &iscolor, &need_release);
  CvMat* mat_ptr = NULL;
  try {
    mat_ptr = cvDecodeImageM(buff, iscolor);
    if (need_release) {
      cvReleaseMat(&buff);
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return OPENCV_OBJECT(rb_klass, mat_ptr);
}

.find_fundamental_mat(points1, points2[,options = {}]) ⇒ nil

Calculates fundamental matrix from corresponding points. Size of the output fundamental matrix is 3x3 or 9x3 (7-point method may return up to 3 matrices)

points1 and points2 should be 2xN, Nx2, 3xN or Nx3 1-channel, or 1xN or Nx1 multi-channel matrix. <i>method<i> is method for computing the fundamental matrix

- CV_FM_7POINT for a 7-point algorithm. (N = 7)
- CV_FM_8POINT for an 8-point algorithm. (N >= 8)
- CV_FM_RANSAC for the RANSAC algorithm. (N >= 8)
- CV_FM_LMEDS for the LMedS algorithm. (N >= 8)

option should be Hash include these keys.

:with_status (true or false)
   If set true, return fundamental_matrix and status. [fundamental_matrix, status]
   Otherwise return fundamental matrix only(default).
:maximum_distance
   The parameter is used for RANSAC.  It is the maximum distance from point to 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.
:desirable_level
   The optional 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 RANSAC and LMedS methods. For other methods it is set to all 1's.

note: option’s default value is CvMat::FIND_FUNDAMENTAL_MAT_OPTION.

Returns:

  • (nil)


5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
# File 'ext/opencv/cvmat.cpp', line 5570

VALUE
rb_find_fundamental_mat(int argc, VALUE *argv, VALUE klass)
{
  VALUE points1, points2, method, option, fundamental_matrix, status;
  int num = 0;
  rb_scan_args(argc, argv, "31", &points1, &points2, &method, &option);
  option = FIND_FUNDAMENTAL_MAT_OPTION(option);
  int fm_method = FIX2INT(method);
  CvMat *points1_ptr = CVMAT_WITH_CHECK(points1);
  if (fm_method == CV_FM_7POINT)
    fundamental_matrix = cCvMat::new_object(9, 3, CV_MAT_DEPTH(points1_ptr->type));
  else
    fundamental_matrix = cCvMat::new_object(3, 3, CV_MAT_DEPTH(points1_ptr->type));

  if (FFM_WITH_STATUS(option)) {
    int status_len = (points1_ptr->rows > points1_ptr->cols) ? points1_ptr->rows : points1_ptr->cols;
    status = cCvMat::new_object(1, status_len, CV_8UC1);
    try {
      num = cvFindFundamentalMat(points1_ptr, CVMAT_WITH_CHECK(points2), CVMAT(fundamental_matrix), fm_method,
				 FFM_MAXIMUM_DISTANCE(option), FFM_DESIRABLE_LEVEL(option), CVMAT(status));
    }
    catch (cv::Exception& e) {
      raise_cverror(e);
    }
    return num == 0 ? Qnil : rb_ary_new3(2, fundamental_matrix, status);
  }
  else {
    try {
      num = cvFindFundamentalMat(points1_ptr, CVMAT_WITH_CHECK(points2), CVMAT(fundamental_matrix), fm_method,
				 FFM_MAXIMUM_DISTANCE(option), FFM_DESIRABLE_LEVEL(option), NULL);
    }
    catch (cv::Exception& e) {
      raise_cverror(e);
    }
    return num == 0 ? Qnil : fundamental_matrix;
  }
}

.find_homography(src_points, dst_points, method = :all, ransac_reproj_threshold = 3, get_mask = false) ⇒ CvMat+

Finds a perspective transformation between two planes.

Parameters:

  • src_points (CvMat)

    Coordinates of the points in the original plane.

  • dst_points (CvMat)

    Coordinates of the points in the target plane.

  • method (Symbol) (defaults to: :all)

    Method used to computed a homography matrix. The following methods are possible:

    • :all - a regular method using all the points

    • :ransac - RANSAC-based robust method

    • :lmeds - Least-Median robust method

  • ransac_reproj_threshold (Number) (defaults to: 3)

    Maximum allowed reprojection error to treat a point pair as an inlier (used in the RANSAC method only).

  • get_mask (Boolean) (defaults to: false)

    If true, the optional output mask set by a robust method (:ransac or :lmeds) is returned additionally.

Returns:

  • (CvMat, Array<CvMat>)

    The perspective transformation H between the source and the destination planes in CvMat. If method is :ransac or :lmeds and get_mask is true, the output mask is also returned in the form of an array [H, output_mask].



3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
# File 'ext/opencv/cvmat.cpp', line 3832

VALUE
rb_find_homography(int argc, VALUE *argv, VALUE self)
{
  VALUE src_points, dst_points, method, ransac_reproj_threshold, get_status;
  rb_scan_args(argc, argv, "23", &src_points, &dst_points, &method, &ransac_reproj_threshold, &get_status);

  VALUE homography = new_object(cvSize(3, 3), CV_32FC1);
  int _method = CVMETHOD("HOMOGRAPHY_CALC_METHOD", method, 0);
  double _ransac_reproj_threshold = NIL_P(ransac_reproj_threshold) ? 0.0 : NUM2DBL(ransac_reproj_threshold);

  if ((_method != 0) && (!NIL_P(get_status)) && IF_BOOL(get_status, 1, 0, 0)) {
    CvMat *src = CVMAT_WITH_CHECK(src_points);
    int num_points = MAX(src->rows, src->cols);
    VALUE status = new_object(cvSize(num_points, 1), CV_8UC1);
    try {
      cvFindHomography(src, CVMAT_WITH_CHECK(dst_points), CVMAT(homography),
		       _method, _ransac_reproj_threshold, CVMAT(status));
    }
    catch (cv::Exception& e) {
      raise_cverror(e);
    }
    return rb_assoc_new(homography, status);
  }
  else {
    try {
      cvFindHomography(CVMAT(src_points), CVMAT(dst_points), CVMAT(homography),
		       _method, _ransac_reproj_threshold, NULL);
    }
    catch (cv::Exception& e) {
      raise_cverror(e);
    }
    return homography;
  }
}

.get_perspective_transform(src, dst) ⇒ CvMat

Calculates a perspective transform from four pairs of the corresponding points.

Parameters:

  • src (Array<CvPoint>)

    Coordinates of quadrangle vertices in the source image.

  • dst (Array<CvPoint>)

    Coordinates of the corresponding quadrangle vertices in the destination image.

Returns:



3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
# File 'ext/opencv/cvmat.cpp', line 3902

VALUE
rb_get_perspective_transform(VALUE self, VALUE source, VALUE dest)
{
  Check_Type(source, T_ARRAY);
  Check_Type(dest, T_ARRAY);

  int count = RARRAY_LEN(source);

  CvPoint2D32f* source_buff = ALLOCA_N(CvPoint2D32f, count);
  CvPoint2D32f* dest_buff = ALLOCA_N(CvPoint2D32f, count);

  for (int i = 0; i < count; i++) {
    source_buff[i] = *(CVPOINT2D32F(RARRAY_PTR(source)[i]));
    dest_buff[i] = *(CVPOINT2D32F(RARRAY_PTR(dest)[i]));
  }

  VALUE map_matrix = new_object(cvSize(3, 3), CV_MAKETYPE(CV_32F, 1));

  try {
    cvGetPerspectiveTransform(source_buff, dest_buff, CVMAT(map_matrix));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return map_matrix;
}

.load(filename, iscolor = 1) ⇒ CvMat

Load an image from the specified file

Parameters:

  • filename (String)

    Name of file to be loaded

  • iscolor (Integer)

    Flags specifying the color type of a loaded image:

    • > 0 Return a 3-channel color image.

    • = 0 Return a grayscale image.

    • < 0 Return the loaded image as is.

Returns:

  • (CvMat)

    Loaded image



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'ext/opencv/cvmat.cpp', line 156

VALUE
rb_load_imageM(int argc, VALUE *argv, VALUE self)
{
  VALUE filename, iscolor;
  rb_scan_args(argc, argv, "11", &filename, &iscolor);
  Check_Type(filename, T_STRING);

  int _iscolor;
  if (NIL_P(iscolor)) {
    _iscolor = CV_LOAD_IMAGE_COLOR;
  }
  else {
    Check_Type(iscolor, T_FIXNUM);
    _iscolor = FIX2INT(iscolor);
  }

  CvMat *mat = NULL;
  try {
    mat = cvLoadImageM(StringValueCStr(filename), _iscolor);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  if (mat == NULL) {
    rb_raise(rb_eStandardError, "file does not exist or invalid format image.");
  }
  return OPENCV_OBJECT(rb_klass, mat);
}

.merge(src1 = nil, src2 = nil, src3 = nil, src4 = nil) ⇒ CvMat

Composes a multi-channel array from several single-channel arrays.

Parameters:

  • src-n (CvMat)

    Source arrays to be merged. All arrays must have the same size and the same depth.

Returns:

  • (CvMat)

    Merged array

See Also:



1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'ext/opencv/cvmat.cpp', line 1445

VALUE
rb_merge(VALUE klass, VALUE args)
{
  int len = RARRAY_LEN(args);
  if (len <= 0 || len > 4) {
    rb_raise(rb_eArgError, "wrong number of argument (%d for 1..4)", len);
  }
  CvMat *src[] = { NULL, NULL, NULL, NULL }, *prev_src = NULL;
  for (int i = 0; i < len; ++i) {
    VALUE object = rb_ary_entry(args, i);
    if (NIL_P(object))
      src[i] = NULL;
    else {
      src[i] = CVMAT_WITH_CHECK(object);
      if (CV_MAT_CN(src[i]->type) != 1)
        rb_raise(rb_eArgError, "image should be single-channel CvMat.");
      if (prev_src == NULL)
        prev_src = src[i];
      else {
        if (!CV_ARE_SIZES_EQ(prev_src, src[i]))
          rb_raise(rb_eArgError, "image size should be same.");
        if (!CV_ARE_DEPTHS_EQ(prev_src, src[i]))
          rb_raise(rb_eArgError, "image depth should be same.");
      }
    }
  }
  // TODO: adapt IplImage
  VALUE dest = Qnil;
  try {
    dest = new_object(cvGetSize(src[0]), CV_MAKETYPE(CV_MAT_DEPTH(src[0]->type), len));
    cvMerge(src[0], src[1], src[2], src[3], CVARR(dest));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

.norm(src1, src2 = nil, norm_type = NORM_L2, mask = nil) ⇒ Number

Calculates an absolute array norm, an absolute difference norm, or a relative difference norm.

Parameters:

  • src1 (CvMat)

    First input array.

  • src2 (CvMat)

    Second input array of the same size and the same type as src1.

  • norm_type (Integer)

    Type of the norm.

  • mask (CvMat)

    Optional operation mask; it must have the same size as src1 and CV_8UC1 type.

Returns:

  • (Number)

    The norm of two arrays.



2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
# File 'ext/opencv/cvmat.cpp', line 2291

VALUE
rb_norm(int argc, VALUE *argv, VALUE self)
{
  VALUE src1, src2, norm_type_val, mask_val;
  rb_scan_args(argc, argv, "13", &src1, &src2, &norm_type_val, &mask_val);

  CvMat *src1_ptr = NULL;
  CvMat *src2_ptr = NULL;
  int norm_type = NIL_P(norm_type_val) ? cv::NORM_L2 : NUM2INT(norm_type_val);
  CvMat *mask = NULL;
  double norm = 0.0;

  try {
    src1_ptr = CVMAT_WITH_CHECK(src1);
    if (!NIL_P(src2)) {
      src2_ptr = CVMAT_WITH_CHECK(src2);
    }
    if (!NIL_P(mask_val)) {
      mask = CVMAT_WITH_CHECK(mask_val);
    }
    norm = cvNorm(src1_ptr, src2_ptr, norm_type, mask);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return DBL2NUM(norm);
}

.rotation_matrix2D(center, angle, scale) ⇒ CvMat

Calculates an affine matrix of 2D rotation.

Parameters:

  • center (CvPoint2D32f)

    Center of the rotation in the source image.

  • angle (Number)

    Rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner).

  • scale (Number)

    Isotropic scale factor.

Returns:

  • (CvMat)

    The output affine transformation, 2x3 floating-point matrix.



3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
# File 'ext/opencv/cvmat.cpp', line 3879

VALUE
rb_rotation_matrix2D(VALUE self, VALUE center, VALUE angle, VALUE scale)
{
  VALUE map_matrix = new_object(cvSize(3, 2), CV_MAKETYPE(CV_32F, 1));
  try {
    cv2DRotationMatrix(VALUE_TO_CVPOINT2D32F(center), NUM2DBL(angle), NUM2DBL(scale), CVMAT(map_matrix));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return map_matrix;
}

.solve(src1, src2, inversion_method = :lu) ⇒ Number

Solves one or more linear systems or least-squares problems.

Parameters:

  • src1 (CvMat)

    Input matrix on the left-hand side of the system.

  • src2 (CvMat)

    Input matrix on the right-hand side of the system.

  • inversion_method (Symbol)

    Inversion method.

    • :lu - Gaussian elimincation with optimal pivot element chose.

    • :svd - Singular value decomposition(SVD) method.

    • :svd_sym - SVD method for a symmetric positively-defined matrix.

Returns:

  • (Number)

    Output solution.



2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
# File 'ext/opencv/cvmat.cpp', line 2564

VALUE
rb_solve(int argc, VALUE *argv, VALUE self)
{
  VALUE src1, src2, symbol;
  rb_scan_args(argc, argv, "21", &src1, &src2, &symbol);
  VALUE dest = Qnil;
  CvArr* src2_ptr = CVARR_WITH_CHECK(src2);
  try {
    dest = new_mat_kind_object(cvGetSize(src2_ptr), src2);
    cvSolve(CVARR_WITH_CHECK(src1), src2_ptr, CVARR(dest), CVMETHOD("INVERSION_METHOD", symbol, CV_LU));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

Instance Method Details

#[](idx0) ⇒ CvScalar #[](idx0, idx1) ⇒ CvScalar #[](idx0, idx1, idx2) ⇒ CvScalar #[](idx0, idx1, idx2, ...) ⇒ CvScalar Also known as: at

Returns a specific array element.

Parameters:

  • idx-n (Integer)

    Zero-based component of the element index

Returns:



978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
# File 'ext/opencv/cvmat.cpp', line 978

VALUE
rb_aref(VALUE self, VALUE args)
{
  int index[CV_MAX_DIM];
  for (int i = 0; i < RARRAY_LEN(args); ++i)
    index[i] = NUM2INT(rb_ary_entry(args, i));
  
  CvScalar scalar = cvScalarAll(0);
  try {
    switch (RARRAY_LEN(args)) {
    case 1:
      scalar = cvGet1D(CVARR(self), index[0]);
      break;
    case 2:
      scalar = cvGet2D(CVARR(self), index[0], index[1]);
      break;
    default:
      scalar = cvGetND(CVARR(self), index);
      break;      
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return cCvScalar::new_object(scalar);
}

#[]=(idx0, value) ⇒ CvMat #[]=(idx0, idx1, value) ⇒ CvMat #[]=(idx0, idx1, idx2, value) ⇒ CvMat #[]=(idx0, idx1, idx2, ..., value) ⇒ CvMat

Changes the particular array element

Parameters:

  • idx-n (Integer)

    Zero-based component of the element index

  • value (CvScalar)

    The assigned value

Returns:



1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
# File 'ext/opencv/cvmat.cpp', line 1019

VALUE
rb_aset(VALUE self, VALUE args)
{
  CvScalar scalar = VALUE_TO_CVSCALAR(rb_ary_pop(args));
  int index[CV_MAX_DIM];
  for (int i = 0; i < RARRAY_LEN(args); ++i)
    index[i] = NUM2INT(rb_ary_entry(args, i));

  try {
    switch (RARRAY_LEN(args)) {
    case 1:
      cvSet1D(CVARR(self), index[0], scalar);
      break;
    case 2:
      cvSet2D(CVARR(self), index[0], index[1], scalar);
      break;
    default:
      cvSetND(CVARR(self), index, scalar);
      break;
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#abs_diff(val) ⇒ CvMat

Computes the per-element absolute difference between two arrays or between an array and a scalar.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to compute absolute difference

Returns:

  • (CvMat)

    Result array



2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
# File 'ext/opencv/cvmat.cpp', line 2077

VALUE
rb_abs_diff(VALUE self, VALUE val)
{
  CvArr* self_ptr = CVARR(self);
  VALUE dest = new_mat_kind_object(cvGetSize(self_ptr), self);
  try {
    if (rb_obj_is_kind_of(val, rb_klass))
      cvAbsDiff(self_ptr, CVARR(val), CVARR(dest));
    else
      cvAbsDiffS(self_ptr, CVARR(dest), VALUE_TO_CVSCALAR(val));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#adaptive_threshold(max_value, options) ⇒ CvMat

Applies an adaptive threshold to an array.

Examples:

mat = CvMat.new(3, 3, CV_8U, 1)
mat.set_data([1, 2, 3, 4, 5, 6, 7, 8, 9])
mat #=> [1, 2, 3,
         4, 5, 6,
         7, 8, 9]
result = mat.adaptive_threshold(7, threshold_type: CV_THRESH_BINARY,
                                adaptive_method: CV_ADAPTIVE_THRESH_MEAN_C,
                                block_size: 3, param1: 1)
result #=> [0, 0, 0,
            7, 7, 7,
            7, 7, 7]

Returns Destination image of the same size and the same type as self.

Parameters:

  • max_value (Number)

    Non-zero value assigned to the pixels for which the condition is satisfied.

  • options (Hash)

    Threshold option

Options Hash (options):

  • :threshold_type (Integer, Symbol) — default: CV_THRESH_BINARY

    Thresholding type; must be one of CV_THRESH_BINARY or :binary, CV_THRESH_BINARY_INV or :binary_inv.

  • :adaptive_method (Integer, Symbol) — default: CV_ADAPTIVE_THRESH_MEAN_C

    Adaptive thresholding algorithm to use: CV_ADAPTIVE_THRESH_MEAN_C or :mean_c, CV_ADAPTIVE_THRESH_GAUSSIAN_C or :gaussian_c.

  • :block_size (Integer) — default: 3

    The size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.

  • :param1 (Number) — default: 5

    The method-dependent parameter. For the methods CV_ADAPTIVE_THRESH_MEAN_C and CV_ADAPTIVE_THRESH_GAUSSIAN_C it is a constant subtracted from the mean or weighted mean, though it may be negative

Returns:

  • (CvMat)

    Destination image of the same size and the same type as self.



4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
# File 'ext/opencv/cvmat.cpp', line 4544

VALUE
rb_adaptive_threshold(int argc, VALUE *argv, VALUE self)
{
  VALUE max_value, options;
  rb_scan_args(argc, argv, "11", &max_value, &options);

  int threshold_type = CV_THRESH_BINARY;
  int adaptive_method = CV_ADAPTIVE_THRESH_MEAN_C;
  int block_size = 3;
  double param1 = 5;
  if (!NIL_P(options)) {
    Check_Type(options, T_HASH);
    threshold_type = CVMETHOD("THRESHOLD_TYPE", LOOKUP_HASH(options, "threshold_type"),
			      CV_THRESH_BINARY);
    adaptive_method = CVMETHOD("ADAPTIVE_METHOD", LOOKUP_HASH(options, "adaptive_method"),
			       CV_ADAPTIVE_THRESH_MEAN_C);
    VALUE _block_size = LOOKUP_HASH(options, "block_size");
    if (!NIL_P(_block_size)) {
      block_size = NUM2INT(_block_size);
    }
    VALUE _param1 = LOOKUP_HASH(options, "param1");
    if (!NIL_P(_param1)) {
      param1 = NUM2INT(_param1);
    }
  }
  CvArr* self_ptr = CVARR(self);
  VALUE dst = new_mat_kind_object(cvGetSize(self_ptr), self);
  try {
    cvAdaptiveThreshold(self_ptr, CVARR(dst), NUM2DBL(max_value), adaptive_method, threshold_type,
			block_size, param1);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  
  return dst;
}

#add(val, mask = nil) ⇒ CvMat Also known as: +

Computes the per-element sum of two arrays or an array and a scalar.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to add

  • mask (CvMat)

    Optional operation mask, 8-bit single channel array, that specifies elements of the destination array to be changed.

Returns:

  • (CvMat)

    Result array



1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
# File 'ext/opencv/cvmat.cpp', line 1625

VALUE
rb_add(int argc, VALUE *argv, VALUE self)
{
  VALUE val, mask, dest;
  rb_scan_args(argc, argv, "11", &val, &mask);
  dest = copy(self);
  try {
    if (rb_obj_is_kind_of(val, rb_klass))
      cvAdd(CVARR(self), CVARR(val), CVARR(dest), MASK(mask));
    else
      cvAddS(CVARR(self), VALUE_TO_CVSCALAR(val), CVARR(dest), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#and(val, mask = nil) ⇒ CvMat Also known as: &

Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to calculate bit-wise conjunction

  • mask (CvMat)

    Optional operation mask, 8-bit single channel array, that specifies elements of the destination array to be changed.

Returns:

  • (CvMat)

    Result array



1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
# File 'ext/opencv/cvmat.cpp', line 1810

VALUE
rb_and(int argc, VALUE *argv, VALUE self)
{
  VALUE val, mask, dest;
  rb_scan_args(argc, argv, "11", &val, &mask);
  dest = copy(self);
  try {
    if (rb_obj_is_kind_of(val, rb_klass))
      cvAnd(CVARR(self), CVARR(val), CVARR(dest), MASK(mask));
    else
      cvAndS(CVARR(self), VALUE_TO_CVSCALAR(val), CVARR(dest), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#apply_color_map(colormap) ⇒ Object

Applies a GNU Octave/MATLAB equivalent colormap on a given image.

Parameters:

colormap - The colormap to apply.


5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
# File 'ext/opencv/cvmat.cpp', line 5171

VALUE
rb_apply_color_map(VALUE self, VALUE colormap)
{
  VALUE dst;
  try {
    cv::Mat dst_mat;
    cv::Mat self_mat(CVMAT(self));

    cv::applyColorMap(self_mat, dst_mat, NUM2INT(colormap));
    CvMat tmp = dst_mat;
    dst = new_object(tmp.rows, tmp.cols, tmp.type);
    cvCopy(&tmp, CVMAT(dst));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return dst;
}

#avg(mask = nil) ⇒ CvScalar

Calculates an average (mean) of array elements.

Parameters:

  • mask (CvMat)

    Optional operation mask.

Returns:

  • (CvScalar)

    The average of array elements.



2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
# File 'ext/opencv/cvmat.cpp', line 2191

VALUE
rb_avg(int argc, VALUE *argv, VALUE self)
{
  VALUE mask;
  rb_scan_args(argc, argv, "01", &mask);
  CvScalar avg;
  try {
    avg = cvAvg(CVARR(self), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return cCvScalar::new_object(avg);
}

#avg_sdv(mask = nil) ⇒ Array<CvScalar>

Calculates a mean and standard deviation of array elements.

Parameters:

  • mask (CvMat)

    Optional operation mask.

Returns:

  • (Array<CvScalar>)

    [mean, stddev], where mean is the computed mean value and stddev is the computed standard deviation.



2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
# File 'ext/opencv/cvmat.cpp', line 2214

VALUE
rb_avg_sdv(int argc, VALUE *argv, VALUE self)
{
  VALUE mask, mean, std_dev;
  rb_scan_args(argc, argv, "01", &mask);
  mean = cCvScalar::new_object();
  std_dev = cCvScalar::new_object();
  try {
    cvAvgSdv(CVARR(self), CVSCALAR(mean), CVSCALAR(std_dev), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(2, mean, std_dev);
}

#cam_shift(window, criteria) ⇒ Array

Implements CAMSHIFT object tracking algrorithm. First, it finds an object center using cvMeanShift and, after that, calculates the object size and orientation. The function returns number of iterations made within cvMeanShift.

Returns:

  • (Array)


5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
# File 'ext/opencv/cvmat.cpp', line 5299

VALUE
rb_cam_shift(VALUE self, VALUE window, VALUE criteria)
{
  VALUE comp = cCvConnectedComp::new_object();
  VALUE box = cCvBox2D::new_object();
  try {
    cvCamShift(CVARR(self), VALUE_TO_CVRECT(window), VALUE_TO_CVTERMCRITERIA(criteria),
	       CVCONNECTEDCOMP(comp), CVBOX2D(box));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(2, comp, box);
}

#canny(thresh1, thresh2, aperture_size = 3) ⇒ CvMat

Finds edges in an image using the [Canny86] algorithm.

Canny86: J. Canny. A Computational Approach to Edge Detection, IEEE Trans. on Pattern Analysis and Machine Intelligence, 8(6), pp. 679-698 (1986).

Parameters:

  • thresh1 (Number)

    First threshold for the hysteresis procedure.

  • thresh2 (Number)

    Second threshold for the hysteresis procedure.

  • aperture_size (Integer)

    Aperture size for the sobel operator.

Returns:

  • (CvMat)

    Output edge map



3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
# File 'ext/opencv/cvmat.cpp', line 3399

VALUE
rb_canny(int argc, VALUE *argv, VALUE self)
{
  VALUE thresh1, thresh2, aperture_size;
  if (rb_scan_args(argc, argv, "21", &thresh1, &thresh2, &aperture_size) < 3)
    aperture_size = INT2FIX(3);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = new_mat_kind_object(cvGetSize(self_ptr), self);
  
  try {
    cvCanny(self_ptr, CVARR(dest), NUM2INT(thresh1), NUM2INT(thresh2), NUM2INT(aperture_size));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#channelInteger

Returns number of channels of the matrix

Returns:

  • (Integer)

    Number of channels of the matrix



457
458
459
460
461
# File 'ext/opencv/cvmat.cpp', line 457

VALUE
rb_channel(VALUE self)
{
  return INT2FIX(CV_MAT_CN(CVMAT(self)->type));
}

#circle(center, radius, options = nil) ⇒ CvMat

Returns an image that is drawn a circle

Parameters:

  • center (CvPoint)

    Center of the circle.

  • radius (Integer)

    Radius of the circle.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



2870
2871
2872
2873
2874
# File 'ext/opencv/cvmat.cpp', line 2870

VALUE
rb_circle(int argc, VALUE *argv, VALUE self)
{
  return rb_circle_bang(argc, argv, rb_clone(self));
}

#circle!(center, radius, options = nil) ⇒ CvMat

Draws a circle

Parameters:

  • center (CvPoint)

    Center of the circle.

  • radius (Integer)

    Radius of the circle.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
# File 'ext/opencv/cvmat.cpp', line 2893

VALUE
rb_circle_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE center, radius, drawing_option;
  rb_scan_args(argc, argv, "21", &center, &radius, &drawing_option);
  drawing_option = DRAWING_OPTION(drawing_option);
  try {
    cvCircle(CVARR(self), VALUE_TO_CVPOINT(center), NUM2INT(radius),
	     DO_COLOR(drawing_option),
	     DO_THICKNESS(drawing_option),
	     DO_LINE_TYPE(drawing_option),
	     DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#cloneCvMat

Makes a clone of an object.

Returns:

  • (CvMat)

    Clone of the object



480
481
482
483
484
485
486
487
488
489
490
491
# File 'ext/opencv/cvmat.cpp', line 480

VALUE
rb_clone(VALUE self)
{
  VALUE clone = rb_obj_clone(self);
  try {
    DATA_PTR(clone) = cvClone(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return clone;
}

#convert_scale(params) ⇒ CvMat

Converts one array to another with optional linear transformation.

Parameters:

  • params (Hash)

    Transform parameters

Options Hash (params):

  • :depth (Integer) — default: same as self

    Depth of the destination array

  • :scale (Number) — default: 1.0

    Scale factor

  • :shift (Number) — default: 0.0

    Value added to the scaled source array elements

Returns:

  • (CvMat)

    Converted array



1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
# File 'ext/opencv/cvmat.cpp', line 1564

VALUE
rb_convert_scale(VALUE self, VALUE hash)
{
  Check_Type(hash, T_HASH);
  CvMat* self_ptr = CVMAT(self);
  VALUE depth = LOOKUP_HASH(hash, "depth");
  VALUE scale = LOOKUP_HASH(hash, "scale");
  VALUE shift = LOOKUP_HASH(hash, "shift");

  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self,
			       CVMETHOD("DEPTH", depth, CV_MAT_DEPTH(self_ptr->type)),
			       CV_MAT_CN(self_ptr->type));
    cvConvertScale(self_ptr, CVARR(dest), IF_DBL(scale, 1.0), IF_DBL(shift, 0.0));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#convert_scale_abs(params) ⇒ CvMat

Scales, computes absolute values, and converts the result to 8-bit.

Parameters:

  • params (Hash)

    Transform parameters

Options Hash (params):

  • :scale (Number) — default: 1.0

    Scale factor

  • :shift (Number) — default: 0.0

    Value added to the scaled source array elements

Returns:

  • (CvMat)

    Converted array



1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
# File 'ext/opencv/cvmat.cpp', line 1596

VALUE
rb_convert_scale_abs(VALUE self, VALUE hash)
{
  Check_Type(hash, T_HASH);
  CvMat* self_ptr = CVMAT(self);
  VALUE scale = LOOKUP_HASH(hash, "scale");
  VALUE shift = LOOKUP_HASH(hash, "shift");
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self, CV_8U, CV_MAT_CN(CVMAT(self)->type));
    cvConvertScaleAbs(self_ptr, CVARR(dest), IF_DBL(scale, 1.0), IF_DBL(shift, 0.0));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#copy(dst = nil, mask = nil) ⇒ CvMat

Copies one array to another.

The function copies selected elements from an input array to an output array:

dst(I) = src(I) if mask(I) != 0

Parameters:

  • dst (CvMat)

    The destination array.

  • mask (CvMat)

    Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed.

Returns:

  • (CvMat)

    Copy of the array



506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'ext/opencv/cvmat.cpp', line 506

VALUE
rb_copy(int argc, VALUE *argv, VALUE self)
{
  VALUE _dst, _mask;
  rb_scan_args(argc, argv, "02", &_dst, &_mask);

  CvMat* mask = MASK(_mask);
  CvArr *src = CVARR(self);
  if (NIL_P(_dst)) {
    CvSize size = cvGetSize(src);
    _dst = new_mat_kind_object(size, self);
  }

  try {
    cvCopy(src, CVARR_WITH_CHECK(_dst), mask);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return _dst;
}

#copy_make_border(border_type, size, offset[,value = CvScalar.new(0)]) ⇒ Object

Copies image and makes border around it. border_type:

  • IPL_BORDER_CONSTANT, :constant

    border is filled with the fixed value, passed as last parameter of the function.
    
  • IPL_BORDER_REPLICATE, :replicate

    the pixels from the top and bottom rows, the left-most and right-most columns are replicated to fill the border
    

size: The destination image size offset: Coordinates of the top-left corner (or bottom-left in the case of images with bottom-left origin) of the destination image rectangle. value: Value of the border pixels if bordertype is IPL_BORDER_CONSTANT or :constant.



4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
# File 'ext/opencv/cvmat.cpp', line 4362

VALUE
rb_copy_make_border(int argc, VALUE *argv, VALUE self)
{
  VALUE border_type, size, offset, value, dest;
  rb_scan_args(argc, argv, "31", &border_type, &size, &offset, &value);
  dest = new_mat_kind_object(VALUE_TO_CVSIZE(size), self);

  int type = 0;
  if (SYMBOL_P(border_type)) {
    ID type_id = rb_to_id(border_type);
    if (type_id == rb_intern("constant"))
      type = IPL_BORDER_CONSTANT;
    else if (type_id == rb_intern("replicate"))
      type = IPL_BORDER_REPLICATE;
    else
      rb_raise(rb_eArgError, "Invalid border_type (should be :constant or :replicate)");
  }
  else
    type = NUM2INT(border_type);

  try {
    cvCopyMakeBorder(CVARR(self), CVARR(dest), VALUE_TO_CVPOINT(offset), type,
		     NIL_P(value) ? cvScalar(0) : VALUE_TO_CVSCALAR(value));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#corner_eigenvv(block_size, aperture_size = 3) ⇒ CvMat

Calculates eigenvalues and eigenvectors of image blocks for corner detection.

Parameters:

  • block_size (Integer)

    Neighborhood size.

  • aperture_size (Integer)

    Aperture parameter for the sobel operator.

Returns:

  • (CvMat)

    Result array.



3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
# File 'ext/opencv/cvmat.cpp', line 3452

VALUE
rb_corner_eigenvv(int argc, VALUE *argv, VALUE self)
{
  VALUE block_size, aperture_size, dest;
  if (rb_scan_args(argc, argv, "11", &block_size, &aperture_size) < 2)
    aperture_size = INT2FIX(3);
  CvMat* self_ptr = CVMAT(self);
  dest = new_object(cvSize(self_ptr->cols * 6, self_ptr->rows), CV_MAKETYPE(CV_32F, 1));
  try {
    cvCornerEigenValsAndVecs(self_ptr, CVARR(dest), NUM2INT(block_size), NUM2INT(aperture_size));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#corner_harris(block_size, aperture_size = 3, k = 0.04) ⇒ CvMat

Harris edge detector.

Parameters:

  • block_size (Integer)

    Neighborhood size.

  • aperture_size (Integer)

    Aperture parameter for the sobel operator.

  • k (Number)

    Harris detector free parameter.

Returns:

  • (CvMat)

    The Harris detector responses.



3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
# File 'ext/opencv/cvmat.cpp', line 3505

VALUE
rb_corner_harris(int argc, VALUE *argv, VALUE self)
{
  VALUE block_size, aperture_size, k, dest;
  rb_scan_args(argc, argv, "12", &block_size, &aperture_size, &k);
  CvArr* self_ptr = CVARR(self);
  dest = new_object(cvGetSize(self_ptr), CV_MAKETYPE(CV_32F, 1));
  try {
    cvCornerHarris(self_ptr, CVARR(dest), NUM2INT(block_size), IF_INT(aperture_size, 3), IF_DBL(k, 0.04));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#corner_min_eigen_val(block_size, aperture_size = 3) ⇒ CvMat

Calculates the minimal eigenvalue of gradient matrices for corner detection.

Parameters:

  • block_size (Integer)

    Neighborhood size.

  • aperture_size (Integer)

    Aperture parameter for the sobel operator.

Returns:

  • (CvMat)

    Result array.



3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
# File 'ext/opencv/cvmat.cpp', line 3478

VALUE
rb_corner_min_eigen_val(int argc, VALUE *argv, VALUE self)
{
  VALUE block_size, aperture_size, dest;
  if (rb_scan_args(argc, argv, "11", &block_size, &aperture_size) < 2)
    aperture_size = INT2FIX(3);
  CvArr* self_ptr = CVARR(self);
  dest = new_object(cvGetSize(self_ptr), CV_MAKETYPE(CV_32F, 1));
  try {
    cvCornerMinEigenVal(self_ptr, CVARR(dest), NUM2INT(block_size), NUM2INT(aperture_size));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#count_non_zeroInteger

Counts non-zero array elements.

Returns:

  • (Integer)

    The number of non-zero elements.



2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
# File 'ext/opencv/cvmat.cpp', line 2151

VALUE
rb_count_non_zero(VALUE self)
{
  int n = 0;
  try {
    n = cvCountNonZero(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return INT2NUM(n);
}

#create_maskCvMat

Creates a mask (1-channel 8bit unsinged image whose elements are 0) from the matrix. The size of the mask is the same as source matrix.

Returns:

  • (CvMat)

    Created mask



404
405
406
407
408
409
410
411
412
413
414
415
# File 'ext/opencv/cvmat.cpp', line 404

VALUE
rb_create_mask(VALUE self)
{
  VALUE mask = cCvMat::new_object(cvGetSize(CVARR(self)), CV_8UC1);
  try {
    cvZero(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return mask;
}

#cross_product(mat) ⇒ CvMat

Calculates the cross product of two 3D vectors.

Parameters:

  • mat (CvMat)

    A vector to calculate the cross product.

Returns:

  • (CvMat)

    The cross product of two vectors.



2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
# File 'ext/opencv/cvmat.cpp', line 2349

VALUE
rb_cross_product(VALUE self, VALUE mat)
{
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvCrossProduct(self_ptr, CVARR_WITH_CHECK(mat), CVARR(dest));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#dataObject

Deprecated.

This method will be removed.



467
468
469
470
471
472
# File 'ext/opencv/cvmat.cpp', line 467

VALUE
rb_data(VALUE self)
{
  IplImage *image = IPLIMAGE(self);
  return rb_str_new((char *)image->imageData, image->imageSize);
}

#dct(flags = CV_DXT_FORWARD) ⇒ CvMat

Performs forward or inverse Discrete Cosine Transform(DCT) of 1D or 2D floating-point array.

Parameters:

  • flags (Integer) (defaults to: CV_DXT_FORWARD)

    transformation flags, representing a combination of the following values:

    • CV_DXT_FORWARD - Performs a 1D or 2D transform.

    • CV_DXT_INVERSE - Performs an inverse 1D or 2D transform instead of the default forward transform.

    • CV_DXT_ROWS - 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.

Returns:

  • (CvMat)

    Output array



2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
# File 'ext/opencv/cvmat.cpp', line 2716

VALUE
rb_dct(int argc, VALUE *argv, VALUE self)
{
  VALUE flag_value;
  rb_scan_args(argc, argv, "01", &flag_value);

  int flags = NIL_P(flag_value) ? CV_DXT_FORWARD : NUM2INT(flag_value);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvDCT(self_ptr, CVARR(dest), flags);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#depthSymbol

Returns depth type of the matrix

Returns:

  • (Symbol)

    Depth type in the form of symbol :cv<bit depth><s|u|f>, where s=signed, u=unsigned, f=float.



445
446
447
448
449
450
# File 'ext/opencv/cvmat.cpp', line 445

VALUE
rb_depth(VALUE self)
{
  return rb_hash_lookup(rb_funcall(rb_const_get(rb_module_opencv(), rb_intern("DEPTH")), rb_intern("invert"), 0),
			INT2FIX(CV_MAT_DEPTH(CVMAT(self)->type)));
}

#detNumber Also known as: determinant

Returns the determinant of a square floating-point matrix.

Returns:

  • (Number)

    The determinant of the matrix.



2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
# File 'ext/opencv/cvmat.cpp', line 2508

VALUE
rb_det(VALUE self)
{
  double det = 0.0;
  try {
    det = cvDet(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_float_new(det);
}

#dft(flags = CV_DXT_FORWARD, nonzero_rows = 0) ⇒ CvMat

Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.

Parameters:

  • flags (Integer) (defaults to: CV_DXT_FORWARD)

    transformation flags, representing a combination of the following values:

    • CV_DXT_FORWARD - Performs a 1D or 2D transform.

    • CV_DXT_INVERSE - Performs an inverse 1D or 2D transform instead of the default forward transform.

    • CV_DXT_SCALE - Scales the result: divide it by the number of array elements. Normally, it is combined with CV_DXT_INVERSE.

    • CV_DXT_INV_SCALE - CV_DXT_INVERSE + CV_DXT_SCALE

  • nonzero_rows (Integer) (defaults to: 0)

    when the parameter is not zero, the function assumes that only the first nonzero_rows rows of the input array (CV_DXT_INVERSE is not set) or only the first nonzero_rows of the output array (CV_DXT_INVERSE is set) contain non-zeros.

Returns:

  • (CvMat)

    Output array



2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
# File 'ext/opencv/cvmat.cpp', line 2682

VALUE
rb_dft(int argc, VALUE *argv, VALUE self)
{
  VALUE flag_value, nonzero_row_value;
  rb_scan_args(argc, argv, "02", &flag_value, &nonzero_row_value);

  int flags = NIL_P(flag_value) ? CV_DXT_FORWARD : NUM2INT(flag_value);
  int nonzero_rows = NIL_P(nonzero_row_value) ? 0 : NUM2INT(nonzero_row_value);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvDFT(self_ptr, CVARR(dest), flags, nonzero_rows);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#diag(val = 0) ⇒ CvMat Also known as: diagonal

Returns a specified diagonal of the matrix

Parameters:

  • val (Integer)

    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.

Returns:

  • (CvMat)

    Specified diagonal



882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'ext/opencv/cvmat.cpp', line 882

VALUE
rb_diag(int argc, VALUE *argv, VALUE self)
{
  VALUE val;
  if (rb_scan_args(argc, argv, "01", &val) < 1)
    val = INT2FIX(0);
  CvMat* diag = NULL;
  try {
    diag = cvGetDiag(CVARR(self), RB_CVALLOC(CvMat), NUM2INT(val));
  }
  catch (cv::Exception& e) {
    cvReleaseMat(&diag);
    raise_cverror(e);
  }
  return DEPEND_OBJECT(rb_klass, diag, self);
}

#dilate([element = nil][,iteration = 1]) ⇒ Object

Create dilates image by using arbitrary structuring element. element is structuring element used for erosion. element should be IplConvKernel. If it is nil, a 3x3 rectangular structuring element is used. iterations is number of times erosion is applied.



4070
4071
4072
4073
4074
# File 'ext/opencv/cvmat.cpp', line 4070

VALUE
rb_dilate(int argc, VALUE *argv, VALUE self)
{
  return rb_dilate_bang(argc, argv, rb_clone(self));
}

#dilate!([element = nil][,iteration = 1]) ⇒ self

Dilate image by using arbitrary structuring element. see also #dilate.

Returns:

  • (self)


4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
# File 'ext/opencv/cvmat.cpp', line 4083

VALUE
rb_dilate_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE element, iteration;
  rb_scan_args(argc, argv, "02", &element, &iteration);
  IplConvKernel* kernel = NIL_P(element) ? NULL : IPLCONVKERNEL_WITH_CHECK(element);
  try {
    cvDilate(CVARR(self), CVARR(self), kernel, IF_INT(iteration, 1));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#dim_size(index) ⇒ Integer

Returns array size along the specified dimension.

Parameters:

  • index (Intger)

    Zero-based dimension index (for matrices 0 means number of rows, 1 means number of columns; for images 0 means height, 1 means width)

Returns:

  • (Integer)

    Array size



952
953
954
955
956
957
958
959
960
961
962
963
# File 'ext/opencv/cvmat.cpp', line 952

VALUE
rb_dim_size(VALUE self, VALUE index)
{
  int dimsize = 0;
  try {
    dimsize = cvGetDimSize(CVARR(self), NUM2INT(index));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return INT2NUM(dimsize);
}

#dimsArray<Integer>

Returns array dimensions sizes

Returns:

  • (Array<Integer>)

    Array dimensions sizes. For 2d arrays the number of rows (height) goes first, number of columns (width) next.



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
# File 'ext/opencv/cvmat.cpp', line 925

VALUE
rb_dims(VALUE self)
{
  int size[CV_MAX_DIM];
  int dims = 0;
  try {
    dims = cvGetDims(CVARR(self), size);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  VALUE ary = rb_ary_new2(dims);
  for (int i = 0; i < dims; ++i) {
    rb_ary_store(ary, i, INT2NUM(size[i]));
  }
  return ary;
}

#div(val, scale = 1.0) ⇒ CvMat Also known as: /

Performs per-element division of two arrays or a scalar by an array.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to divide

  • scale (Number)

    Scale factor

Returns:

  • (CvMat)

    Result array



1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
# File 'ext/opencv/cvmat.cpp', line 1743

VALUE
rb_div(int argc, VALUE *argv, VALUE self)
{
  VALUE val, scale;
  if (rb_scan_args(argc, argv, "11", &val, &scale) < 2)
    scale = rb_float_new(1.0);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    if (rb_obj_is_kind_of(val, rb_klass))
      cvDiv(self_ptr, CVARR(val), CVARR(dest), NUM2DBL(scale));
    else {
      CvScalar scl = VALUE_TO_CVSCALAR(val);
      VALUE mat = new_mat_kind_object(cvGetSize(self_ptr), self);
      CvArr* mat_ptr = CVARR(mat);
      cvSet(mat_ptr, scl);
      cvDiv(self_ptr, mat_ptr, CVARR(dest), NUM2DBL(scale));
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#dot_product(mat) ⇒ Number

Calculates the dot product of two arrays in Euclidean metrics.

Parameters:

  • mat (CvMat)

    An array to calculate the dot product.

Returns:

  • (Number)

    The dot product of two arrays.



2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
# File 'ext/opencv/cvmat.cpp', line 2328

VALUE
rb_dot_product(VALUE self, VALUE mat)
{
  double result = 0.0;
  try {
    result = cvDotProduct(CVARR(self), CVARR_WITH_CHECK(mat));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_float_new(result);
}

#draw_chessboard_corners(pattern_size, corners, pattern_was_found) ⇒ nil

Returns an image which is rendered the detected chessboard corners.

pattern_size (CvSize) - Number of inner corners per a chessboard row and column. corners (Array<CvPoint2D32f>) - Array of detected corners, the output of CvMat#find_chessboard_corners. pattern_was_found (Boolean)- Parameter indicating whether the complete board was found or not.

Returns:

  • (nil)


4865
4866
4867
4868
4869
# File 'ext/opencv/cvmat.cpp', line 4865

VALUE
rb_draw_chessboard_corners(VALUE self, VALUE pattern_size, VALUE corners, VALUE pattern_was_found)
{
  return rb_draw_chessboard_corners_bang(copy(self), pattern_size, corners, pattern_was_found);
}

#draw_chessboard_corners!(pattern_size, corners, pattern_was_found) ⇒ self

Renders the detected chessboard corners.

pattern_size (CvSize) - Number of inner corners per a chessboard row and column. corners (Array<CvPoint2D32f>) - Array of detected corners, the output of CvMat#find_chessboard_corners. pattern_was_found (Boolean)- Parameter indicating whether the complete board was found or not.

Returns:

  • (self)


4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
# File 'ext/opencv/cvmat.cpp', line 4881

VALUE
rb_draw_chessboard_corners_bang(VALUE self, VALUE pattern_size, VALUE corners, VALUE pattern_was_found)
{
  Check_Type(corners, T_ARRAY);
  int count = RARRAY_LEN(corners);
  CvPoint2D32f* corners_buff = ALLOCA_N(CvPoint2D32f, count);
  VALUE* corners_ptr = RARRAY_PTR(corners);
  for (int i = 0; i < count; i++) {
    corners_buff[i] = *(CVPOINT2D32F(corners_ptr[i]));
  }

  try {
    int found = (pattern_was_found == Qtrue);
    cvDrawChessboardCorners(CVARR(self), VALUE_TO_CVSIZE(pattern_size), corners_buff, count, found);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return self;
}

#draw_contours(contour, external_color, hole_color, max_level, options) ⇒ Object

Draws contour outlines or interiors in an image.

  • contour (CvContour) - Pointer to the first contour

  • external_color (CvScalar) - Color of the external contours

  • hole_color (CvScalar) - Color of internal contours (holes)

  • max_level (Integer) - Maximal level for drawn contours. If 0, only contour is drawn. If 1, the contour and all contours following it on the same level are drawn. If 2, all contours following and all contours one level below the contours are drawn, and so forth. If the value is negative, the function does not draw the contours following after contour but draws the child contours of contour up to the |max_level| - 1 level.

  • options (Hash) - Drawing options.

    • :thickness (Integer) - Thickness of lines the contours are drawn with. If it is negative, the contour interiors are drawn (default: 1).

    • :line_type (Integer or Symbol) - Type of the contour segments, see CvMat#line description (default: 8).



4824
4825
4826
4827
4828
# File 'ext/opencv/cvmat.cpp', line 4824

VALUE
rb_draw_contours(int argc, VALUE *argv, VALUE self)
{
  return rb_draw_contours_bang(argc, argv, copy(self));
}

#draw_contours!(contour, external_color, hole_color, max_level, options) ⇒ Object

Draws contour outlines or interiors in an image.

see CvMat#draw_contours



4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
# File 'ext/opencv/cvmat.cpp', line 4838

VALUE
rb_draw_contours_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE contour, external_color, hole_color, max_level, options;
  rb_scan_args(argc, argv, "41", &contour, &external_color, &hole_color, &max_level, &options);
  options = DRAWING_OPTION(options);
  try {
    cvDrawContours(CVARR(self), CVSEQ_WITH_CHECK(contour), VALUE_TO_CVSCALAR(external_color),
		   VALUE_TO_CVSCALAR(hole_color), NUM2INT(max_level),
		   DO_THICKNESS(options), DO_LINE_TYPE(options));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#each_col {|col| ... } ⇒ CvMat Also known as: each_column

TODO:

To return an enumerator if no block is given

Calls block once for each column in the matrix, passing that column as a parameter.

Yields:

  • (col)

    Each column in the matrix

Returns:



854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
# File 'ext/opencv/cvmat.cpp', line 854

VALUE
rb_each_col(VALUE self)
{
  int cols = CVMAT(self)->cols;
  CvMat *col = NULL;
  for (int i = 0; i < cols; ++i) {
    try {
      col = cvGetCol(CVARR(self), RB_CVALLOC(CvMat), i);
    }
    catch (cv::Exception& e) {
      if (col != NULL)
	cvReleaseMat(&col);
      raise_cverror(e);
    }
    rb_yield(DEPEND_OBJECT(rb_klass, col, self));
  }
  return self;
}

#each_row {|row| ... } ⇒ CvMat

TODO:

To return an enumerator if no block is given

Calls block once for each row in the matrix, passing that row as a parameter.

Yields:

  • (row)

    Each row in the matrix

Returns:



827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'ext/opencv/cvmat.cpp', line 827

VALUE
rb_each_row(VALUE self)
{
  int rows = CVMAT(self)->rows;
  CvMat* row = NULL;
  for (int i = 0; i < rows; ++i) {
    try {
      row = cvGetRow(CVARR(self), RB_CVALLOC(CvMat), i);
    }
    catch (cv::Exception& e) {
      if (row != NULL)
	cvReleaseMat(&row);
      raise_cverror(e);
    }
    rb_yield(DEPEND_OBJECT(rb_klass, row, self));
  }
  return self;
}

#eigenvvArray<CvMat>

Computes eigenvalues and eigenvectors of symmetric matrix. self should be symmetric square matrix. self is modified during the processing.

Returns:

  • (Array<CvMat>)

    Array of [eigenvalues, eigenvectors]



2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
# File 'ext/opencv/cvmat.cpp', line 2641

VALUE
rb_eigenvv(int argc, VALUE *argv, VALUE self)
{
  VALUE epsilon, lowindex, highindex;
  rb_scan_args(argc, argv, "03", &epsilon, &lowindex, &highindex);
  double eps = (NIL_P(epsilon)) ? 0.0 : NUM2DBL(epsilon);
  int lowidx = (NIL_P(lowindex)) ? -1 : NUM2INT(lowindex);
  int highidx = (NIL_P(highindex)) ? -1 : NUM2INT(highindex);
  VALUE eigen_vectors = Qnil, eigen_values = Qnil;
  CvArr* self_ptr = CVARR(self);
  try {
    CvSize size = cvGetSize(self_ptr);
    int type = cvGetElemType(self_ptr);
    eigen_vectors = new_object(size, type);
    eigen_values = new_object(size.height, 1, type);
    // NOTE: eps, lowidx, highidx are ignored in the current OpenCV implementation.
    cvEigenVV(self_ptr, CVARR(eigen_vectors), CVARR(eigen_values), eps, lowidx, highidx);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(2, eigen_vectors, eigen_values);
}

#ellipse(center, axes, angle, start_angle, end_angle, options = nil) ⇒ CvMat

Returns an image that is drawn a simple or thick elliptic arc or fills an ellipse sector.

Parameters:

  • center (CvPoint)

    Center of the ellipse.

  • axes (CvSize)

    Length of the ellipse axes.

  • angle (Number)

    Ellipse rotation angle in degrees.

  • start_angle (Number)

    Starting angle of the elliptic arc in degrees.

  • end_angle (Number)

    Ending angle of the elliptic arc in degrees.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



2932
2933
2934
2935
2936
# File 'ext/opencv/cvmat.cpp', line 2932

VALUE
rb_ellipse(int argc, VALUE *argv, VALUE self)
{
  return rb_ellipse_bang(argc, argv, rb_clone(self));
}

#ellipse!(center, axes, angle, start_angle, end_angle, options = nil) ⇒ CvMat

Draws a simple or thick elliptic arc or fills an ellipse sector.

Parameters:

  • center (CvPoint)

    Center of the ellipse.

  • axes (CvSize)

    Length of the ellipse axes.

  • angle (Number)

    Ellipse rotation angle in degrees.

  • start_angle (Number)

    Starting angle of the elliptic arc in degrees.

  • end_angle (Number)

    Ending angle of the elliptic arc in degrees.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
# File 'ext/opencv/cvmat.cpp', line 2958

VALUE
rb_ellipse_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE center, axis, angle, start_angle, end_angle, drawing_option;
  rb_scan_args(argc, argv, "51", &center, &axis, &angle, &start_angle, &end_angle, &drawing_option);
  drawing_option = DRAWING_OPTION(drawing_option);
  try {
    cvEllipse(CVARR(self), VALUE_TO_CVPOINT(center),
	      VALUE_TO_CVSIZE(axis),
	      NUM2DBL(angle), NUM2DBL(start_angle), NUM2DBL(end_angle),
	      DO_COLOR(drawing_option),
	      DO_THICKNESS(drawing_option),
	      DO_LINE_TYPE(drawing_option),
	      DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#ellipse_box(box, options = nil) ⇒ CvMat

Returns an image that is drawn a simple or thick elliptic arc or fills an ellipse sector.

Parameters:

  • box (CvBox2D)

    Alternative ellipse representation via CvBox2D. This means that the function draws an ellipse inscribed in the rotated rectangle.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



2996
2997
2998
2999
3000
# File 'ext/opencv/cvmat.cpp', line 2996

VALUE
rb_ellipse_box(int argc, VALUE *argv, VALUE self)
{
  return rb_ellipse_box_bang(argc, argv, rb_clone(self));
}

#ellipse_box!(box, options = nil) ⇒ CvMat

Draws a simple or thick elliptic arc or fills an ellipse sector.

Parameters:

  • box (CvBox2D)

    Alternative ellipse representation via CvBox2D. This means that the function draws an ellipse inscribed in the rotated rectangle.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
# File 'ext/opencv/cvmat.cpp', line 3019

VALUE
rb_ellipse_box_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE box, drawing_option;
  rb_scan_args(argc, argv, "11", &box, &drawing_option);
  drawing_option = DRAWING_OPTION(drawing_option);
  try {
    cvEllipseBox(CVARR(self), VALUE_TO_CVBOX2D(box),
		 DO_COLOR(drawing_option),
		 DO_THICKNESS(drawing_option),
		 DO_LINE_TYPE(drawing_option),
		 DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#encode_image(ext, params = nil) ⇒ Array<Integer> Also known as: encode

Encodes an image into a memory buffer.

Examples:

jpg = CvMat.load('image.jpg')
bytes1 = jpg.encode_image('.jpg') # Encodes a JPEG image which quality is 95
bytes2 = jpg.encode_image('.jpg', CV_IMWRITE_JPEG_QUALITY => 10) # Encodes a JPEG image which quality is 10

png = CvMat.load('image.png')
bytes3 = mat.encode_image('.png', CV_IMWRITE_PNG_COMPRESSION => 1)  # Encodes a PNG image which compression level is 1

Parameters:

  • ext (String)

    File extension that defines the output format (‘.jpg’, ‘.png’, …)

  • params (Hash) (defaults to: nil)
    • Format-specific parameters.

Options Hash (params):

  • CV_IMWRITE_JPEG_QUALITY (Integer) — default: 95

    For JPEG, it can be a quality ( CV_IMWRITE_JPEG_QUALITY ) from 0 to 100 (the higher is the better).

  • CV_IMWRITE_PNG_COMPRESSION (Integer) — default: 3

    For PNG, it can be the compression level ( CV_IMWRITE_PNG_COMPRESSION ) from 0 to 9. A higher value means a smaller size and longer compression time.

  • CV_IMWRITE_PXM_BINARY (Integer) — default: 1

    For PPM, PGM, or PBM, it can be a binary format flag ( CV_IMWRITE_PXM_BINARY ), 0 or 1.

Returns:

  • (Array<Integer>)

    Encoded image as array of bytes.



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'ext/opencv/cvmat.cpp', line 208

VALUE
rb_encode_imageM(int argc, VALUE *argv, VALUE self)
{
  VALUE _ext, _params;
  rb_scan_args(argc, argv, "11", &_ext, &_params);
  Check_Type(_ext, T_STRING);
  const char* ext = RSTRING_PTR(_ext);
  CvMat* buff = NULL;
  int* params = NULL;

  if (!NIL_P(_params)) {
    params = hash_to_format_specific_param(_params);
  }

  try {
    buff = cvEncodeImage(ext, CVARR(self), params);
  }
  catch (cv::Exception& e) {
    if (params != NULL) {
      free(params);
      params = NULL;
    }
    raise_cverror(e);
  }
  if (params != NULL) {
    free(params);
    params = NULL;
  }

  const int size = buff->rows * buff->cols;
  VALUE array = rb_ary_new2(size);
  for (int i = 0; i < size; i++) {
    rb_ary_store(array, i, CHR2FIX(CV_MAT_ELEM(*buff, char, 0, i)));
  }

  try {
    cvReleaseMat(&buff);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return array;
}

#eq(val) ⇒ CvMat

Performs the per-element comparison “equal” of two arrays or an array and scalar value.

Parameters:

  • val (CvMat, CvScalar, Number)

    Array, scalar or number to compare

Returns:

  • (CvMat)

    Result array



1949
1950
1951
1952
1953
# File 'ext/opencv/cvmat.cpp', line 1949

VALUE
rb_eq(VALUE self, VALUE val)
{
  return rb_cmp_internal(self, val, CV_CMP_EQ);
}

#equalize_histObject

Equalize histgram of grayscale of image.

equalizes histogram of the input image using the following algorithm:

  1. calculate histogram H for src.

  2. normalize histogram, so that the sum of histogram bins is 255.

  3. compute integral of the histogram: H’(i) = sum0≤j≤iH(j)

  4. transform the image using H’ as a look-up table: dst(x,y)=H’(src(x,y))

The algorithm normalizes brightness and increases contrast of the image.

support single-channel 8bit image (grayscale) only.



5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
# File 'ext/opencv/cvmat.cpp', line 5147

VALUE
rb_equalize_hist(VALUE self)
{
  VALUE dest = Qnil;
  try {
    CvArr* self_ptr = CVARR(self);
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvEqualizeHist(self_ptr, CVARR(dest));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#erode([element = nil, iteration = 1]) ⇒ Object

Create erodes image by using arbitrary structuring element. element is structuring element used for erosion. element should be IplConvKernel. If it is nil, a 3x3 rectangular structuring element is used. iterations is number of times erosion is applied.



4033
4034
4035
4036
4037
# File 'ext/opencv/cvmat.cpp', line 4033

VALUE
rb_erode(int argc, VALUE *argv, VALUE self)
{
  return rb_erode_bang(argc, argv, rb_clone(self));
}

#erode!([element = nil][,iteration = 1]) ⇒ self

Erodes image by using arbitrary structuring element. see also #erode.

Returns:

  • (self)


4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
# File 'ext/opencv/cvmat.cpp', line 4046

VALUE
rb_erode_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE element, iteration;
  rb_scan_args(argc, argv, "02", &element, &iteration);
  IplConvKernel* kernel = NIL_P(element) ? NULL : IPLCONVKERNEL_WITH_CHECK(element);
  try {
    cvErode(CVARR(self), CVARR(self), kernel, IF_INT(iteration, 1));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#extract_surf(params, mask = nil) ⇒ Array<CvSeq<CvSURFPoint>, Array<float>>

Extracts Speeded Up Robust Features from an image

Parameters:

  • params (CvSURFParams)

    Various algorithm parameters put to the structure CvSURFParams.

  • mask (CvMat) (defaults to: nil)

    The optional input 8-bit mask. The features are only found in the areas that contain more than 50% of non-zero mask pixels.

Returns:

  • (Array<CvSeq<CvSURFPoint>, Array<float>>)

    Output vector of keypoints and descriptors.



5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
# File 'ext/opencv/cvmat.cpp', line 5660

VALUE
rb_extract_surf(int argc, VALUE *argv, VALUE self)
{
  VALUE _params, _mask;
  rb_scan_args(argc, argv, "11", &_params, &_mask);

  // Prepare arguments
  CvSURFParams params = *CVSURFPARAMS_WITH_CHECK(_params);
  CvMat* mask = MASK(_mask);
  VALUE storage = cCvMemStorage::new_object();
  CvSeq* keypoints = NULL;
  CvSeq* descriptors = NULL;

  // Compute SURF keypoints and descriptors
  try {
    cvExtractSURF(CVARR(self), mask, &keypoints, &descriptors, CVMEMSTORAGE(storage),
		  params, 0);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  VALUE _keypoints = cCvSeq::new_sequence(cCvSeq::rb_class(), keypoints, cCvSURFPoint::rb_class(), storage);
  
  // Create descriptor array
  const int DIM_SIZE = (params.extended) ? 128 : 64;
  const int NUM_KEYPOINTS = keypoints->total;
  VALUE _descriptors = rb_ary_new2(NUM_KEYPOINTS);
  for (int m = 0; m < NUM_KEYPOINTS; ++m) {
    VALUE elem = rb_ary_new2(DIM_SIZE);
    float *descriptor = (float*)cvGetSeqElem(descriptors, m);
    for (int n = 0; n < DIM_SIZE; ++n) {
      rb_ary_store(elem, n, rb_float_new(descriptor[n]));
    }
    rb_ary_store(_descriptors, m, elem);
  }
  
  return rb_assoc_new(_keypoints, _descriptors);
}

#fill_convex_poly(points, options = nil) ⇒ CvMat

Returns an image that is filled a convex polygon.

Parameters:

  • points (Array<CvPoint>)

    Polygon vertices.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



3130
3131
3132
3133
3134
# File 'ext/opencv/cvmat.cpp', line 3130

VALUE
rb_fill_convex_poly(int argc, VALUE *argv, VALUE self)
{
  return rb_fill_convex_poly_bang(argc, argv, rb_clone(self));
}

#fill_convex_poly!(points, options = nil) ⇒ CvMat

Fills a convex polygon.

Parameters:

  • points (Array<CvPoint>)

    Polygon vertices.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
# File 'ext/opencv/cvmat.cpp', line 3152

VALUE
rb_fill_convex_poly_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE points, drawing_option;
  int i, num_points;
  CvPoint *p;

  rb_scan_args(argc, argv, "11", &points, &drawing_option);
  Check_Type(points, T_ARRAY);
  drawing_option = DRAWING_OPTION(drawing_option);
  num_points = RARRAY_LEN(points);
  p = ALLOCA_N(CvPoint, num_points);
  for (i = 0; i < num_points; ++i)
    p[i] = VALUE_TO_CVPOINT(rb_ary_entry(points, i));

  try {
    cvFillConvexPoly(CVARR(self), p, num_points,
		     DO_COLOR(drawing_option),
		     DO_LINE_TYPE(drawing_option),
		     DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#fill_poly(points, options = nil) ⇒ CvMat

Returns an image that is filled the area bounded by one or more polygons.

Parameters:

  • points (Array<CvPoint>)

    Array of polygons where each polygon is represented as an array of points.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



3054
3055
3056
3057
3058
# File 'ext/opencv/cvmat.cpp', line 3054

VALUE
rb_fill_poly(int argc, VALUE *argv, VALUE self)
{
  return rb_fill_poly_bang(argc, argv, self);
}

#fill_poly!(points, options = nil) ⇒ CvMat

Fills the area bounded by one or more polygons.

Parameters:

  • points (Array<CvPoint>)

    Array of polygons where each polygon is represented as an array of points.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
# File 'ext/opencv/cvmat.cpp', line 3076

VALUE
rb_fill_poly_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE polygons, drawing_option;
  VALUE points;
  int i, j;
  int num_polygons;
  int *num_points;
  CvPoint **p;

  rb_scan_args(argc, argv, "11", &polygons, &drawing_option);
  Check_Type(polygons, T_ARRAY);
  drawing_option = DRAWING_OPTION(drawing_option);
  num_polygons = RARRAY_LEN(polygons);
  num_points = ALLOCA_N(int, num_polygons);

  p = ALLOCA_N(CvPoint*, num_polygons);
  for (j = 0; j < num_polygons; ++j) {
    points = rb_ary_entry(polygons, j);
    Check_Type(points, T_ARRAY);
    num_points[j] = RARRAY_LEN(points);
    p[j] = ALLOCA_N(CvPoint, num_points[j]);
    for (i = 0; i < num_points[j]; ++i) {
      p[j][i] = VALUE_TO_CVPOINT(rb_ary_entry(points, i));
    }
  }
  try {
    cvFillPoly(CVARR(self), p, num_points, num_polygons,
	       DO_COLOR(drawing_option),
	       DO_LINE_TYPE(drawing_option),
	       DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#filter2d(kernel[,anchor]) ⇒ Object

Convolves image with the kernel. Convolution kernel, single-channel floating point matrix (or same depth of self’s). If you want to apply different kernels to different channels, split the image using CvMat#split into separate color planes and process them individually.



4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
# File 'ext/opencv/cvmat.cpp', line 4330

VALUE
rb_filter2d(int argc, VALUE *argv, VALUE self)
{
  VALUE _kernel, _anchor;
  rb_scan_args(argc, argv, "11", &_kernel, &_anchor);
  CvMat* kernel = CVMAT_WITH_CHECK(_kernel);
  CvArr* self_ptr = CVARR(self);
  VALUE _dest = Qnil;
  try {
    _dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvFilter2D(self_ptr, CVARR(_dest), kernel, NIL_P(_anchor) ? cvPoint(-1,-1) : VALUE_TO_CVPOINT(_anchor));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return _dest;
}

#find_chessboard_corners(pattern_size, flag = CV_CALIB_CB_ADAPTIVE_THRESH) ⇒ Array<Array<CvPoint2D32f>, Boolean>

Finds the positions of internal corners of the chessboard.

Examples:

mat = CvMat.load('chessboard.jpg', 1)
gray = mat.BGR2GRAY
pattern_size = CvSize.new(4, 4)
corners, found = gray.find_chessboard_corners(pattern_size, CV_CALIB_CB_ADAPTIVE_THRESH)

if found
  corners = gray.find_corner_sub_pix(corners, CvSize.new(3, 3), CvSize.new(-1, -1), CvTermCriteria.new(20, 0.03))
end

result = mat.draw_chessboard_corners(pattern_size, corners, found)
w = GUI::Window.new('Result')
w.show result
GUI::wait_key

Parameters:

  • pattern_size (CvSize)

    Number of inner corners per a chessboard row and column.

  • flags (Integer)

    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 CvMat#equalize_hist() 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.

Returns:

  • (Array<Array<CvPoint2D32f>, Boolean>)

    An array which includes the positions of internal corners of the chessboard, and a parameter indicating whether the complete board was found or not.



3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
# File 'ext/opencv/cvmat.cpp', line 3557

VALUE
rb_find_chessboard_corners(int argc, VALUE *argv, VALUE self)
{
  VALUE pattern_size_val, flag_val;
  rb_scan_args(argc, argv, "11", &pattern_size_val, &flag_val);

  int flag = NIL_P(flag_val) ? CV_CALIB_CB_ADAPTIVE_THRESH : NUM2INT(flag_val);
  CvSize pattern_size = VALUE_TO_CVSIZE(pattern_size_val);
  CvPoint2D32f* corners = ALLOCA_N(CvPoint2D32f, pattern_size.width * pattern_size.height);
  int num_found_corners = 0;
  int pattern_was_found = 0;
  try {
    pattern_was_found = cvFindChessboardCorners(CVARR(self), pattern_size, corners, &num_found_corners, flag);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  VALUE found_corners = rb_ary_new2(num_found_corners);
  for (int i = 0; i < num_found_corners; i++) {
    rb_ary_store(found_corners, i, cCvPoint2D32f::new_object(corners[i]));
  }

  VALUE found = (pattern_was_found > 0) ? Qtrue : Qfalse;
  return rb_assoc_new(found_corners, found);
}

#find_contours(find_contours_options) ⇒ CvContour, CvChain

Finds contours in binary image.

Parameters:

  • find_contours_options (Hash)

    Options

Options Hash (find_contours_options):

  • :mode (Symbol) — default: :list

    Retrieval mode.

    • :external - retrive only the extreme outer contours

    • :list - retrieve all the contours and puts them in the list.

    • :ccomp - retrieve all the contours and organizes them into two-level hierarchy: top level are external boundaries of the components, second level are bounda boundaries of the holes

    • :tree - retrieve all the contours and reconstructs the full hierarchy of nested contours Connectivity determines which neighbors of a pixel are considered.

  • :method (Symbol) — default: :approx_simple

    Approximation method.

    • :code - output contours in the Freeman chain code. All other methods output polygons (sequences of vertices).

    • :approx_none - translate all the points from the chain code into points;

    • :approx_simple - compress horizontal, vertical, and diagonal segments, that is, the function leaves only their ending points;

    • :approx_tc89_l1, :approx_tc89_kcos - apply one of the flavors of Teh-Chin chain approximation algorithm.

  • :offset (CvPoint) — default: CvPoint.new(0, 0)

    Offset, by which every contour point is shifted.

Returns:

  • (CvContour, CvChain)

    Detected contours. If :method is :code, returns as CvChain, otherwise CvContour.



4760
4761
4762
4763
4764
# File 'ext/opencv/cvmat.cpp', line 4760

VALUE
rb_find_contours(int argc, VALUE *argv, VALUE self)
{
  return rb_find_contours_bang(argc, argv, copy(self));
}

#find_contours!(find_contours_options) ⇒ CvContour, CvChain

Finds contours in binary image.

Returns:

  • (CvContour, CvChain)

    Detected contours. If :method is :code, returns as CvChain, otherwise CvContour.



4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
# File 'ext/opencv/cvmat.cpp', line 4774

VALUE
rb_find_contours_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE find_contours_option, klass, element_klass, storage;
  rb_scan_args(argc, argv, "01", &find_contours_option);
  CvSeq *contour = NULL;
  find_contours_option = FIND_CONTOURS_OPTION(find_contours_option);
  int mode = FC_MODE(find_contours_option);
  int method = FC_METHOD(find_contours_option);
  int header_size;
  if (method == CV_CHAIN_CODE) {
    klass = cCvChain::rb_class();
    element_klass = T_FIXNUM;
    header_size = sizeof(CvChain);
  }
  else {
    klass = cCvContour::rb_class();
    element_klass = cCvPoint::rb_class();
    header_size = sizeof(CvContour);
  }
  storage = cCvMemStorage::new_object();

  int count = 0;
  try {
    count = cvFindContours(CVARR(self), CVMEMSTORAGE(storage), &contour, header_size,
			   mode, method, FC_OFFSET(find_contours_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  if (count == 0)
    return Qnil;
  else
    return cCvSeq::new_sequence(klass, contour, element_klass, storage);
}

#find_corner_sub_pix(corners, win_size, zero_zone, criteria) ⇒ Array<CvPoint2D32f>

Refines the corner locations.

Parameters:

  • corners (Array<CvPoint>)

    Initial coordinates of the input corners.

  • win_size (CvSize)

    Half of the side length of the search window.

  • zero_zone (CvSize)

    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.

  • criteria (CvTermCriteria)

    Criteria for termination of the iterative process of corner refinement.

Returns:



3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
# File 'ext/opencv/cvmat.cpp', line 3596

VALUE
rb_find_corner_sub_pix(VALUE self, VALUE corners, VALUE win_size, VALUE zero_zone, VALUE criteria)
{
  Check_Type(corners, T_ARRAY);
  int count = RARRAY_LEN(corners);
  CvPoint2D32f* corners_buff = ALLOCA_N(CvPoint2D32f, count);
  VALUE* corners_ptr = RARRAY_PTR(corners);

  for (int i = 0; i < count; i++) {
    corners_buff[i] = *(CVPOINT2D32F(corners_ptr[i]));
  }

  try {
    cvFindCornerSubPix(CVARR(self), corners_buff, count, VALUE_TO_CVSIZE(win_size),
		       VALUE_TO_CVSIZE(zero_zone), VALUE_TO_CVTERMCRITERIA(criteria));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  VALUE refined_corners = rb_ary_new2(count);
  for (int i = 0; i < count; i++) {
    rb_ary_store(refined_corners, i, cCvPoint2D32f::new_object(corners_buff[i]));
  }

  return refined_corners;
}

#flip(flip_mode) ⇒ CvMat

Returns a fliped 2D array around vertical, horizontal, or both axes.

Parameters:

  • flip_mode (Symbol)

    Flag to specify how to flip the array.

    • :x - Flipping around the x-axis.

    • :y - Flipping around the y-axis.

    • :xy - Flipping around both axes.

Returns:

  • (CvMat)

    Flipped array



1358
1359
1360
1361
1362
# File 'ext/opencv/cvmat.cpp', line 1358

VALUE
rb_flip(int argc, VALUE *argv, VALUE self)
{
  return rb_flip_bang(argc, argv, copy(self));
}

#flip!(flip_mode) ⇒ CvMat

Flips a 2D array around vertical, horizontal, or both axes.

Parameters:

  • flip_mode (Symbol)

    Flag to specify how to flip the array.

    • :x - Flipping around the x-axis.

    • :y - Flipping around the y-axis.

    • :xy - Flipping around both axes.

Returns:

  • (CvMat)

    Flipped array



1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
# File 'ext/opencv/cvmat.cpp', line 1372

VALUE
rb_flip_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE format;
  int mode = 1;
  if (rb_scan_args(argc, argv, "01", &format) > 0) {
    Check_Type(format, T_SYMBOL);
    ID flip_mode = rb_to_id(format);
    if (flip_mode == rb_intern("x")) {
      mode = 1;
    }
    else if (flip_mode == rb_intern("y")) {
      mode = 0;
    }
    else if (flip_mode == rb_intern("xy")) {
      mode = -1;
    }
  }
  try {
    cvFlip(CVARR(self), NULL, mode);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#flood_fill(seed_point, new_val, lo_diff = CvScalar.new(0), up_diff = CvScalar.new(0), flood_fill_option = nil) ⇒ Array<CvMat, CvConnectedComp>

Fills a connected component with the given color.

Parameters:

  • seed_point (CvPoint)

    Starting point.

  • new_val (CvScalar)

    New value of the repainted domain pixels.

  • lo_diff (CvScalar) (defaults to: CvScalar.new(0))

    Maximal lower brightness/color difference between the currently observed pixel and one of its neighbor belong to the component or seed pixel to add the pixel to component. In case of 8-bit color images it is packed value.

  • up_diff (CvScalar) (defaults to: CvScalar.new(0))

    Maximal upper brightness/color difference between the currently observed pixel and one of its neighbor belong to the component or seed pixel to add the pixel to component. In case of 8-bit color images it is packed value.

  • flood_fill_option (Hash) (defaults to: nil)

Options Hash (flood_fill_option):

  • :connectivity (Integer) — default: 4

    Connectivity determines which neighbors of a pixel are considered (4 or 8).

  • :fixed_range (Boolean) — default: false

    If set the difference between the current pixel and seed pixel is considered, otherwise difference between neighbor pixels is considered (the range is floating).

  • :mask_only (Boolean) — default: false

    If set, the function does not fill the image(new_val is ignored), but the fills mask.

Returns:



4687
4688
4689
4690
4691
# File 'ext/opencv/cvmat.cpp', line 4687

VALUE
rb_flood_fill(int argc, VALUE *argv, VALUE self)
{
  return rb_flood_fill_bang(argc, argv, copy(self));
}

#flood_fill!(seed_point, new_val, lo_diff = CvScalar.new(0), up_diff = CvScalar.new(0), flood_fill_option = nil) ⇒ Object

Fills a connected component with the given color.



4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
# File 'ext/opencv/cvmat.cpp', line 4701

VALUE
rb_flood_fill_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE seed_point, new_val, lo_diff, up_diff, flood_fill_option;
  rb_scan_args(argc, argv, "23", &seed_point, &new_val, &lo_diff, &up_diff, &flood_fill_option);
  flood_fill_option = FLOOD_FILL_OPTION(flood_fill_option);
  int flags = FF_CONNECTIVITY(flood_fill_option);
  if (FF_FIXED_RANGE(flood_fill_option)) {
    flags |= CV_FLOODFILL_FIXED_RANGE;
  }
  if (FF_MASK_ONLY(flood_fill_option)) {
    flags |= CV_FLOODFILL_MASK_ONLY;
  }
  CvArr* self_ptr = CVARR(self);
  VALUE comp = cCvConnectedComp::new_object();
  VALUE mask = Qnil;
  try {
    CvSize size = cvGetSize(self_ptr);
    // TODO: Change argument format to set mask
    mask = new_object(size.height + 2, size.width + 2, CV_MAKETYPE(CV_8U, 1));
    CvMat* mask_ptr = CVMAT(mask);
    cvSetZero(mask_ptr);
    cvFloodFill(self_ptr,
		VALUE_TO_CVPOINT(seed_point),
		VALUE_TO_CVSCALAR(new_val),
		NIL_P(lo_diff) ? cvScalar(0) : VALUE_TO_CVSCALAR(lo_diff),
		NIL_P(up_diff) ? cvScalar(0) : VALUE_TO_CVSCALAR(up_diff),
		CVCONNECTEDCOMP(comp),
		flags,
		mask_ptr);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(3, self, comp, mask);
}

#ge(val) ⇒ CvMat

Performs the per-element comparison “greater than or equal” of two arrays or an array and scalar value.

Parameters:

  • val (CvMat, CvScalar, Number)

    Array, scalar or number to compare

Returns:

  • (CvMat)

    Result array



1979
1980
1981
1982
1983
# File 'ext/opencv/cvmat.cpp', line 1979

VALUE
rb_ge(VALUE self, VALUE val)
{
  return rb_cmp_internal(self, val, CV_CMP_GE);
}

#get_cols(index) ⇒ CvMat #get_cols(range) ⇒ CvMat

Returns array of column or column span.

Overloads:

  • #get_cols(index) ⇒ CvMat

    Returns Selected column.

    Parameters:

    • index (Integer)

      Zero-based index of the selected column

    Returns:

    • (CvMat)

      Selected column

  • #get_cols(range) ⇒ CvMat

    Returns Selected columns.

    Parameters:

    • range (Range)

      Zero-based index range of the selected column

    Returns:

    • (CvMat)

      Selected columns



802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
# File 'ext/opencv/cvmat.cpp', line 802

VALUE
rb_get_cols(VALUE self, VALUE col)
{
  int start, end;
  rb_get_range_index(col, &start, &end);
  CvMat* submat = RB_CVALLOC(CvMat);
  try {
    cvGetCols(CVARR(self), submat, start, end);
  }
  catch (cv::Exception& e) {
    cvFree(&submat);
    raise_cverror(e);
  }

  return DEPEND_OBJECT(rb_klass, submat, self);
}

#get_rows(index, delta_row = 1) ⇒ CvMat #get_rows(range, delta_row = 1) ⇒ CvMat

Returns array of row or row span.

Overloads:

  • #get_rows(index, delta_row = 1) ⇒ CvMat

    Returns Selected row.

    Parameters:

    • index (Integer)

      Zero-based index of the selected row

    • delta_row (Integer) (defaults to: 1)

      Index step in the row span.

    Returns:

    • (CvMat)

      Selected row

  • #get_rows(range, delta_row = 1) ⇒ CvMat

    Returns Selected rows.

    Parameters:

    • range (Range)

      Zero-based index range of the selected row

    • delta_row (Integer) (defaults to: 1)

      Index step in the row span.

    Returns:

    • (CvMat)

      Selected rows



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'ext/opencv/cvmat.cpp', line 771

VALUE
rb_get_rows(int argc, VALUE* argv, VALUE self)
{
  VALUE row_val, delta_val;
  rb_scan_args(argc, argv, "11", &row_val, &delta_val);

  int start, end;
  rb_get_range_index(row_val, &start, &end);
  int delta = NIL_P(delta_val) ? 1 : NUM2INT(delta_val);
  CvMat* submat = RB_CVALLOC(CvMat);
  try {
    cvGetRows(CVARR(self), submat, start, end, delta);
  }
  catch (cv::Exception& e) {
    cvFree(&submat);
    raise_cverror(e);
  }

  return DEPEND_OBJECT(rb_klass, submat, self);
}

#good_features_to_track(quality_level, min_distance, good_features_to_track_option = {}) ⇒ Array<CvPoint2D32f>

Determines strong corners on an image.

Parameters:

  • quality_level (Number)

    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 or the Harris function response.

  • min_distance (Number)

    Minimum possible Euclidean distance between the returned corners.

  • good_features_to_track_option (Hash) (defaults to: {})

    Options.

Options Hash (good_features_to_track_option):

  • :mask (CvMat) — default: nil

    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.

  • :block_size (Integer) — default: 3

    Size of an average block for computing a derivative covariation matrix over each pixel neighborhood.

  • :use_harris (Boolean) — default: false

    Parameter indicating whether to use a Harris detector.

  • :k (Number) — default: 0.04

    Free parameter of the Harris detector.

Returns:

  • (Array<CvPoint2D32f>)

    Output vector of detected corners.



3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
# File 'ext/opencv/cvmat.cpp', line 3644

VALUE
rb_good_features_to_track(int argc, VALUE *argv, VALUE self)
{
  VALUE quality_level, min_distance, good_features_to_track_option;
  rb_scan_args(argc, argv, "21", &quality_level, &min_distance, &good_features_to_track_option);
  good_features_to_track_option = GOOD_FEATURES_TO_TRACK_OPTION(good_features_to_track_option);
  int np = GF_MAX(good_features_to_track_option);
  if (np <= 0)
    rb_raise(rb_eArgError, "option :max should be positive value.");

  CvMat *self_ptr = CVMAT(self);
  CvPoint2D32f *p32 = (CvPoint2D32f*)rb_cvAlloc(sizeof(CvPoint2D32f) * np);
  int type = CV_MAKETYPE(CV_32F, 1);
  CvMat* eigen = rb_cvCreateMat(self_ptr->rows, self_ptr->cols, type);
  CvMat* tmp = rb_cvCreateMat(self_ptr->rows, self_ptr->cols, type);
  try {
    cvGoodFeaturesToTrack(self_ptr, &eigen, &tmp, p32, &np, NUM2DBL(quality_level), NUM2DBL(min_distance),
			  GF_MASK(good_features_to_track_option),
			  GF_BLOCK_SIZE(good_features_to_track_option),
			  GF_USE_HARRIS(good_features_to_track_option),
			  GF_K(good_features_to_track_option));
  }
  catch (cv::Exception& e) {
    if (eigen != NULL)
      cvReleaseMat(&eigen);
    if (tmp != NULL)
      cvReleaseMat(&tmp);
    if (p32 != NULL)
      cvFree(&p32);
    raise_cverror(e);
  }
  VALUE corners = rb_ary_new2(np);
  for (int i = 0; i < np; ++i)
    rb_ary_store(corners, i, cCvPoint2D32f::new_object(p32[i]));
  cvFree(&p32);
  cvReleaseMat(&eigen);
  cvReleaseMat(&tmp);
  return corners;
}

#gt(val) ⇒ CvMat

Performs the per-element comparison “greater than” of two arrays or an array and scalar value.

Parameters:

  • val (CvMat, CvScalar, Number)

    Array, scalar or number to compare

Returns:

  • (CvMat)

    Result array



1964
1965
1966
1967
1968
# File 'ext/opencv/cvmat.cpp', line 1964

VALUE
rb_gt(VALUE self, VALUE val)
{
  return rb_cmp_internal(self, val, CV_CMP_GT);
}

#rowsInteger Also known as: rows

Returns number of rows of the matrix.

Returns:

  • (Integer)

    Number of rows of the matrix



433
434
435
436
437
# File 'ext/opencv/cvmat.cpp', line 433

VALUE
rb_height(VALUE self)
{
  return INT2NUM(CVMAT(self)->height);
}

#hough_circles(method, dp, min_dist, param1, param2, min_radius = 0, max_radius = 0) ⇒ CvSeq<CvCircle32f>

Finds circles in a grayscale image using the Hough transform.

Parameters:

  • method (Integer)

    Detection method to use. Currently, the only implemented method is CV_HOUGH_GRADIENT.

  • dp (Number)

    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.

  • min_dist (Number)

    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.

  • param1 (Number)

    First method-specific parameter. In case of CV_HOUGH_GRADIENT, it is the higher threshold of the two passed to the #canny detector (the lower one is twice smaller).

  • param2 (Number)

    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.

Returns:



5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
# File 'ext/opencv/cvmat.cpp', line 5081

VALUE
rb_hough_circles(int argc, VALUE *argv, VALUE self)
{
  const int INVALID_TYPE = -1;
  VALUE method, dp, min_dist, param1, param2, min_radius, max_radius, storage;
  rb_scan_args(argc, argv, "52", &method, &dp, &min_dist, &param1, &param2, 
	       &min_radius, &max_radius);
  storage = cCvMemStorage::new_object();
  int method_flag = CVMETHOD("HOUGH_TRANSFORM_METHOD", method, INVALID_TYPE);
  if (method_flag == INVALID_TYPE)
    rb_raise(rb_eArgError, "Invalid method: %d", method_flag);
  CvSeq *seq = NULL;
  try {
    seq = cvHoughCircles(CVARR(self), CVMEMSTORAGE(storage),
			 method_flag, NUM2DBL(dp), NUM2DBL(min_dist),
			 NUM2DBL(param1), NUM2DBL(param2),
			 IF_INT(min_radius, 0), IF_INT(max_radius, 0));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return cCvSeq::new_sequence(cCvSeq::rb_class(), seq, cCvCircle32f::rb_class(), storage);
}

#hough_lines(method, rho, theta, threshold, param1, param2) ⇒ CvSeq<CvLine, CvTwoPoints>

Finds lines in binary image using a Hough transform.

Parameters:

  • method (Integer)

    The Hough transform variant, one of the following:

    • CV_HOUGH_STANDARD - classical or standard Hough transform.

    • CV_HOUGH_PROBABILISTIC - probabilistic Hough transform (more efficient in case if picture contains a few long linear segments).

    • CV_HOUGH_MULTI_SCALE - multi-scale variant of the classical Hough transform. The lines are encoded the same way as CV_HOUGH_STANDARD.

  • rho (Number)

    Distance resolution in pixel-related units.

  • theta (Number)

    Angle resolution measured in radians.

  • threshold (Number)

    Threshold parameter. A line is returned by the function if the corresponding accumulator value is greater than threshold.

  • param1 (Number)

    The first method-dependent parameter:

    • For the classical Hough transform it is not used (0).

    • For the probabilistic Hough transform it is the minimum line length.

    • For the multi-scale Hough transform it is the divisor for the distance resolution. (The coarse distance resolution will be rho and the accurate resolution will be (rho / param1)).

  • param2 (Number)

    The second method-dependent parameter:

    • For the classical Hough transform it is not used (0).

    • For the probabilistic Hough transform it is the maximum gap between line segments lying on the same line to treat them as a single line segment (i.e. to join them).

    • For the multi-scale Hough transform it is the divisor for the angle resolution. (The coarse angle resolution will be theta and the accurate resolution will be (theta / param2).)

Returns:

  • (CvSeq<CvLine, CvTwoPoints>)

    Output lines. If method is CV_HOUGH_STANDARD or CV_HOUGH_MULTI_SCALE, the class of elements is CvLine, otherwise CvTwoPoints.



5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
# File 'ext/opencv/cvmat.cpp', line 5027

VALUE
rb_hough_lines(int argc, VALUE *argv, VALUE self)
{
  const int INVALID_TYPE = -1;
  VALUE method, rho, theta, threshold, p1, p2;
  rb_scan_args(argc, argv, "42", &method, &rho, &theta, &threshold, &p1, &p2);
  int method_flag = CVMETHOD("HOUGH_TRANSFORM_METHOD", method, INVALID_TYPE);
  if (method_flag == INVALID_TYPE)
    rb_raise(rb_eArgError, "Invalid method: %d", method_flag);
  VALUE storage = cCvMemStorage::new_object();
  CvSeq *seq = NULL;
  try {
    seq = cvHoughLines2(CVARR(copy(self)), CVMEMSTORAGE(storage),
			method_flag, NUM2DBL(rho), NUM2DBL(theta), NUM2INT(threshold),
			IF_DBL(p1, 0), IF_DBL(p2, 0));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  switch (method_flag) {
  case CV_HOUGH_STANDARD:
  case CV_HOUGH_MULTI_SCALE:
    return cCvSeq::new_sequence(cCvSeq::rb_class(), seq, cCvLine::rb_class(), storage);
    break;
  case CV_HOUGH_PROBABILISTIC:
    return cCvSeq::new_sequence(cCvSeq::rb_class(), seq, cCvTwoPoints::rb_class(), storage);
    break;
  default:
    break;
  }

  return Qnil;
}

#identity(value) ⇒ CvMat

Returns a scaled identity matrix.

arr(i, j) = value if i = j, 0 otherwise

Parameters:

  • value (CvScalar)

    Value to assign to diagonal elements.

Returns:

  • (CvMat)

    Scaled identity matrix.



1230
1231
1232
1233
1234
# File 'ext/opencv/cvmat.cpp', line 1230

VALUE
rb_set_identity(int argc, VALUE *argv, VALUE self)
{
  return rb_set_identity_bang(argc, argv, copy(self));
}

#identity!(value) ⇒ CvMat

Initializes a scaled identity matrix.

arr(i, j) = value if i = j, 0 otherwise

Parameters:

  • value (CvScalar)

    Value to assign to diagonal elements.

Returns:



1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
# File 'ext/opencv/cvmat.cpp', line 1244

VALUE
rb_set_identity_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE val;
  CvScalar value;
  if (rb_scan_args(argc, argv, "01",  &val) < 1)
    value = cvRealScalar(1);
  else
    value = VALUE_TO_CVSCALAR(val);

  try {
    cvSetIdentity(CVARR(self), value);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#in_range(min, max) ⇒ CvMat

Checks if array elements lie between the elements of two other arrays.

Parameters:

  • min (CvMat, CvScalar)

    Inclusive lower boundary array or a scalar.

  • max (CvMat, CvScalar)

    Inclusive upper boundary array or a scalar.

Returns:

  • (CvMat)

    Result array



2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
# File 'ext/opencv/cvmat.cpp', line 2040

VALUE
rb_in_range(VALUE self, VALUE min, VALUE max)
{
  CvArr* self_ptr = CVARR(self);
  CvSize size = cvGetSize(self_ptr);
  VALUE dest = new_object(size, CV_8UC1);
  try {
    if (rb_obj_is_kind_of(min, rb_klass) && rb_obj_is_kind_of(max, rb_klass))
      cvInRange(self_ptr, CVARR(min), CVARR(max), CVARR(dest));
    else if (rb_obj_is_kind_of(min, rb_klass)) {
      VALUE tmp = new_object(size, cvGetElemType(self_ptr));
      cvSet(CVARR(tmp), VALUE_TO_CVSCALAR(max));
      cvInRange(self_ptr, CVARR(min), CVARR(tmp), CVARR(dest));
    }
    else if (rb_obj_is_kind_of(max, rb_klass)) {
      VALUE tmp = new_object(size, cvGetElemType(self_ptr));
      cvSet(CVARR(tmp), VALUE_TO_CVSCALAR(min));
      cvInRange(self_ptr, CVARR(tmp), CVARR(max), CVARR(dest));
    }
    else
      cvInRangeS(self_ptr, VALUE_TO_CVSCALAR(min), VALUE_TO_CVSCALAR(max), CVARR(dest));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#inpaint(inpaint_method, mask, radius) ⇒ Object

Inpaints the selected region in the image The radius of circlular neighborhood of each point inpainted that is considered by the algorithm.



5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
# File 'ext/opencv/cvmat.cpp', line 5112

VALUE
rb_inpaint(VALUE self, VALUE inpaint_method, VALUE mask, VALUE radius)
{
  const int INVALID_TYPE = -1;
  VALUE dest = Qnil;
  int method = CVMETHOD("INPAINT_METHOD", inpaint_method, INVALID_TYPE);
  if (method == INVALID_TYPE)
    rb_raise(rb_eArgError, "Invalid method");
  try {
    CvArr* self_ptr = CVARR(self);
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvInpaint(self_ptr, MASK(mask), CVARR(dest), NUM2DBL(radius), method);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#inside?(point) ⇒ Boolean #inside?(rect) ⇒ Boolean

Tests whether a coordinate or rectangle is inside of the matrix

Overloads:

  • #inside?(point) ⇒ Boolean

    Parameters:

    • obj (#x, #y)

      Tested coordinate

  • #inside?(rect) ⇒ Boolean

    Parameters:

Returns:

  • (Boolean)

    If the point or rectangle is inside of the matrix, return true. If not, return false.



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'ext/opencv/cvmat.cpp', line 360

VALUE
rb_inside_q(VALUE self, VALUE object)
{
  if (cCvPoint::rb_compatible_q(cCvPoint::rb_class(), object)) {
    CvMat *mat = CVMAT(self);
    int x = NUM2INT(rb_funcall(object, rb_intern("x"), 0));
    int y = NUM2INT(rb_funcall(object, rb_intern("y"), 0));
    if (cCvRect::rb_compatible_q(cCvRect::rb_class(), object)) {
      int width = NUM2INT(rb_funcall(object, rb_intern("width"), 0));
      int height = NUM2INT(rb_funcall(object, rb_intern("height"), 0));
      return (x >= 0) && (y >= 0) && (x < mat->width) && ((x + width) < mat->width)
	&& (y < mat->height) && ((y + height) < mat->height) ? Qtrue : Qfalse;
    }
    else {
      return (x >= 0) && (y >= 0) && (x < mat->width) && (y < mat->height) ? Qtrue : Qfalse;
    }
  }
  rb_raise(rb_eArgError, "argument 1 should have method \"x\", \"y\"");
  return Qnil;
}

#integral(need_sqsum = false, need_tilted_sum = false) ⇒ Array?

Calculates integral images. If need_sqsum = true, calculate the integral image for squared pixel values. If need_tilted_sum = true, calculate the integral for the image rotated by 45 degrees.

sum(X,Y)=sumx<X,y<Yimage(x,y)
sqsum(X,Y)=sumx<X,y<Yimage(x,y)2
tilted_sum(X,Y)=sumy<Y,abs(x-X)<yimage(x,y)

Using these integral images, one may calculate sum, mean, standard deviation over arbitrary up-right or rotated rectangular region of the image in a constant time.

Returns:

  • (Array, nil)


4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
# File 'ext/opencv/cvmat.cpp', line 4406

VALUE
rb_integral(int argc, VALUE *argv, VALUE self)
{
  VALUE need_sqsum = Qfalse, need_tiled_sum = Qfalse;
  rb_scan_args(argc, argv, "02", &need_sqsum, &need_tiled_sum);

  VALUE sum = Qnil;
  VALUE sqsum = Qnil;
  VALUE tiled_sum = Qnil;
  CvArr* self_ptr = CVARR(self);
  try {
    CvSize self_size = cvGetSize(self_ptr);
    CvSize size = cvSize(self_size.width + 1, self_size.height + 1);
    int type_cv64fcn = CV_MAKETYPE(CV_64F, CV_MAT_CN(cvGetElemType(self_ptr)));
    sum = cCvMat::new_object(size, type_cv64fcn);
    sqsum = (need_sqsum == Qtrue ? cCvMat::new_object(size, type_cv64fcn) : Qnil);
    tiled_sum = (need_tiled_sum == Qtrue ? cCvMat::new_object(size, type_cv64fcn) : Qnil);
    cvIntegral(self_ptr, CVARR(sum), (need_sqsum == Qtrue) ? CVARR(sqsum) : NULL,
	       (need_tiled_sum == Qtrue) ? CVARR(tiled_sum) : NULL);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  
  if ((need_sqsum != Qtrue) && (need_tiled_sum != Qtrue))
    return sum;
  else {
    VALUE dest = rb_ary_new3(1, sum);
    if (need_sqsum == Qtrue)
      rb_ary_push(dest, sqsum);
    if (need_tiled_sum == Qtrue)
      rb_ary_push(dest, tiled_sum);
    return dest;
  }
}

#invert(inversion_method = :lu) ⇒ Number

Finds inverse or pseudo-inverse of matrix.

Parameters:

  • inversion_method (Symbol)

    Inversion method.

    • :lu - Gaussian elimincation with optimal pivot element chose.

    • :svd - Singular value decomposition(SVD) method.

    • :svd_sym - SVD method for a symmetric positively-defined matrix.

Returns:

  • (Number)

    Inverse or pseudo-inverse of matrix.



2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
# File 'ext/opencv/cvmat.cpp', line 2532

VALUE
rb_invert(int argc, VALUE *argv, VALUE self)
{
  VALUE symbol;
  rb_scan_args(argc, argv, "01", &symbol);
  int method = CVMETHOD("INVERSION_METHOD", symbol, CV_LU);
  VALUE dest = Qnil;
  CvArr* self_ptr = CVARR(self);
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvInvert(self_ptr, CVARR(dest), method);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#laplace(aperture_size = 3) ⇒ Object

Calculates the Laplacian of an image.

Parameters:

  • aperture_size (Integer)

    Aperture size used to compute the second-derivative filters. The size must be positive and odd.

Returns:

  • Output image.



3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
# File 'ext/opencv/cvmat.cpp', line 3359

VALUE
rb_laplace(int argc, VALUE *argv, VALUE self)
{
  VALUE aperture_size, dest;
  if (rb_scan_args(argc, argv, "01", &aperture_size) < 1)
    aperture_size = INT2FIX(3);
  CvMat* self_ptr = CVMAT(self);
  switch(CV_MAT_DEPTH(self_ptr->type)) {
  case CV_8U:
    dest = new_mat_kind_object(cvGetSize(self_ptr), self, CV_16S, 1);
    break;
  case CV_32F:
    dest = new_mat_kind_object(cvGetSize(self_ptr), self, CV_32F, 1);
    break;
  default:
    rb_raise(rb_eArgError, "source depth should be CV_8U or CV_32F.");
  }

  try {
    cvLaplace(self_ptr, CVARR(dest), NUM2INT(aperture_size));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#le(val) ⇒ CvMat

Performs the per-element comparison “less than or equal” of two arrays or an array and scalar value.

Parameters:

  • val (CvMat, CvScalar, Number)

    Array, scalar or number to compare

Returns:

  • (CvMat)

    Result array



2009
2010
2011
2012
2013
# File 'ext/opencv/cvmat.cpp', line 2009

VALUE
rb_le(VALUE self, VALUE val)
{
  return rb_cmp_internal(self, val, CV_CMP_LE);
}

#line(p1, p2, options = nil) ⇒ CvMat

Returns an image that is drawn a line segment connecting two points.

Parameters:

  • p1 (CvPoint)

    First point of the line segment.

  • p2 (CvPoint)

    Second point of the line segment.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



2752
2753
2754
2755
2756
# File 'ext/opencv/cvmat.cpp', line 2752

VALUE
rb_line(int argc, VALUE *argv, VALUE self)
{
  return rb_line_bang(argc, argv, rb_clone(self));
}

#line!(p1, p2, options = nil) ⇒ CvMat

Draws a line segment connecting two points.

Parameters:

  • p1 (CvPoint)

    First point of the line segment.

  • p2 (CvPoint)

    Second point of the line segment.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
# File 'ext/opencv/cvmat.cpp', line 2775

VALUE
rb_line_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE p1, p2, drawing_option;
  rb_scan_args(argc, argv, "21", &p1, &p2, &drawing_option);
  drawing_option = DRAWING_OPTION(drawing_option);
  try {
    cvLine(CVARR(self), VALUE_TO_CVPOINT(p1), VALUE_TO_CVPOINT(p2),
	   DO_COLOR(drawing_option),
	   DO_THICKNESS(drawing_option),
	   DO_LINE_TYPE(drawing_option),
	   DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#log_polar(size, center, magnitude, flags = CV_INTER_LINEAR|CV_WARP_FILL_OUTLIERS) ⇒ CvMat

Remaps an image to log-polar space.

Parameters:

  • size (CvSize)

    Size of the destination image.

  • center (CvPoint2D32f)

    The transformation center; where the output precision is maximal.

  • magnitude (Number)

    Magnitude scale parameter.

  • flags (Integer) (defaults to: CV_INTER_LINEAR|CV_WARP_FILL_OUTLIERS)

    A combination of interpolation methods and the following optional flags:

    • CV_WARP_FILL_OUTLIERS - fills all of the destination image pixels. If some of them correspond to outliers in the source image, they are set to zero.

    • CV_WARP_INVERSE_MAP - performs inverse transformation.

Returns:

  • (CvMat)

    Destination image.



4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
# File 'ext/opencv/cvmat.cpp', line 4008

VALUE
rb_log_polar(int argc, VALUE *argv, VALUE self)
{
  VALUE dst_size, center, m, flags;
  rb_scan_args(argc, argv, "31", &dst_size, &center, &m, &flags);
  int _flags = NIL_P(flags) ? (CV_INTER_LINEAR | CV_WARP_FILL_OUTLIERS) : NUM2INT(flags);
  VALUE dest = new_mat_kind_object(VALUE_TO_CVSIZE(dst_size), self);
  try {
    cvLogPolar(CVARR(self), CVARR(dest), VALUE_TO_CVPOINT2D32F(center), NUM2DBL(m), _flags);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#lt(val) ⇒ CvMat

Performs the per-element comparison “less than” of two arrays or an array and scalar value.

Parameters:

  • val (CvMat, CvScalar, Number)

    Array, scalar or number to compare

Returns:

  • (CvMat)

    Result array



1994
1995
1996
1997
1998
# File 'ext/opencv/cvmat.cpp', line 1994

VALUE
rb_lt(VALUE self, VALUE val)
{
  return rb_cmp_internal(self, val, CV_CMP_LT);
}

#lut(lut) ⇒ CvMat

Performs a look-up table transform of an array.

Parameters:

  • lut (CvMat)

    Look-up table of 256 elements. In case of multi-channel source 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 source array.

Returns:

  • (CvMat)

    Transformed array



1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
# File 'ext/opencv/cvmat.cpp', line 1540

VALUE
rb_lut(VALUE self, VALUE lut)
{
  VALUE dest = copy(self);
  try {
    cvLUT(CVARR(self), CVARR(dest), CVARR_WITH_CHECK(lut));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#mat_mul(val, shiftvec = nil) ⇒ CvMat Also known as: *

Calculates the product of two arrays.

dst = self * val + shiftvec

Parameters:

  • val (CvMat)

    Array to multiply

  • shiftvec (CvMat)

    Optional translation vector

Returns:

  • (CvMat)

    Result array



1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
# File 'ext/opencv/cvmat.cpp', line 1715

VALUE
rb_mat_mul(int argc, VALUE *argv, VALUE self)
{
  VALUE val, shiftvec, dest;
  rb_scan_args(argc, argv, "11", &val, &shiftvec);
  CvArr* self_ptr = CVARR(self);  
  dest = new_mat_kind_object(cvGetSize(self_ptr), self);
  try {
    if (NIL_P(shiftvec))
      cvMatMul(self_ptr, CVARR_WITH_CHECK(val), CVARR(dest));
    else
      cvMatMulAdd(self_ptr, CVARR_WITH_CHECK(val), CVARR_WITH_CHECK(shiftvec), CVARR(dest));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#match_shapes(object, method) ⇒ Float

Compares two shapes(self and object). object should be CvMat or CvContour.

A - object1, B - object2:

  • method=CV_CONTOURS_MATCH_I1

    I1(A,B)=sumi=1..7abs(1/mAi - 1/mBi)
    
  • method=CV_CONTOURS_MATCH_I2

    I2(A,B)=sumi=1..7abs(mAi - mBi)
    
  • method=CV_CONTOURS_MATCH_I3

    I3(A,B)=sumi=1..7abs(mAi - mBi)/abs(mAi)
    

Returns:

  • (Float)


5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
# File 'ext/opencv/cvmat.cpp', line 5251

VALUE
rb_match_shapes(int argc, VALUE *argv, VALUE self)
{
  VALUE object, method, param;
  rb_scan_args(argc, argv, "21", &object, &method, &param);
  int method_flag = CVMETHOD("COMPARISON_METHOD", method);
  if (!(rb_obj_is_kind_of(object, cCvMat::rb_class()) || rb_obj_is_kind_of(object, cCvContour::rb_class())))
    rb_raise(rb_eTypeError, "argument 1 (shape) should be %s or %s",
	     rb_class2name(cCvMat::rb_class()), rb_class2name(cCvContour::rb_class()));
  double result = 0;
  try {
    result = cvMatchShapes(CVARR(self), CVARR(object), method_flag);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_float_new(result);
}

#match_template(template, method = CV_TM_SQDIFF) ⇒ Object

Compares template against overlapped image regions.

After the match_template finishes comparison, the best matches can be found as global minimums (CV_TM_SQDIFF) or maximums(CV_TM_CCORR or CV_TM_CCOEFF) using CvMat#min_max_loc. In case of color image and template summation in both numerator and each sum in denominator is done over all the channels (and separate mean values are used for each channel).

Parameters:

  • template (CvMat)

    Searched template. It must be not greater than the source image and have the same data type.

  • method (Integer) (defaults to: CV_TM_SQDIFF)

    Parameter specifying the comparison method.

    • CV_TM_SQDIFF

    • CV_TM_SQDIFF_NORMED

    • CV_TM_CCORR

    • CV_TM_CCORR_NORMED

    • CV_TM_CCOEFF

    • CV_TM_CCOEFF_NORMED



5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
# File 'ext/opencv/cvmat.cpp', line 5210

VALUE
rb_match_template(int argc, VALUE *argv, VALUE self)
{
  VALUE templ, method;
  int method_flag;
  if (rb_scan_args(argc, argv, "11", &templ, &method) == 1)
    method_flag = CV_TM_SQDIFF;
  else
    method_flag = CVMETHOD("MATCH_TEMPLATE_METHOD", method);

  CvArr* self_ptr = CVARR(self);
  CvArr* templ_ptr = CVARR_WITH_CHECK(templ);
  VALUE result = Qnil;
  try {
    CvSize src_size = cvGetSize(self_ptr);
    CvSize template_size = cvGetSize(templ_ptr);
    result = cCvMat::new_object(src_size.height - template_size.height + 1,
				src_size.width - template_size.width + 1,
				CV_32FC1);
    cvMatchTemplate(self_ptr, templ_ptr, CVARR(result), method_flag);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return result;
}

#mean_shift(window, criteria) ⇒ Object

Implements CAMSHIFT object tracking algrorithm. First, it finds an object center using mean_shift and, after that, calculates the object size and orientation.



5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
# File 'ext/opencv/cvmat.cpp', line 5278

VALUE
rb_mean_shift(VALUE self, VALUE window, VALUE criteria)
{
  VALUE comp = cCvConnectedComp::new_object();
  try {
    cvMeanShift(CVARR(self), VALUE_TO_CVRECT(window), VALUE_TO_CVTERMCRITERIA(criteria), CVCONNECTEDCOMP(comp));    
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return comp;
}

#min_max_loc(mask = nil) ⇒ Array<Number, CvPoint>

Finds the global minimum and maximum in an array.

Parameters:

  • mask (CvMat)

    Optional mask used to select a sub-array.

Returns:

  • (Array<Number, CvPoint>)

    [min_val, max_val, min_loc, max_loc], where min_val, max_val are minimum, maximum values as Number and min_loc, max_loc are minimum, maximum locations as CvPoint, respectively.



2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
# File 'ext/opencv/cvmat.cpp', line 2262

VALUE
rb_min_max_loc(int argc, VALUE *argv, VALUE self)
{
  VALUE mask, min_loc, max_loc;
  double min_val = 0.0, max_val = 0.0;
  rb_scan_args(argc, argv, "01", &mask);
  min_loc = cCvPoint::new_object();
  max_loc = cCvPoint::new_object();
  try {
    cvMinMaxLoc(CVARR(self), &min_val, &max_val, CVPOINT(min_loc), CVPOINT(max_loc), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(4, rb_float_new(min_val), rb_float_new(max_val), min_loc, max_loc);
}

#momentsObject

Calculates moments.



4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
# File 'ext/opencv/cvmat.cpp', line 4984

VALUE
rb_moments(int argc, VALUE *argv, VALUE self)
{
  VALUE is_binary;
  rb_scan_args(argc, argv, "01", &is_binary);
  CvArr *self_ptr = CVARR(self);
  VALUE moments = Qnil;
  try {
    moments = cCvMoments::new_object(self_ptr, TRUE_OR_FALSE(is_binary, 0));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return moments;
}

#morphology(operation, element = nil, iteration = 1) ⇒ CvMat

Performs advanced morphological transformations using erosion and dilation as basic operations.

Parameters:

  • operation (Integer)

    Type of morphological operation.

    • CV_MOP_OPEN - Opening

    • CV_MOP_CLOSE - Closing

    • CV_MOP_GRADIENT - Morphological gradient

    • CV_MOP_TOPHAT - Top hat

    • CV_MOP_BLACKHAT - Black hat

  • element (IplConvKernel)

    Structuring element.

  • iteration (Integer)

    Number of times erosion and dilation are applied.

Returns:

  • (CvMat)

    Result array



4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
# File 'ext/opencv/cvmat.cpp', line 4113

VALUE
rb_morphology(int argc, VALUE *argv, VALUE self)
{
  VALUE element, iteration, operation_val;
  rb_scan_args(argc, argv, "12", &operation_val, &element, &iteration);

  int operation = CVMETHOD("MORPHOLOGICAL_OPERATION", operation_val, -1);
  CvArr* self_ptr = CVARR(self);
  CvSize size = cvGetSize(self_ptr);
  VALUE dest = new_mat_kind_object(size, self);
  IplConvKernel* kernel = NIL_P(element) ? NULL : IPLCONVKERNEL_WITH_CHECK(element);
  try {
    if (operation == CV_MOP_GRADIENT) {
      CvMat* temp = rb_cvCreateMat(size.height, size.width, cvGetElemType(self_ptr));
      cvMorphologyEx(self_ptr, CVARR(dest), temp, kernel, CV_MOP_GRADIENT, IF_INT(iteration, 1));
      cvReleaseMat(&temp);
    }
    else {
      cvMorphologyEx(self_ptr, CVARR(dest), 0, kernel, operation, IF_INT(iteration, 1));
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return dest;
}

#mul(val, scale = 1.0) ⇒ CvMat

Calculates the per-element scaled product of two arrays.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to multiply

  • scale (Number)

    Optional scale factor.

Returns:

  • (CvMat)

    Result array



1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
# File 'ext/opencv/cvmat.cpp', line 1681

VALUE
rb_mul(int argc, VALUE *argv, VALUE self)
{
  VALUE val, scale, dest;
  if (rb_scan_args(argc, argv, "11", &val, &scale) < 2)
    scale = rb_float_new(1.0);
  dest = new_mat_kind_object(cvGetSize(CVARR(self)), self);
  try {
    if (rb_obj_is_kind_of(val, rb_klass))
      cvMul(CVARR(self), CVARR(val), CVARR(dest), NUM2DBL(scale));
    else {
      CvScalar scl = VALUE_TO_CVSCALAR(val);
      VALUE mat = new_object(cvGetSize(CVARR(self)), cvGetElemType(CVARR(self)));
      cvSet(CVARR(mat), scl);
      cvMul(CVARR(self), CVARR(mat), CVARR(dest), NUM2DBL(scale));
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#mul_transposed(options) ⇒ CvMat

Calculates the product of a matrix and its transposition.

This function calculates the product of self and its transposition:

if :order = 0
  dst = scale * (self - delta) * (self - delta)T
otherwise
  dst = scale * (self - delta)T * (self - delta)

Parameters:

  • options (Hash)

    Options

Options Hash (options):

  • :order (Integer) — default: 0

    Flag specifying the multiplication ordering, should be 0 or 1.

  • :delta (CvMat) — default: nil

    Optional delta matrix subtracted from source before the multiplication.

  • :scale (Number) — default: 1.0

    Optional scale factor for the matrix product.

Returns:

  • (CvMat)

    Result array.



2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
# File 'ext/opencv/cvmat.cpp', line 2431

VALUE
rb_mul_transposed(int argc, VALUE *argv, VALUE self)
{
  VALUE options = Qnil;
  VALUE _delta = Qnil, _scale = Qnil, _order = Qnil;

  if (rb_scan_args(argc, argv, "01", &options) > 0) {
    Check_Type(options, T_HASH);
    _delta = LOOKUP_HASH(options, "delta");
    _scale = LOOKUP_HASH(options, "scale");
    _order = LOOKUP_HASH(options, "order");
  }

  CvArr* delta = NIL_P(_delta) ? NULL : CVARR_WITH_CHECK(_delta);
  double scale = NIL_P(_scale) ? 1.0 : NUM2DBL(_scale);
  int order = NIL_P(_order) ? 0 : NUM2INT(_order);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = new_mat_kind_object(cvGetSize(self_ptr), self);
  try {
    cvMulTransposed(self_ptr, CVARR(dest), order, delta, scale);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return dest;
}

#ne(val) ⇒ CvMat

Performs the per-element comparison “not equal” of two arrays or an array and scalar value.

Parameters:

  • val (CvMat, CvScalar, Number)

    Array, scalar or number to compare

Returns:

  • (CvMat)

    Result array



2024
2025
2026
2027
2028
# File 'ext/opencv/cvmat.cpp', line 2024

VALUE
rb_ne(VALUE self, VALUE val)
{
  return rb_cmp_internal(self, val, CV_CMP_NE);
}

#normalize(alpha = 1.0, beta = 0.0, norm_type = NORM_L2, dtype = -1, mask = nil) ⇒ CvMat

Normalizes the norm or value range of an array.

Parameters:

  • alpha (Number) (defaults to: 1.0)

    Norm value to normalize to or the lower range boundary in case of the range normalization.

  • beta (Number) (defaults to: 0.0)

    Upper range boundary in case of the range normalization. It is not used for the norm normalization.

  • norm_type (Integer) (defaults to: NORM_L2)

    Normalization type.

  • dtype (Integer) (defaults to: -1)

    when negative, the output array has the same type as src; otherwise, it has the same number of channels as src and the depth

  • mask (CvMat) (defaults to: nil)

    Optional operation mask.

Returns:

  • (CvMat)

    Normalized array.



2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
# File 'ext/opencv/cvmat.cpp', line 2109

VALUE
rb_normalize(int argc, VALUE *argv, VALUE self)
{
  VALUE alpha_val, beta_val, norm_type_val, dtype_val, mask_val;
  rb_scan_args(argc, argv, "05", &alpha_val, &beta_val, &norm_type_val, &dtype_val, &mask_val);

  double alpha = NIL_P(alpha_val) ? 1.0 : NUM2DBL(alpha_val);
  double beta = NIL_P(beta_val) ? 0.0 : NUM2DBL(beta_val);
  int norm_type = NIL_P(norm_type_val) ? cv::NORM_L2 : NUM2INT(norm_type_val);
  int dtype = NIL_P(dtype_val) ? -1 : NUM2INT(dtype_val);
  VALUE dst;

  try {
    cv::Mat self_mat(CVMAT(self));
    cv::Mat dst_mat;

    if (NIL_P(mask_val)) {
      cv::normalize(self_mat, dst_mat, alpha, beta, norm_type, dtype);
    }
    else {
      cv::Mat mask(MASK(mask_val));
      cv::normalize(self_mat, dst_mat, alpha, beta, norm_type, dtype, mask);
    }
    dst = new_mat_kind_object(cvGetSize(CVARR(self)), self, dst_mat.depth(), dst_mat.channels());

    CvMat tmp = dst_mat;
    cvCopy(&tmp, CVMAT(dst));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return dst;
}

#notCvMat

Returns an array which elements are bit-wise invertion of source array.

Returns:

  • (CvMat)

    Result array



1893
1894
1895
1896
1897
# File 'ext/opencv/cvmat.cpp', line 1893

VALUE
rb_not(VALUE self)
{
  return rb_not_bang(copy(self));
}

#not!CvMat

Inverts every bit of an array.

Returns:

  • (CvMat)

    Result array



1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
# File 'ext/opencv/cvmat.cpp', line 1906

VALUE
rb_not_bang(VALUE self)
{
  try {
    cvNot(CVARR(self), CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#optical_flow_bm(prev[,velx = nil][,vely = nil][,option]) ⇒ Array

Calculates optical flow for two images (previous -> self) using block matching method. Return horizontal component of the optical flow and vertical component of the optical flow. prev is previous image. velx is previous velocity field of x-axis, and vely is previous velocity field of y-axis.

options

  • :block_size -> should be CvSize (default is CvSize(4,4))

    Size of basic blocks that are compared.
    
  • :shift_size -> should be CvSize (default is CvSize(1,1))

    Block coordinate increments.
    
  • :max_range -> should be CvSize (default is CVSize(4,4))

    Size of the scanned neighborhood in pixels around block.
    

note: option’s default value is CvMat::OPTICAL_FLOW_BM_OPTION.

Velocity is computed for every block, but not for every pixel, so velocity image pixels correspond to input image blocks. input/output velocity field’s size should be (self.width / block_size.width)x(self.height / block_size.height). e.g. image.size is 320x240 and block_size is 4x4, velocity field’s size is 80x60.

Returns:

  • (Array)


5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
# File 'ext/opencv/cvmat.cpp', line 5507

VALUE
rb_optical_flow_bm(int argc, VALUE *argv, VALUE self)
{
  VALUE prev, velx, vely, options;
  rb_scan_args(argc, argv, "13", &prev, &velx, &vely, &options);
  options = OPTICAL_FLOW_BM_OPTION(options);
  CvArr* self_ptr = CVARR(self);
  CvSize block_size = BM_BLOCK_SIZE(options);
  CvSize shift_size = BM_SHIFT_SIZE(options);
  CvSize max_range  = BM_MAX_RANGE(options);

  int use_previous = 0;
  try {
    CvSize image_size = cvGetSize(self_ptr);
    CvSize velocity_size = cvSize((image_size.width - block_size.width + shift_size.width) / shift_size.width,
				  (image_size.height - block_size.height + shift_size.height) / shift_size.height);
    CvMat *velx_ptr, *vely_ptr;
    if (NIL_P(velx) && NIL_P(vely)) {
      int type = CV_MAKETYPE(CV_32F, 1);
      velx = cCvMat::new_object(velocity_size, type);
      vely = cCvMat::new_object(velocity_size, type);
      velx_ptr = CVMAT(velx);
      vely_ptr = CVMAT(vely);
    }
    else {
      use_previous = 1;
      velx_ptr = CVMAT_WITH_CHECK(velx);
      vely_ptr = CVMAT_WITH_CHECK(vely);
    }
    cvCalcOpticalFlowBM(CVMAT_WITH_CHECK(prev), self_ptr,
			block_size, shift_size, max_range, use_previous,
			velx_ptr, vely_ptr);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(2, velx, vely);
}

#optical_flow_hs(prev[,velx = nil][,vely = nil][,options]) ⇒ Array

Calculates optical flow for two images (previous -> self) using Horn & Schunck algorithm. Return horizontal component of the optical flow and vertical component of the optical flow. prev is previous image velx is previous velocity field of x-axis, and vely is previous velocity field of y-axis.

options

  • :lambda -> should be Float (default is 0.0005)

    Lagrangian multiplier.
    
  • :criteria -> should be CvTermCriteria object (default is CvTermCriteria(1, 0.001))

    Criteria of termination of velocity computing.
    

note: option’s default value is CvMat::OPTICAL_FLOW_HS_OPTION.

sample code

velx, vely = nil, nil
while true
  current = capture.query
  velx, vely = current.optical_flow_hs(prev, velx, vely) if prev
  prev = current
end

Returns:

  • (Array)


5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
# File 'ext/opencv/cvmat.cpp', line 5422

VALUE
rb_optical_flow_hs(int argc, VALUE *argv, VALUE self)
{
  VALUE prev, velx, vely, options;
  int use_previous = 0;
  rb_scan_args(argc, argv, "13", &prev, &velx, &vely, &options);
  options = OPTICAL_FLOW_HS_OPTION(options);
  CvMat *velx_ptr, *vely_ptr;
  CvArr* self_ptr = CVARR(self);
  try {
    if (NIL_P(velx) && NIL_P(vely)) {
      CvSize size = cvGetSize(self_ptr);
      int type = CV_MAKETYPE(CV_32F, 1);
      velx = cCvMat::new_object(size, type);
      vely = cCvMat::new_object(size, type);
      velx_ptr = CVMAT(velx);
      vely_ptr = CVMAT(vely);
    }
    else {
      use_previous = 1;
      velx_ptr = CVMAT_WITH_CHECK(velx);
      vely_ptr = CVMAT_WITH_CHECK(vely);
    }
    cvCalcOpticalFlowHS(CVMAT_WITH_CHECK(prev), self_ptr, use_previous, velx_ptr, vely_ptr,
			HS_LAMBDA(options), HS_CRITERIA(options));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(2, velx, vely);
}

#optical_flow_lk(prev, win_size) ⇒ Array

Calculates optical flow for two images (previous -> self) using Lucas & Kanade algorithm Return horizontal component of the optical flow and vertical component of the optical flow.

win_size is size of the averaging window used for grouping pixels.

Returns:

  • (Array)


5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
# File 'ext/opencv/cvmat.cpp', line 5463

VALUE
rb_optical_flow_lk(VALUE self, VALUE prev, VALUE win_size)
{
  VALUE velx = Qnil;
  VALUE vely = Qnil;
  try {
    CvArr* self_ptr = CVARR(self);
    CvSize size = cvGetSize(self_ptr);
    int type = CV_MAKETYPE(CV_32F, 1);
    velx = cCvMat::new_object(size, type);
    vely = cCvMat::new_object(size, type);
    cvCalcOpticalFlowLK(CVMAT_WITH_CHECK(prev), self_ptr, VALUE_TO_CVSIZE(win_size),
			CVARR(velx), CVARR(vely));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return rb_ary_new3(2, velx, vely);
}

#or(val, mask = nil) ⇒ CvMat Also known as: |

Calculates the per-element bit-wise disjunction of two arrays or an array and a scalar.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to calculate bit-wise disjunction

  • mask (CvMat)

    Optional operation mask, 8-bit single channel array, that specifies elements of the destination array to be changed.

Returns:

  • (CvMat)

    Result array



1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
# File 'ext/opencv/cvmat.cpp', line 1839

VALUE
rb_or(int argc, VALUE *argv, VALUE self)
{
  VALUE val, mask, dest;
  rb_scan_args(argc, argv, "11", &val, &mask);
  dest = copy(self);
  try {
    if (rb_obj_is_kind_of(val, rb_klass))
      cvOr(CVARR(self), CVARR(val), CVARR(dest), MASK(mask));
    else
      cvOrS(CVARR(self), VALUE_TO_CVSCALAR(val), CVARR(dest), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#perspective_transform(mat) ⇒ CvMat

Performs the perspective matrix transformation of vectors.

Parameters:

  • mat (CvMat)

    3x3 or 4x4 floating-point transformation matrix.

Returns:

  • (CvMat)

    Transformed vector.



2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
# File 'ext/opencv/cvmat.cpp', line 2399

VALUE
rb_perspective_transform(VALUE self, VALUE mat)
{
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvPerspectiveTransform(self_ptr, CVARR(dest), CVMAT_WITH_CHECK(mat));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#poly_line(points, options = nil) ⇒ CvMat

Returns an image that is drawn several polygonal curves.

Parameters:

  • points (Array<CvPoint>)

    Array of polygonal curves.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :is_closed (Boolean)

    Indicates whether the polylines must be drawn closed. If closed, the method draws the line from the last vertex of every contour to the first vertex.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



3199
3200
3201
3202
3203
# File 'ext/opencv/cvmat.cpp', line 3199

VALUE
rb_poly_line(int argc, VALUE *argv, VALUE self)
{
  return rb_poly_line_bang(argc, argv, rb_clone(self));
}

#poly_line!(points, options = nil) ⇒ CvMat

Draws several polygonal curves.

Parameters:

  • points (Array<CvPoint>)

    Array of polygonal curves.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :is_closed (Boolean)

    Indicates whether the polylines must be drawn closed. If closed, the method draws the line from the last vertex of every contour to the first vertex.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
# File 'ext/opencv/cvmat.cpp', line 3225

VALUE
rb_poly_line_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE polygons, drawing_option;
  VALUE points;
  int i, j;
  int num_polygons;
  int *num_points;
  CvPoint **p;

  rb_scan_args(argc, argv, "11", &polygons, &drawing_option);
  Check_Type(polygons, T_ARRAY);
  drawing_option = DRAWING_OPTION(drawing_option);
  num_polygons = RARRAY_LEN(polygons);
  num_points = ALLOCA_N(int, num_polygons);
  p = ALLOCA_N(CvPoint*, num_polygons);

  for (j = 0; j < num_polygons; ++j) {
    points = rb_ary_entry(polygons, j);
    Check_Type(points, T_ARRAY);
    num_points[j] = RARRAY_LEN(points);
    p[j] = ALLOCA_N(CvPoint, num_points[j]);
    for (i = 0; i < num_points[j]; ++i) {
      p[j][i] = VALUE_TO_CVPOINT(rb_ary_entry(points, i));
    }
  }

  try {
    cvPolyLine(CVARR(self), p, num_points, num_polygons,
	       DO_IS_CLOSED(drawing_option),
	       DO_COLOR(drawing_option),
	       DO_THICKNESS(drawing_option),
	       DO_LINE_TYPE(drawing_option),
	       DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return self;
}

#pre_corner_detect(aperture_size = 3) ⇒ CvMat

Calculates a feature map for corner detection.

Parameters:

  • aperture_size (Integer)

    Aperture size for the sobel operator.

Returns:

  • (CvMat)

    Output image



3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
# File 'ext/opencv/cvmat.cpp', line 3425

VALUE
rb_pre_corner_detect(int argc, VALUE *argv, VALUE self)
{
  VALUE aperture_size, dest = Qnil;
  if (rb_scan_args(argc, argv, "01", &aperture_size) < 1)
    aperture_size = INT2FIX(3);

  CvArr *self_ptr = CVARR(self);
  try {
    dest = new_object(cvGetSize(self_ptr), CV_MAKETYPE(CV_32F, 1));
    cvPreCornerDetect(self_ptr, CVARR(dest), NUM2INT(aperture_size));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#put_text(text, org, font, color = CvColor::Black) ⇒ CvMat

Returns an image which is drawn a text string.

Parameters:

  • text (String)

    Text string to be drawn.

  • org (CvPoint)

    Bottom-left corner of the text string in the image.

  • font (CvFont)

    CvFont object.

  • color (CvScalar)

    Text color.

Returns:

  • (CvMat)

    Output image



3279
3280
3281
3282
3283
# File 'ext/opencv/cvmat.cpp', line 3279

VALUE
rb_put_text(int argc, VALUE* argv, VALUE self)
{
  return rb_put_text_bang(argc, argv, rb_clone(self));
}

#put_text!(text, org, font, color = CvColor::Black) ⇒ CvMat

Draws a text string.

Parameters:

  • text (String)

    Text string to be drawn.

  • org (CvPoint)

    Bottom-left corner of the text string in the image.

  • font (CvFont)

    CvFont object.

  • color (CvScalar)

    Text color.

Returns:



3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
# File 'ext/opencv/cvmat.cpp', line 3296

VALUE
rb_put_text_bang(int argc, VALUE* argv, VALUE self)
{
  VALUE _text, _point, _font, _color;
  rb_scan_args(argc, argv, "31", &_text, &_point, &_font, &_color);
  CvScalar color = NIL_P(_color) ? CV_RGB(0, 0, 0) : VALUE_TO_CVSCALAR(_color);
  try {
    cvPutText(CVARR(self), StringValueCStr(_text), VALUE_TO_CVPOINT(_point),
	      CVFONT_WITH_CHECK(_font), color);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#pyr_down([filter = :gaussian_5x5]) ⇒ Object

Return downsamples image.

This operation performs downsampling step of Gaussian pyramid decomposition. First it convolves source image with the specified filter and then downsamples the image by rejecting even rows and columns.

note: filter - only :gaussian_5x5 is currently supported.



4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
# File 'ext/opencv/cvmat.cpp', line 4594

VALUE
rb_pyr_down(int argc, VALUE *argv, VALUE self)
{
  int filter = CV_GAUSSIAN_5x5;
  if (argc > 0) {
    VALUE filter_type = argv[0];
    switch (TYPE(filter_type)) {
    case T_SYMBOL:
      // currently suport CV_GAUSSIAN_5x5 only.
      break;
    default:
      raise_typeerror(filter_type, rb_cSymbol);
    }
  }
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    CvSize original_size = cvGetSize(self_ptr);
    CvSize size = { original_size.width >> 1, original_size.height >> 1 };
    dest = new_mat_kind_object(size, self);
    cvPyrDown(self_ptr, CVARR(dest), filter);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#pyr_mean_shift_filtering(sp, sr[,max_level = 1][termcrit = CvTermCriteria.new(5,1)]) ⇒ Object

Does meanshift image segmentation.

sp - The spatial window radius.
sr - The color window radius.
max_level - Maximum level of the pyramid for the segmentation.
termcrit - Termination criteria: when to stop meanshift iterations.

This method is 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:

{(x,y): X-sp≤x≤X+sp && Y-sp≤y≤Y+sp && ||(R,G,B)-(r,g,b)|| ≤ sr},

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:

(X,Y)~(X',Y'), (R,G,B)~(R',G',B').

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):

I(X,Y) <- (R*,G*,B*).

Then max_level > 0, the gaussian pyramid of max_level+1 levels is built, and the above procedure is run on the smallest layer. 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 much (>sr) from the lower-resolution layer, that is, the boundaries of the color regions are clarified.

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 max_level==0).



4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
# File 'ext/opencv/cvmat.cpp', line 4936

VALUE
rb_pyr_mean_shift_filtering(int argc, VALUE *argv, VALUE self)
{
  VALUE spatial_window_radius, color_window_radius, max_level, termcrit;
  rb_scan_args(argc, argv, "22", &spatial_window_radius, &color_window_radius, &max_level, &termcrit);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvPyrMeanShiftFiltering(self_ptr, CVARR(dest),
			    NUM2DBL(spatial_window_radius),
			    NUM2DBL(color_window_radius),
			    IF_INT(max_level, 1),
			    NIL_P(termcrit) ? cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, 5, 1)
			    : VALUE_TO_CVTERMCRITERIA(termcrit));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#pyr_up([filter = :gaussian_5x5]) ⇒ Object

Return upsamples image.

This operation performs up-sampling step of Gaussian pyramid decomposition. First it upsamples the source image by injecting even zero rows and columns and then convolves result with the specified filter multiplied by 4 for interpolation. So the destination image is four times larger than the source image.

note: filter - only :gaussian_5x5 is currently supported.



4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
# File 'ext/opencv/cvmat.cpp', line 4635

VALUE
rb_pyr_up(int argc, VALUE *argv, VALUE self)
{
  VALUE filter_type;
  rb_scan_args(argc, argv, "01", &filter_type);
  int filter = CV_GAUSSIAN_5x5;
  if (argc > 0) {
    switch (TYPE(filter_type)) {
    case T_SYMBOL:
      // currently suport CV_GAUSSIAN_5x5 only.
      break;
    default:
      raise_typeerror(filter_type, rb_cSymbol);
    }
  }
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    CvSize original_size = cvGetSize(self_ptr);
    CvSize size = { original_size.width << 1, original_size.height << 1 };
    dest = new_mat_kind_object(size, self);
    cvPyrUp(self_ptr, CVARR(dest), filter);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#quadrangle_sub_pix(map_matrix, size = self.size) ⇒ CvMat

Note:

CvMat#quadrangle_sub_pix is similar to CvMat#warp_affine, but the outliers are extrapolated using replication border mode.

Applies an affine transformation to an image.

Parameters:

  • map_matrix (CvMat)

    2x3 transformation matrix.

  • size (CvSize)

    Size of the output image.

Returns:

  • (CvMat)

    Output image that has the size size and the same type as self.



3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
# File 'ext/opencv/cvmat.cpp', line 3726

VALUE
rb_quadrangle_sub_pix(int argc, VALUE *argv, VALUE self)
{
  VALUE map_matrix, size;
  VALUE dest = Qnil;
  CvSize _size;
  CvArr* self_ptr = CVARR(self);
  try {
    if (rb_scan_args(argc, argv, "11", &map_matrix, &size) < 2)
      _size = cvGetSize(self_ptr);
    else
      _size = VALUE_TO_CVSIZE(size);
    dest = new_mat_kind_object(_size, self);
    cvGetQuadrangleSubPix(self_ptr, CVARR(dest), CVMAT_WITH_CHECK(map_matrix));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#rand_shuffle(seed = -1, iter_factor = 1) ⇒ CvMat

Returns shuffled matrix by swapping randomly chosen pairs of the matrix elements on each iteration (where each element may contain several components in case of multi-channel arrays)

Parameters:

  • seed (Integer)

    Integer value used to initiate a random sequence

  • iter_factor (Integer)

    The relative parameter that characterizes intensity of the shuffling performed. The number of iterations (i.e. pairs swapped) is round(iter_factor*rows(mat)*cols(mat)), so iter_factor = 0 means that no shuffling is done, iter_factor = 1 means that the function swaps rows(mat)*cols(mat) random pairs etc

Returns:

  • (CvMat)

    Shuffled matrix



1496
1497
1498
1499
1500
# File 'ext/opencv/cvmat.cpp', line 1496

VALUE
rb_rand_shuffle(int argc, VALUE *argv, VALUE self)
{
  return rb_rand_shuffle_bang(argc, argv, copy(self));
}

#rand_shuffle!(seed = -1, iter_factor = 1) ⇒ CvMat

Shuffles the matrix by swapping randomly chosen pairs of the matrix elements on each iteration (where each element may contain several components in case of multi-channel arrays)

Parameters:

  • seed (Integer)

    Integer value used to initiate a random sequence

  • iter_factor (Integer)

    The relative parameter that characterizes intensity of the shuffling performed. The number of iterations (i.e. pairs swapped) is round(iter_factor*rows(mat)*cols(mat)), so iter_factor = 0 means that no shuffling is done, iter_factor = 1 means that the function swaps rows(mat)*cols(mat) random pairs etc

Returns:

  • (CvMat)

    Shuffled matrix



1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'ext/opencv/cvmat.cpp', line 1511

VALUE
rb_rand_shuffle_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE seed, iter;
  rb_scan_args(argc, argv, "02", &seed, &iter);
  try {
    if (NIL_P(seed))
      cvRandShuffle(CVARR(self), NULL, IF_INT(iter, 1));
    else {
      CvRNG rng = cvRNG(rb_num2ll(seed));
      cvRandShuffle(CVARR(self), &rng, IF_INT(iter, 1));
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#range(start, end) ⇒ CvMat

Returns initialized matrix as following:

arr(i,j)=(end-start)*(i*cols(arr)+j)/(cols(arr)*rows(arr))

Parameters:

  • start (Number)

    The lower inclusive boundary of the range

  • end (Number)

    The upper exclusive boundary of the range

Returns:

  • (CvMat)

    Initialized matrix



1272
1273
1274
1275
1276
# File 'ext/opencv/cvmat.cpp', line 1272

VALUE
rb_range(VALUE self, VALUE start, VALUE end)
{
  return rb_range_bang(copy(self), start, end);
}

#range!(start, end) ⇒ CvMat

Initializes the matrix as following:

arr(i,j)=(end-start)*(i*cols(arr)+j)/(cols(arr)*rows(arr))

Parameters:

  • start (Number)

    The lower inclusive boundary of the range

  • end (Number)

    The upper exclusive boundary of the range

Returns:



1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# File 'ext/opencv/cvmat.cpp', line 1286

VALUE
rb_range_bang(VALUE self, VALUE start, VALUE end)
{
  try {
    cvRange(CVARR(self), NUM2DBL(start), NUM2DBL(end));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#rect_sub_pix(center, size = self.size) ⇒ CvMat

Retrieves a pixel rectangle from an image with sub-pixel accuracy.

Parameters:

  • center (CvPoint2D32f)

    Floating point coordinates of the center of the extracted rectangle within the source image. The center must be inside the image.

  • size (CvSize)

    Size of the extracted patch.

Returns:

  • (CvMat)

    Extracted patch that has the size size and the same number of channels as self.



3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
# File 'ext/opencv/cvmat.cpp', line 3694

VALUE
rb_rect_sub_pix(int argc, VALUE *argv, VALUE self)
{
  VALUE center, size;
  VALUE dest = Qnil;
  CvSize _size;
  CvArr* self_ptr = CVARR(self);
  try {
    if (rb_scan_args(argc, argv, "11", &center, &size) < 2)
      _size = cvGetSize(self_ptr);
    else
      _size = VALUE_TO_CVSIZE(size);
    dest = new_mat_kind_object(_size, self);
    cvGetRectSubPix(self_ptr, CVARR(dest), VALUE_TO_CVPOINT2D32F(center));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#rectangle(p1, p2, options = nil) ⇒ CvMat

Returns an image that is drawn a simple, thick, or filled up-right rectangle.

Parameters:

  • p1 (CvPoint)

    Vertex of the rectangle.

  • p2 (CvPoint)

    Vertex of the rectangle opposite to p1.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:

  • (CvMat)

    Output image



2811
2812
2813
2814
2815
# File 'ext/opencv/cvmat.cpp', line 2811

VALUE
rb_rectangle(int argc, VALUE *argv, VALUE self)
{
  return rb_rectangle_bang(argc, argv, rb_clone(self));
}

#rectangle!(p1, p2, options = nil) ⇒ CvMat

Draws a simple, thick, or filled up-right rectangle.

Parameters:

  • p1 (CvPoint)

    Vertex of the rectangle.

  • p2 (CvPoint)

    Vertex of the rectangle opposite to p1.

  • options (Hash) (defaults to: nil)

    Drawing options

Options Hash (options):

  • :color (CvScalar)

    Line color.

  • :thickness (Integer)

    Line thickness.

  • :line_type (Integer)

    Type of the line.

    • 8 - 8-connected line.

    • 4 - 4-connected line.

    • CV_AA - Antialiased line.

  • :shift (Integer)

    Number of fractional bits in the point coordinates.

Returns:



2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
# File 'ext/opencv/cvmat.cpp', line 2834

VALUE
rb_rectangle_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE p1, p2, drawing_option;
  rb_scan_args(argc, argv, "21", &p1, &p2, &drawing_option);
  drawing_option = DRAWING_OPTION(drawing_option);
  try {
    cvRectangle(CVARR(self), VALUE_TO_CVPOINT(p1), VALUE_TO_CVPOINT(p2),
		DO_COLOR(drawing_option),
		DO_THICKNESS(drawing_option),
		DO_LINE_TYPE(drawing_option),
		DO_SHIFT(drawing_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#remap(mapx, mapy, flags = CV_INTER_LINEAR|CV_WARP_FILL_OUTLIERS, fillval = 0) ⇒ CvMat

Applies a generic geometrical transformation to an image.

Parameters:

  • mapx (CvMat)

    The first map of either (x,y) points or just x values having the type CV_16SC2, CV_32FC1, or CV_32FC2.

  • mapy (CvMat)

    The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map if mapx is (x,y) points), respectively.

  • flags (Integer) (defaults to: CV_INTER_LINEAR|CV_WARP_FILL_OUTLIERS)

    Combination of interpolation methods (CV_INTER_LINEAR or CV_INTER_NEAREST) and the optional flag CV_WARP_INVERSE_MAP, that sets map_matrix as the inverse transformation.

  • fillval (Number, CvScalar) (defaults to: 0)

    Value used in case of a constant border.

Returns:

  • (CvMat)

    Output image.



3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
# File 'ext/opencv/cvmat.cpp', line 3974

VALUE
rb_remap(int argc, VALUE *argv, VALUE self)
{
  VALUE mapx, mapy, flags_val, option, fillval;
  if (rb_scan_args(argc, argv, "23", &mapx, &mapy, &flags_val, &option, &fillval) < 5)
    fillval = INT2FIX(0);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  int flags = NIL_P(flags_val) ? (CV_INTER_LINEAR | CV_WARP_FILL_OUTLIERS) : NUM2INT(flags_val);
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvRemap(self_ptr, CVARR(dest), CVARR_WITH_CHECK(mapx), CVARR_WITH_CHECK(mapy),
	    flags, VALUE_TO_CVSCALAR(fillval));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#repeat(dst) ⇒ CvMat

Fills the destination array with repeated copies of the source array.

Parameters:

  • dst (CvMat)

    Destination array of the same type as self.

Returns:

  • (CvMat)

    Destination array



1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
# File 'ext/opencv/cvmat.cpp', line 1335

VALUE
rb_repeat(VALUE self, VALUE object)
{
  try {
    cvRepeat(CVARR(self), CVARR_WITH_CHECK(object));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return object;
}

#reshape(cn, rows = 0) ⇒ CvMat

Changes shape of matrix/image without copying data.

Examples:

mat = CvMat.new(3, 3, CV_8U, 3)  #=> 3x3 3-channel matrix
vec = mat.reshape(:rows => 1)    #=> 1x9 3-channel matrix
ch1 = mat.reshape(:channel => 1) #=> 9x3 1-channel matrix

Parameters:

  • cn (Integer)

    New number of channels. If the parameter is 0, the number of channels remains the same.

  • rows (Integer) (defaults to: 0)

    New number of rows. If the parameter is 0, the number of rows remains the same.

Returns:

  • (CvMat)

    Changed matrix



1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
# File 'ext/opencv/cvmat.cpp', line 1310

VALUE
rb_reshape(int argc, VALUE *argv, VALUE self)
{
  VALUE cn, rows;
  CvMat *mat = NULL;
  rb_scan_args(argc, argv, "11", &cn, &rows);
  try {
    mat = cvReshape(CVARR(self), RB_CVALLOC(CvMat), NUM2INT(cn), IF_INT(rows, 0));
  }
  catch (cv::Exception& e) {
    if (mat != NULL)
      cvReleaseMat(&mat);
    raise_cverror(e);
  }
  return DEPEND_OBJECT(rb_klass, mat, self);
}

#resize(size, interpolation = :linear) ⇒ CvMat

Resizes an image.

Parameters:

  • size (CvSize)

    Output image size.

  • interpolation (Symbol)

    Interpolation method:

    • CV_INTER_NN - A nearest-neighbor interpolation

    • CV_INTER_LINEAR - A bilinear interpolation (used by default)

    • CV_INTER_AREA - 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 :nn method.

    • CV_INTER_CUBIC - A bicubic interpolation over 4x4 pixel neighborhood

    • CV_INTER_LANCZOS4 - A Lanczos interpolation over 8x8 pixel neighborhood

Returns:

  • (CvMat)

    Output image.



3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
# File 'ext/opencv/cvmat.cpp', line 3763

VALUE
rb_resize(int argc, VALUE *argv, VALUE self)
{
  VALUE size, interpolation;
  rb_scan_args(argc, argv, "11", &size, &interpolation);
  VALUE dest = new_mat_kind_object(VALUE_TO_CVSIZE(size), self);
  int method = NIL_P(interpolation) ? CV_INTER_LINEAR : NUM2INT(interpolation);

  try {
    cvResize(CVARR(self), CVARR(dest), method);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#save_image(filename) ⇒ CvMat Also known as: save

Saves an image to a specified file. The image format is chosen based on the filename extension.

Parameters:

  • filename (String)

    Name of the file

Returns:



1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
# File 'ext/opencv/cvmat.cpp', line 1163

VALUE
rb_save_image(int argc, VALUE *argv, VALUE self)
{
  VALUE _filename, _params;
  rb_scan_args(argc, argv, "11", &_filename, &_params);
  Check_Type(_filename, T_STRING);
  int *params = NULL;
  if (!NIL_P(_params)) {
    params = hash_to_format_specific_param(_params);
  }

  try {
    cvSaveImage(StringValueCStr(_filename), CVARR(self), params);
  }
  catch (cv::Exception& e) {
    if (params != NULL) {
      free(params);
      params = NULL;
    }
    raise_cverror(e);
  }
  if (params != NULL) {
    free(params);
    params = NULL;
  }

  return self;
}

#sdv(mask = nil) ⇒ CvScalar

Calculates a standard deviation of array elements.

Parameters:

  • mask (CvMat)

    Optional operation mask.

Returns:

  • (CvScalar)

    The standard deviation of array elements.



2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
# File 'ext/opencv/cvmat.cpp', line 2237

VALUE
rb_sdv(int argc, VALUE *argv, VALUE self)
{
  VALUE mask, std_dev;
  rb_scan_args(argc, argv, "01", &mask);
  std_dev = cCvScalar::new_object();
  try {
    cvAvgSdv(CVARR(self), NULL, CVSCALAR(std_dev), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return std_dev;
}

#set(value, mask = nil) ⇒ CvMat Also known as: fill

Returns a matrix which is set every element to a given value. The function copies the scalar value to every selected element of the destination array:

mat[I] = value if mask(I) != 0

Parameters:

  • value (CvScalar)

    Fill value

  • mask (CvMat)

    Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed

Returns:

  • (CvMat)

    Matrix which is set every element to a given value.



1125
1126
1127
1128
1129
# File 'ext/opencv/cvmat.cpp', line 1125

VALUE
rb_set(int argc, VALUE *argv, VALUE self)
{
  return rb_set_bang(argc, argv, copy(self));
}

#set!(value, mask = nil) ⇒ CvMat Also known as: fill!

Sets every element of the matrix to a given value. The function copies the scalar value to every selected element of the destination array:

mat[I] = value if mask(I) != 0

Parameters:

  • value (CvScalar)

    Fill value

  • mask (CvMat)

    Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed

Returns:



1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
# File 'ext/opencv/cvmat.cpp', line 1141

VALUE
rb_set_bang(int argc, VALUE *argv, VALUE self)
{
  VALUE value, mask;
  rb_scan_args(argc, argv, "11", &value, &mask);
  try {
    cvSet(CVARR(self), VALUE_TO_CVSCALAR(value), MASK(mask));    
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#set_data(data) ⇒ CvMat

Assigns user data to the array header

Parameters:

  • data (Array<Integer>)

    User data

Returns:



1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
# File 'ext/opencv/cvmat.cpp', line 1053

VALUE
rb_set_data(VALUE self, VALUE data)
{
  data = rb_funcall(data, rb_intern("flatten"), 0);
  const int DATA_LEN = RARRAY_LEN(data);
  CvMat *self_ptr = CVMAT(self);
  int depth = CV_MAT_DEPTH(self_ptr->type);
  void* array = NULL;

  switch (depth) {
  case CV_8U:
    array = rb_cvAlloc(sizeof(uchar) * DATA_LEN);
    for (int i = 0; i < DATA_LEN; ++i)
      ((uchar*)array)[i] = (uchar)(NUM2INT(rb_ary_entry(data, i)));
    break;
  case CV_8S:
    array = rb_cvAlloc(sizeof(char) * DATA_LEN);
    for (int i = 0; i < DATA_LEN; ++i)
      ((char*)array)[i] = (char)(NUM2INT(rb_ary_entry(data, i)));
    break;
  case CV_16U:
    array = rb_cvAlloc(sizeof(ushort) * DATA_LEN);
    for (int i = 0; i < DATA_LEN; ++i)
      ((ushort*)array)[i] = (ushort)(NUM2INT(rb_ary_entry(data, i)));
    break;
  case CV_16S:
    array = rb_cvAlloc(sizeof(short) * DATA_LEN);
    for (int i = 0; i < DATA_LEN; ++i)
      ((short*)array)[i] = (short)(NUM2INT(rb_ary_entry(data, i)));
    break;
  case CV_32S:
    array = rb_cvAlloc(sizeof(int) * DATA_LEN);
    for (int i = 0; i < DATA_LEN; ++i)
      ((int*)array)[i] = NUM2INT(rb_ary_entry(data, i));
    break;
  case CV_32F:
    array = rb_cvAlloc(sizeof(float) * DATA_LEN);
    for (int i = 0; i < DATA_LEN; ++i)
      ((float*)array)[i] = (float)NUM2DBL(rb_ary_entry(data, i));
    break;
  case CV_64F:
    array = rb_cvAlloc(sizeof(double) * DATA_LEN);
    for (int i = 0; i < DATA_LEN; ++i)
      ((double*)array)[i] = NUM2DBL(rb_ary_entry(data, i));
    break;
  default:
    rb_raise(rb_eArgError, "Invalid CvMat depth");
    break;
  }

  try {
    cvSetData(self_ptr, array, self_ptr->step);    
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return self;
}

#set_zeroCvMat Also known as: clear, zero

Returns cleared array.

Returns:

  • (CvMat)

    Cleared array



1198
1199
1200
1201
1202
# File 'ext/opencv/cvmat.cpp', line 1198

VALUE
rb_set_zero(VALUE self)
{
  return rb_set_zero_bang(copy(self));
}

#set_zero!CvMat Also known as: clear!, zero!

Clears the array.

Returns:



1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
# File 'ext/opencv/cvmat.cpp', line 1210

VALUE
rb_set_zero_bang(VALUE self)
{
  try {
    cvSetZero(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return self;
}

#sizeCvSize

Returns size of the matrix

Returns:

  • (CvSize)

    Size of the matrix



905
906
907
908
909
910
911
912
913
914
915
916
# File 'ext/opencv/cvmat.cpp', line 905

VALUE
rb_size(VALUE self)
{
  CvSize size;
  try {
    size = cvGetSize(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return cCvSize::new_object(size);
}

#smooth(smoothtype, size1 = 3, size2 = 0, sigma1 = 0, sigma2 = 0) ⇒ CvMat

Smooths the image in one of several ways.

Parameters:

  • smoothtype (Integer)

    Type of the smoothing.

    • CV_BLUR_NO_SCALE - linear convolution with size1 x size2 box kernel (all 1’s). If you want to smooth different pixels with different-size box kernels, you can use the integral image that is computed using CvMat#integral.

    • CV_BLUR - linear convolution with size1 x size2 box kernel (all 1’s) with subsequent scaling by 1 / (size1 x size1).

    • CV_GAUSSIAN - linear convolution with a size1 x size2 Gaussian kernel.

    • CV_MEDIAN - median filter with a size1 x size1 square aperture

    • CV_BILATERAL - bilateral filter with a size1 x size1 square aperture, color sigma = sigma1 and spatial sigma = sigma2. If size1 = 0, the aperture square side is set to CvMat#round(sigma2 * 1.5) * 2 + 1.

  • size1 (Integer) (defaults to: 3)

    The first parameter of the smoothing operation, the aperture width. Must be a positive odd number (1, 3, 5, …)

  • size2 (Integer) (defaults to: 0)

    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.

  • sigma1 (Integer) (defaults to: 0)

    In the case of a Gaussian parameter this parameter may specify Gaussian sigma (standard deviation). If it is zero, it is calculated from the kernel size.

Returns:

  • (CvMat)

    The destination image.



4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
# File 'ext/opencv/cvmat.cpp', line 4278

VALUE
rb_smooth(int argc, VALUE *argv, VALUE self)
{
  VALUE smoothtype, p1, p2, p3, p4;
  rb_scan_args(argc, argv, "14", &smoothtype, &p1, &p2, &p3, &p4);
  int _smoothtype = CVMETHOD("SMOOTHING_TYPE", smoothtype, -1);
  
  VALUE (*smooth_func)(int c, VALUE* v, VALUE s);
  argc--;
  switch (_smoothtype) {
  case CV_BLUR_NO_SCALE:
    smooth_func = rb_smooth_blur_no_scale;
    argc = (argc > 2) ? 2 : argc;
    break;
  case CV_BLUR:
    smooth_func = rb_smooth_blur;
    argc = (argc > 2) ? 2 : argc;
    break;
  case CV_GAUSSIAN:
    smooth_func = rb_smooth_gaussian;
    break;
  case CV_MEDIAN:
    smooth_func = rb_smooth_median;
    argc = (argc > 1) ? 1 : argc;
    break;
  case CV_BILATERAL:
    smooth_func = rb_smooth_bilateral;
    argc = (argc > 2) ? 2 : argc;
    break;
  default:
    smooth_func = rb_smooth_gaussian;
    break;
  }
  VALUE result = Qnil;
  try {
    result = (*smooth_func)(argc, argv + 1, self);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return result;
}

#snake_image(points, alpha, beta, gamma, window, criteria[, calc_gradient = true]) ⇒ Object

Updates snake in order to minimize its total energy that is a sum of internal energy that depends on contour shape (the smoother contour is, the smaller internal energy is) and external energy that depends on the energy field and reaches minimum at the local energy extremums that correspond to the image edges in case of image gradient.

The parameter criteria.epsilon is used to define the minimal number of points that must be moved during any iteration to keep the iteration process running.

If at some iteration the number of moved points is less than criteria.epsilon or the function performed criteria.max_iter iterations, the function terminates.

points

Contour points (snake).

alpha

Weight[s] of continuity energy, single float or array of length floats, one per each contour point.

beta

Weight[s] of curvature energy, similar to alpha.

gamma

Weight[s] of image energy, similar to alpha.

window

Size of neighborhood of every point used to search the minimum, both win.width and win.height must be odd.

criteria

Termination criteria.

calc_gradient

Gradient flag. If not 0, the function calculates gradient magnitude for every image pixel and consideres
it as the energy field, otherwise the input image itself is considered.


5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
# File 'ext/opencv/cvmat.cpp', line 5345

VALUE
rb_snake_image(int argc, VALUE *argv, VALUE self)
{
  VALUE points, alpha, beta, gamma, window, criteria, calc_gradient;
  rb_scan_args(argc, argv, "61", &points, &alpha, &beta, &gamma, &window, &criteria, &calc_gradient);
  CvPoint *pointset = 0;
  int length = CVPOINTS_FROM_POINT_SET(points, &pointset);
  int coeff = (TYPE(alpha) == T_ARRAY && TYPE(beta) == T_ARRAY && TYPE(gamma) == T_ARRAY) ? CV_ARRAY : CV_VALUE;
  float *a = 0, *b = 0, *c = 0;
  IplImage stub;
  int i;
  if (coeff == CV_VALUE) {
    float buff_a, buff_b, buff_c;
    buff_a = (float)NUM2DBL(alpha);
    buff_b = (float)NUM2DBL(beta);
    buff_c = (float)NUM2DBL(gamma);
    a = &buff_a;
    b = &buff_b;
    c = &buff_c;
  }
  else { // CV_ARRAY
    if ((RARRAY_LEN(alpha) != length) ||
	(RARRAY_LEN(beta) != length) ||
	(RARRAY_LEN(gamma) != length))
      rb_raise(rb_eArgError, "alpha, beta, gamma should be same size of points");
    a = ALLOCA_N(float, length);
    b = ALLOCA_N(float, length);
    c = ALLOCA_N(float, length);
    for (i = 0; i < length; ++i) {
      a[i] = (float)NUM2DBL(RARRAY_PTR(alpha)[i]);
      b[i] = (float)NUM2DBL(RARRAY_PTR(beta)[i]);
      c[i] = (float)NUM2DBL(RARRAY_PTR(gamma)[i]);
    }
  }
  CvSize win = VALUE_TO_CVSIZE(window);
  CvTermCriteria tc = VALUE_TO_CVTERMCRITERIA(criteria);
  try {
    cvSnakeImage(cvGetImage(CVARR(self), &stub), pointset, length,
		 a, b, c, coeff, win, tc, IF_BOOL(calc_gradient, 1, 0, 1));
  }
  catch (cv::Exception& e) {
    if (pointset != NULL)
      cvFree(&pointset);
    raise_cverror(e);
  }
  VALUE result = rb_ary_new2(length);
  for (i = 0; i < length; ++i)
    rb_ary_push(result, cCvPoint::new_object(pointset[i]));
  cvFree(&pointset);
  
  return result;
}

#sobel(xorder, yorder, aperture_size = 3) ⇒ CvMat

Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator.

Parameters:

  • xorder (Integer)

    Order of the derivative x.

  • yorder (Integer)

    Order of the derivative y.

  • aperture_size (Integer)

    Size of the extended Sobel kernel; it must be 1, 3, 5, or 7.

Returns:

  • (CvMat)

    Output image.



3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
# File 'ext/opencv/cvmat.cpp', line 3322

VALUE
rb_sobel(int argc, VALUE *argv, VALUE self)
{
  VALUE xorder, yorder, aperture_size, dest;
  if (rb_scan_args(argc, argv, "21", &xorder, &yorder, &aperture_size) < 3)
    aperture_size = INT2FIX(3);
  CvMat* self_ptr = CVMAT(self);
  switch(CV_MAT_DEPTH(self_ptr->type)) {
  case CV_8U:
    dest = new_mat_kind_object(cvGetSize(self_ptr), self, CV_16S, 1);
    break;
  case CV_32F:
    dest = new_mat_kind_object(cvGetSize(self_ptr), self, CV_32F, 1);
    break;
  default:
    rb_raise(rb_eArgError, "source depth should be CV_8U or CV_32F.");
    break;
  }

  try {
    cvSobel(self_ptr, CVARR(dest), NUM2INT(xorder), NUM2INT(yorder), NUM2INT(aperture_size));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#splitArray<CvMat>

Divides a multi-channel array into several single-channel arrays.

Examples:

img = CvMat.new(640, 480, CV_8U, 3) #=> 3-channel image
a = img.split                       #=> [img-ch1, img-ch2, img-ch3]

Returns:

  • (Array<CvMat>)

    Array of single-channel arrays

See Also:



1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
# File 'ext/opencv/cvmat.cpp', line 1410

VALUE
rb_split(VALUE self)
{
  CvArr* self_ptr = CVARR(self);
  int type = cvGetElemType(self_ptr);
  int depth = CV_MAT_DEPTH(type), channel = CV_MAT_CN(type);
  VALUE dest = rb_ary_new2(channel);
  try {
    CvArr *dest_ptr[] = { NULL, NULL, NULL, NULL };
    CvSize size = cvGetSize(self_ptr);
    for (int i = 0; i < channel; ++i) {
      VALUE tmp = new_mat_kind_object(size, self, depth, 1);
      rb_ary_store(dest, i, tmp);
      dest_ptr[i] = CVARR(tmp);
    }
    cvSplit(self_ptr, dest_ptr[0], dest_ptr[1], dest_ptr[2], dest_ptr[3]);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return dest;
}

#square?Boolean

Returns whether the matrix is a square.

Returns:

  • (Boolean)

    If width = height, returns true. if not, returns false.



658
659
660
661
662
663
# File 'ext/opencv/cvmat.cpp', line 658

VALUE
rb_square_q(VALUE self)
{
  CvMat *mat = CVMAT(self);
  return mat->width == mat->height ? Qtrue : Qfalse;
}

#sub(val, mask = nil) ⇒ CvMat Also known as: -

Calculates the per-element difference between two arrays or array and a scalar.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to subtract

  • mask (CvMat)

    Optional operation mask, 8-bit single channel array, that specifies elements of the destination array to be changed.

Returns:

  • (CvMat)

    Result array



1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
# File 'ext/opencv/cvmat.cpp', line 1654

VALUE
rb_sub(int argc, VALUE *argv, VALUE self)
{
  VALUE val, mask, dest;
  rb_scan_args(argc, argv, "11", &val, &mask);
  dest = copy(self);
  try {
    if (rb_obj_is_kind_of(val, rb_klass))
      cvSub(CVARR(self), CVARR(val), CVARR(dest), MASK(mask));
    else
      cvSubS(CVARR(self), VALUE_TO_CVSCALAR(val), CVARR(dest), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#sub_rect(rect) ⇒ CvMat #sub_rect(topleft, size) ⇒ CvMat #sub_rect(x, y, width, height) ⇒ CvMat Also known as: subrect

Returns matrix corresponding to the rectangular sub-array of input image or matrix

Overloads:

  • #sub_rect(rect) ⇒ CvMat

    Parameters:

    • rect (CvRect)

      Zero-based coordinates of the rectangle of interest.

  • #sub_rect(topleft, size) ⇒ CvMat

    Parameters:

    • topleft (CvPoint)

      Top-left coordinates of the rectangle of interest

    • size (CvSize)

      Size of the rectangle of interest

  • #sub_rect(x, y, width, height) ⇒ CvMat

    Parameters:

    • x (Integer)

      X-coordinate of the rectangle of interest

    • y (Integer)

      Y-coordinate of the rectangle of interest

    • width (Integer)

      Width of the rectangle of interest

    • height (Integer)

      Height of the rectangle of interest

Returns:

  • (CvMat)

    Sub-array of matrix



706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'ext/opencv/cvmat.cpp', line 706

VALUE
rb_sub_rect(VALUE self, VALUE args)
{
  CvRect area;
  CvPoint topleft;
  CvSize size;
  switch(RARRAY_LEN(args)) {
  case 1:
    area = VALUE_TO_CVRECT(RARRAY_PTR(args)[0]);
    break;
  case 2:
    topleft = VALUE_TO_CVPOINT(RARRAY_PTR(args)[0]);
    size = VALUE_TO_CVSIZE(RARRAY_PTR(args)[1]);
    area.x = topleft.x;
    area.y = topleft.y;
    area.width = size.width;
    area.height = size.height;
    break;
  case 4:
    area.x = NUM2INT(RARRAY_PTR(args)[0]);
    area.y = NUM2INT(RARRAY_PTR(args)[1]);
    area.width = NUM2INT(RARRAY_PTR(args)[2]);
    area.height = NUM2INT(RARRAY_PTR(args)[3]);
    break;
  default:
    rb_raise(rb_eArgError, "wrong number of arguments (%ld of 1 or 2 or 4)", RARRAY_LEN(args));
  }

  CvMat* mat = NULL;
  try {
    mat = cvGetSubRect(CVARR(self), RB_CVALLOC(CvMat), area);
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return DEPEND_OBJECT(rb_klass, mat, self);
}

#subspace_project(w, mean) ⇒ Object



5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
# File 'ext/opencv/cvmat.cpp', line 5704

VALUE
rb_subspace_project(VALUE self, VALUE w, VALUE mean)
{
  VALUE projection;
  try {
    cv::Mat w_mat(CVMAT_WITH_CHECK(w));
    cv::Mat mean_mat(CVMAT_WITH_CHECK(mean));
    cv::Mat self_mat(CVMAT(self));
    cv::Mat pmat = cv::subspaceProject(w_mat, mean_mat, self_mat);
    projection = new_object(pmat.rows, pmat.cols, pmat.type());
    CvMat tmp = pmat;
    cvCopy(&tmp, CVMAT(projection));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return projection;
}

#subspace_reconstruct(w, mean) ⇒ Object



5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
# File 'ext/opencv/cvmat.cpp', line 5728

VALUE
rb_subspace_reconstruct(VALUE self, VALUE w, VALUE mean)
{
  VALUE result;
  try {
    cv::Mat w_mat(CVMAT_WITH_CHECK(w));
    cv::Mat mean_mat(CVMAT_WITH_CHECK(mean));
    cv::Mat self_mat(CVMAT(self));
    cv::Mat rmat = cv::subspaceReconstruct(w_mat, mean_mat, self_mat);
    result = new_object(rmat.rows, rmat.cols, rmat.type());
    CvMat tmp = rmat;
    cvCopy(&tmp, CVMAT(result));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return result;
}

#sumCvScalar

Calculates the sum of array elements.

Returns:

  • (CvScalar)

    The sum of array elements.



2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
# File 'ext/opencv/cvmat.cpp', line 2171

VALUE
rb_sum(VALUE self)
{
  CvScalar sum;
  try {
    sum = cvSum(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return cCvScalar::new_object(sum);
}

#svd(flag = 0) ⇒ Array<CvMat>

Performs SVD of a matrix

Parameters:

  • flag (Integer)

    Operation flags.

    • CV_SVD_MODIFY_A - Use the algorithm to modify the decomposed matrix. It can save space and speed up processing.

    • CV_SVD_U_T - Indicate that only a vector of singular values w is to be computed, while u and v will be set to empty matrices.

    • CV_SVD_V_T - When the matrix is not square, by default the algorithm produces u and v matrices of sufficiently large size for the further A reconstruction. If, however, CV_SVD_V_T flag is specified, u and v will be full-size square orthogonal matrices.

Returns:

  • (Array<CvMat>)

    Array of the computed values [w, u, v], where

    • w - Computed singular values

    • u - Computed left singular vectors

    • v - Computed right singular vectors



2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
# File 'ext/opencv/cvmat.cpp', line 2594

VALUE
rb_svd(int argc, VALUE *argv, VALUE self)
{
  VALUE _flag = Qnil;
  int flag = 0;
  if (rb_scan_args(argc, argv, "01", &_flag) > 0) {
    flag = NUM2INT(_flag);
  }

  CvMat* self_ptr = CVMAT(self);
  VALUE w = new_mat_kind_object(cvSize(self_ptr->cols, self_ptr->rows), self);
  
  int rows = 0;
  int cols = 0;
  if (flag & CV_SVD_U_T) {
    rows = MIN(self_ptr->rows, self_ptr->cols);
    cols = self_ptr->rows;
  }
  else {
    rows = self_ptr->rows;
    cols = MIN(self_ptr->rows, self_ptr->cols);
  }
  VALUE u = new_mat_kind_object(cvSize(cols, rows), self);

  if (flag & CV_SVD_V_T) {
    rows = MIN(self_ptr->rows, self_ptr->cols);
    cols = self_ptr->cols;
  }
  else {
    rows = self_ptr->cols;
    cols = MIN(self_ptr->rows, self_ptr->cols);
  }
  VALUE v = new_mat_kind_object(cvSize(cols, rows), self);

  cvSVD(self_ptr, CVARR(w), CVARR(u), CVARR(v), flag);

  return rb_ary_new3(3, w, u, v);
}

#threshold(threshold, max_value, threshold_type) ⇒ CvMat #threshold(threshold, max_value, threshold_type, use_otsu) ⇒ Array<CvMat, Number>

Applies a fixed-level threshold to each array element.

Examples:

mat = CvMat.new(3, 3, CV_8U, 1)
mat.set_data([1, 2, 3, 4, 5, 6, 7, 8, 9])
mat #=> [1, 2, 3,
         4, 5, 6,
         7, 8, 9]
result = mat.threshold(4, 7, CV_THRESH_BINARY)
result #=> [0, 0, 0,
            0, 7, 7,
            7, 7, 7]

Overloads:

  • #threshold(threshold, max_value, threshold_type) ⇒ CvMat

    Returns Output array of the same size and type as self.

    Parameters:

    • threshold (Number)

      Threshold value.

    • max_value (Number)

      Maximum value to use with the CV_THRESH_BINARY and CV_THRESH_BINARY_INV thresholding types.

    • threshold_type (Integer)

      Thresholding type

      • CV_THRESH_BINARY

      • CV_THRESH_BINARY_INV

      • CV_THRESH_TRUNC

      • CV_THRESH_TOZERO

      • CV_THRESH_TOZERO_INV

    Returns:

    • (CvMat)

      Output array of the same size and type as self.

  • #threshold(threshold, max_value, threshold_type, use_otsu) ⇒ Array<CvMat, Number>

    Returns Output array and Otsu’s threshold.

    Parameters:

    • threshold (Number)

      Threshold value.

    • max_value (Number)

      Maximum value to use with the CV_THRESH_BINARY and CV_THRESH_BINARY_INV thresholding types.

    • threshold_type (Integer)

      Thresholding type

      • CV_THRESH_BINARY

      • CV_THRESH_BINARY_INV

      • CV_THRESH_TRUNC

      • CV_THRESH_TOZERO

      • CV_THRESH_TOZERO_INV

    • use_otsu (Boolean)

      Determines the optimal threshold value using the Otsu’s algorithm

    Returns:

    • (Array<CvMat, Number>)

      Output array and Otsu’s threshold.



4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
# File 'ext/opencv/cvmat.cpp', line 4502

VALUE
rb_threshold(int argc, VALUE *argv, VALUE self)
{
  VALUE threshold, max_value, threshold_type, use_otsu;
  rb_scan_args(argc, argv, "31", &threshold, &max_value, &threshold_type, &use_otsu);
  const int INVALID_TYPE = -1;
  int type = CVMETHOD("THRESHOLD_TYPE", threshold_type, INVALID_TYPE);
  if (type == INVALID_TYPE)
    rb_raise(rb_eArgError, "Invalid threshold type.");
  
  return rb_threshold_internal(type, threshold, max_value, use_otsu, self);
}

#to_16sCvMat

Converts the matrix to 16bit signed.

Returns:

  • (CvMat)

    Converted matrix which depth is 16bit signed. The size and channels of the new matrix are same as the source.



594
595
596
597
598
# File 'ext/opencv/cvmat.cpp', line 594

VALUE
rb_to_16s(VALUE self)
{
  return rb_to_X_internal(self, CV_16S);
}

#to_16uCvMat

Converts the matrix to 16bit unsigned.

Returns:

  • (CvMat)

    Converted matrix which depth is 16bit unsigned. The size and channels of the new matrix are same as the source.



582
583
584
585
# File 'ext/opencv/cvmat.cpp', line 582

VALUE rb_to_16u(VALUE self)
{
  return rb_to_X_internal(self, CV_16U);
}

#to_32fCvMat

Converts the matrix to 32bit float.

Returns:

  • (CvMat)

    Converted matrix which depth is 32bit float. The size and channels of the new matrix are same as the source.



620
621
622
623
624
# File 'ext/opencv/cvmat.cpp', line 620

VALUE
rb_to_32f(VALUE self)
{
  return rb_to_X_internal(self, CV_32F);
}

#to_32sCvMat

Converts the matrix to 32bit signed.

Returns:

  • (CvMat)

    Converted matrix which depth is 32bit signed. The size and channels of the new matrix are same as the source.



607
608
609
610
611
# File 'ext/opencv/cvmat.cpp', line 607

VALUE
rb_to_32s(VALUE self)
{
  return rb_to_X_internal(self, CV_32S);
}

#to_64fCvMat

Converts the matrix to 64bit float.

Returns:

  • (CvMat)

    Converted matrix which depth is 64bit float. The size and channels of the new matrix are same as the source.



633
634
635
636
637
# File 'ext/opencv/cvmat.cpp', line 633

VALUE
rb_to_64f(VALUE self)
{
  return rb_to_X_internal(self, CV_64F);
}

#to_8sCvMat

Converts the matrix to 8bit signed.

Returns:

  • (CvMat)

    Converted matrix which depth is 8bit signed. The size and channels of the new matrix are same as the source.



569
570
571
572
573
# File 'ext/opencv/cvmat.cpp', line 569

VALUE
rb_to_8s(VALUE self)
{
  return rb_to_X_internal(self, CV_8S);
}

#to_8uCvMat

Converts the matrix to 8bit unsigned.

Returns:

  • (CvMat)

    Converted matrix which depth is 8bit unsigned. The size and channels of the new matrix are same as the source.



556
557
558
559
560
# File 'ext/opencv/cvmat.cpp', line 556

VALUE
rb_to_8u(VALUE self)
{
  return rb_to_X_internal(self, CV_8U);
}

#to_CvMatCvMat

Converts an object to CvMat

Returns:

  • (CvMat)

    Converted matrix



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'ext/opencv/cvmat.cpp', line 673

VALUE
rb_to_CvMat(VALUE self)
{
  // CvMat#to_CvMat aborts when self's class is CvMat.
  if (CLASS_OF(self) == rb_klass)
    return self;

  CvMat *mat = NULL;
  try {
    mat = cvGetMat(CVARR(self), RB_CVALLOC(CvMat));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return DEPEND_OBJECT(rb_klass, mat, self);
}

#to_IplConvKernel(anchor) ⇒ IplConvKernel

Creates a structuring element from the matrix for morphological operations.

Parameters:

  • anchor (CvPoint)

    Anchor position within the element

Returns:



388
389
390
391
392
393
394
395
396
# File 'ext/opencv/cvmat.cpp', line 388

VALUE
rb_to_IplConvKernel(VALUE self, VALUE anchor)
{
  CvMat *src = CVMAT(self);
  CvPoint p = VALUE_TO_CVPOINT(anchor);
  IplConvKernel *kernel = rb_cvCreateStructuringElementEx(src->cols, src->rows, p.x, p.y,
							  CV_SHAPE_CUSTOM, src->data.i);
  return DEPEND_OBJECT(cIplConvKernel::rb_class(), kernel, self);
}

#to_sString

Returns String representation of the matrix.

Returns:

  • (String)

    String representation of the matrix



337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'ext/opencv/cvmat.cpp', line 337

VALUE
rb_to_s(VALUE self)
{
  const int i = 6;
  VALUE str[i];
  str[0] = rb_str_new2("<%s:%dx%d,depth=%s,channel=%d>");
  str[1] = rb_str_new2(rb_class2name(CLASS_OF(self)));
  str[2] = rb_width(self);
  str[3] = rb_height(self);
  str[4] = rb_depth(self);
  str[5] = rb_channel(self);
  return rb_f_sprintf(i, str);
}

#traceCvScalar

Returns the trace of a matrix.

Returns:



2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
# File 'ext/opencv/cvmat.cpp', line 2467

VALUE
rb_trace(VALUE self)
{
  CvScalar scalar;
  try {
    scalar = cvTrace(CVARR(self));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return cCvScalar::new_object(scalar);
}

#transform(transmat, shiftvec = nil) ⇒ CvMat

Performs the matrix transformation of every array element.

Parameters:

  • transmat (CvMat)

    Transformation 2x2 or 2x3 floating-point matrix.

  • shiftvec (CvMat)

    Optional translation vector.

Returns:

  • (CvMat)

    Transformed array.



2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
# File 'ext/opencv/cvmat.cpp', line 2373

VALUE
rb_transform(int argc, VALUE *argv, VALUE self)
{
  VALUE transmat, shiftvec;
  rb_scan_args(argc, argv, "11", &transmat, &shiftvec);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvTransform(self_ptr, CVARR(dest), CVMAT_WITH_CHECK(transmat),
		NIL_P(shiftvec) ? NULL : CVMAT_WITH_CHECK(shiftvec));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#transposeCvMat Also known as: t

Transposes a matrix.

Returns:

  • (CvMat)

    Transposed matrix.



2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
# File 'ext/opencv/cvmat.cpp', line 2487

VALUE
rb_transpose(VALUE self)
{
  CvMat* self_ptr = CVMAT(self);
  VALUE dest = new_mat_kind_object(cvSize(self_ptr->rows, self_ptr->cols), self);
  try {
    cvTranspose(self_ptr, CVARR(dest));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#vector?Boolean

Returns whether the matrix is a vector.

Returns:

  • (Boolean)

    If width or height of the matrix is 1, returns true. if not, returns false.



645
646
647
648
649
650
# File 'ext/opencv/cvmat.cpp', line 645

VALUE
rb_vector_q(VALUE self)
{
  CvMat *mat = CVMAT(self);
  return (mat->width == 1|| mat->height == 1) ? Qtrue : Qfalse;
}

#warp_affine(map_matrix, flags = CV_INTER_LINEAR|CV_WARP_FILL_OUTLIERS, fillval = 0) ⇒ CvMat

Applies an affine transformation to an image.

Parameters:

  • map_matrix (CvMat)

    2x3 transformation matrix.

  • flags (Integer)

    Combination of interpolation methods (#see resize) and the optional flag WARP_INVERSE_MAP that means that map_matrix is the inverse transformation.

  • fillval (Number, CvScalar)

    Value used in case of a constant border.

Returns:

  • (CvMat)

    Output image that has the size size and the same type as self.



3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
# File 'ext/opencv/cvmat.cpp', line 3791

VALUE
rb_warp_affine(int argc, VALUE *argv, VALUE self)
{
  VALUE map_matrix, flags_val, fill_value;
  VALUE dest = Qnil;
  if (rb_scan_args(argc, argv, "12", &map_matrix, &flags_val, &fill_value) < 3)
    fill_value = INT2FIX(0);
  CvArr* self_ptr = CVARR(self);
  int flags = NIL_P(flags_val) ? (CV_INTER_LINEAR | CV_WARP_FILL_OUTLIERS) : NUM2INT(flags_val);
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvWarpAffine(self_ptr, CVARR(dest), CVMAT_WITH_CHECK(map_matrix),
		 flags, VALUE_TO_CVSCALAR(fill_value));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#warp_perspective(map_matrix, flags = CV_INTER_LINEAR|CV_WARP_FILL_OUTLIERS, fillval = 0) ⇒ CvMat

Applies a perspective transformation to an image.

Parameters:

  • map_matrix (CvMat)

    3x3 transformation matrix.

  • flags (Integer) (defaults to: CV_INTER_LINEAR|CV_WARP_FILL_OUTLIERS)

    Combination of interpolation methods (CV_INTER_LINEAR or CV_INTER_NEAREST) and the optional flag CV_WARP_INVERSE_MAP, that sets map_matrix as the inverse transformation.

  • fillval (Number, CvScalar) (defaults to: 0)

    Value used in case of a constant border.

Returns:

  • (CvMat)

    Output image.



3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
# File 'ext/opencv/cvmat.cpp', line 3940

VALUE
rb_warp_perspective(int argc, VALUE *argv, VALUE self)
{
  VALUE map_matrix, flags_val, option, fillval;
  if (rb_scan_args(argc, argv, "13", &map_matrix, &flags_val, &option, &fillval) < 4)
    fillval = INT2FIX(0);
  CvArr* self_ptr = CVARR(self);
  VALUE dest = Qnil;
  int flags = NIL_P(flags_val) ? (CV_INTER_LINEAR | CV_WARP_FILL_OUTLIERS) : NUM2INT(flags_val);
  try {
    dest = new_mat_kind_object(cvGetSize(self_ptr), self);
    cvWarpPerspective(self_ptr, CVARR(dest), CVMAT_WITH_CHECK(map_matrix),
		      flags, VALUE_TO_CVSCALAR(fillval));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}

#watershed(markers) ⇒ CvMat

Performs a marker-based image segmentation using the watershed algorithm.

Parameters:

  • markers (CvMat)

    Input 32-bit single-channel image of markers. It should have the same size as self

Returns:

  • (CvMat)

    Output image



4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
# File 'ext/opencv/cvmat.cpp', line 4966

VALUE
rb_watershed(VALUE self, VALUE markers)
{
  try {
    cvWatershed(CVARR(self), CVARR_WITH_CHECK(markers));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return markers;
}

#widthInteger Also known as: columns, cols

Returns number of columns of the matrix.

Returns:

  • (Integer)

    Number of columns of the matrix



422
423
424
425
426
# File 'ext/opencv/cvmat.cpp', line 422

VALUE
rb_width(VALUE self)
{
  return INT2NUM(CVMAT(self)->width);
}

#xor(val, mask = nil) ⇒ CvMat Also known as: ^

Calculates the per-element bit-wise “exclusive or” operation on two arrays or an array and a scalar.

Parameters:

  • val (CvMat, CvScalar)

    Array or scalar to calculate bit-wise xor operation.

  • mask (CvMat)

    Optional operation mask, 8-bit single channel array, that specifies elements of the destination array to be changed.

Returns:

  • (CvMat)

    Result array



1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
# File 'ext/opencv/cvmat.cpp', line 1868

VALUE
rb_xor(int argc, VALUE *argv, VALUE self)
{
  VALUE val, mask, dest;
  rb_scan_args(argc, argv, "11", &val, &mask);
  dest = copy(self);
  try {
    if (rb_obj_is_kind_of(val, rb_klass))
      cvXor(CVARR(self), CVARR(val), CVARR(dest), MASK(mask));
    else
      cvXorS(CVARR(self), VALUE_TO_CVSCALAR(val), CVARR(dest), MASK(mask));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  return dest;
}