Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV: How Do I split an Image?

Tags:

opencv

I would like to split an image which is captured from a webcam into N*N squares, so that I can process those squares separably.

like image 566
Ahmed Saleh Avatar asked Sep 17 '11 14:09

Ahmed Saleh


1 Answers

You need to use a ROI (Region Of Interest) option of OpenCV image structures. In C interface you need a function cvSetImageROI, in C++ it will be operator() of cv::Mat class. Here is a simple C++ sample for processing image by NxN blocks:

cv::Mat img;
capture >> img;

for (int r = 0; r < img.rows; r += N)
    for (int c = 0; c < img.cols; c += N)
    {
        cv::Mat tile = img(cv::Range(r, min(r + N, img.rows)),
                     cv::Range(c, min(c + N, img.cols)));//no data copying here
        //cv::Mat tileCopy = img(cv::Range(r, min(r + N, img.rows)),
                     //cv::Range(c, min(c + N, img.cols))).clone();//with data copying

        //tile can be smaller than NxN if image size is not a factor of N
        your_function_processTile(tile);
    }

C version:

IplImage* img;
CvRect roi;
CvSize size;
int r, c;

size = cvGetSize(img);
for (r = 0; r < size.height; r += N)
    for (c = 0; c < size.width; c += N)
    {
        roi.x = c;
        roi.y = r;
        roi.width = (c + N > size.width) ? (size.width - c) : N;
        roi.height = (r + N > size.height) ? (size.height - r) : N;

        cvSetImageROI(img, roi);

        processTile(img);
    }
cvResetImageROI(img);
like image 172
Andrey Kamaev Avatar answered Oct 22 '22 13:10

Andrey Kamaev