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

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.


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.


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.


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.


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


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.

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.


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.


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.


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.


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


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.


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.

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


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.


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.


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.


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.


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.


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


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


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

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.


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

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.


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.


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.

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


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.

Options Hash (params):

  • :scale (Number) — default: 1.0

    Scale factor

  • :shift (Number) — default: 0.0

    Value added to the scaled source array elements


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

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.


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.


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.


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.


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.


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.


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.


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


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.


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.


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


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.


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.


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


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.


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.


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.


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.


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


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


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.


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.

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.


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.

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.


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.

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.


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.

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.


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

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.


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.


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.


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


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.

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.


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.

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.


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.

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.


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.

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.


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

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.

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.


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.


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.


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.


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.


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.

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.


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.


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.


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.


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.

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.


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.


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.


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.


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.


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

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

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.


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


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.


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.


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.


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.


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.

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.


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.

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.


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.


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.


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.


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

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)
    

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


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.


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.


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.


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)

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.


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.


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.


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.


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.


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.


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

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.


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.


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.


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.

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.


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.

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.


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.


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.


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.


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.


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)


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)


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

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

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.


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.

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.


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.

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.


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.


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.


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

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.


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.


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.


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

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

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


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.


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.


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


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.


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.


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]

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.


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.


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


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.


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


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]

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.


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.


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.


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.


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.


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.


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.


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


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.


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;
}