Purpose of cvGet2D and cvSet2D?

c, image-processing, opencv

Solution

Short Answer: `cvGet2D()` and `cvSet2D()` are used to get and set elements of a two-dimensional matrix or image, respectively.

Long Answer:

Suppose you create a `CvMat m`:

CvMat* m = cvCreateMat(3, 3, CV_32FC1);
float data[9] = {0, 1, 2, 3,  4, 5, 6, 7, 8};
cvSetData(m, data, m->step);

This creates a matrix which looks like this:

[0.0 1.0 2.0]
[3.0 4.0 5.0]
[6.0 7.0 8.0]

If you want to get the element containing the value `2.0`, you would use `cvGet2D()` to get the element in the first row and third column:

CvScalar scal = cvGet2D(m, 0, 2);    // Rows and columns are zero-indexed

But since this is only a single-channel matrix, only the first element of `scal` contains meaningful data.

double value = scal.data[0];    // Voila! value == 2.0

But now what if you wanted to change the value of that element? Then you would use `cvSet2D()`:

CvScalar new_value = cvScalar(9.0);
cvSet2D(m, 0, 2, new_value);

Then, the data in `m` looks like this:

[0.0 1.0 9.0] <-- note the change
[3.0 4.0 5.0]
[6.0 7.0 8.0]

Problem

What are `cvSet2D` and `cvGet2D` actually doing in OpenCV? Like in the following code to rotate a matrix, I am using `cvGet2D`: ``` CvMat* rot3= cv2DRotationMatrix( center, angle, scale, rot); cv::Mat rot3cpp(rot3); for(int j=0;j<rot3cpp.rows;j++) { for (int i=0;i<rot3cpp.cols;i++) { CvScalar scal = cvGet2D(rot3,j,i); printf("new matrix is %f: \n", rot3cpp.at<float>(j,i)); } } ``` How will use of `cvSet2D` change my code if I add the line: ``` cvSet2D(rot3,i,j,scal); // set the (i,j) pixel value ``` before printing the value? What does "setting (i,j) pixel value" mean?

Original source