1

I would like to crop a cv::Mat. Refer to How to crop a CvMat in OpenCV? , I wrote the following piece of code.

        // I would like to crop around this central point.
        x = 100;
        y = 100;

        int centerOff = 30, size = 61;

        cv::Mat img2 = sourceImage(Rect((int)x-centerOff, (int)y-centerOff, size, size));

        for (int i=0; i<size; i++) {
            for (int j=0; j<size; j++) {
                std::cout << (int)img2.at<uchar>(i, j) << " " << (int)sourceImage.at<uchar>(x-centerOff+i, y-centerOff+j) << "\n"; 
            }
        }

It turns out the output of img2 and sourceImage is different. I would like to know the reason of it.

Community
  • 1
  • 1
choyukchow
  • 41
  • 6
  • what's the type of x and y? – Micka Mar 27 '17 at 05:06
  • The type of x and y is float. – choyukchow Mar 27 '17 at 05:09
  • in your (int)sourceImage.at(x-centerOff+i, y-centerOff+j) you've x and y in the wrong order, but since they're equal it should be no problem. – Micka Mar 27 '17 at 05:09
  • Do you mean that I should put it as (int)sourceImage.at(y-centerOff+j, x-centerOff+i)? – choyukchow Mar 27 '17 at 05:13
  • yes, that would be right for cases where x an y aren't equal. – Micka Mar 27 '17 at 05:14
  • is your image really type uchar or is it cv::Vec3b? – Micka Mar 27 '17 at 05:17
  • 1
    Emmm actually in my code x and y are different, so changing the position of x and y solves my problem. Thanks a lot! It saves my day :) May I know why is it the case? Why it is not Mat.at(x, y)? – choyukchow Mar 27 '17 at 05:20
  • because in mathematics, matrix rows are numbered by the first index. See my interpretation: http://stackoverflow.com/questions/25642532/opencv-pointx-y-represent-column-row-or-row-column/25644503#25644503 – Micka Mar 27 '17 at 05:28
  • Then why I don't need to change img2.at(i, j) to img2.at(j, i)? – choyukchow Mar 27 '17 at 06:43
  • you would have to, if size was split in sizeX and sizeY (which is equal in your sample code). The right way is to use y dimension in the outer loop and x dimension in the inner loop and .at(y,x) – Micka Mar 27 '17 at 06:45

0 Answers0