Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract sub-image from image using OpenCV and C++

Tags:

c++

opencv

I'm trying to get a sub-image from a RGB image in openCV and C++. I've seen the other threads on this topic but it didn't worked for me.

This is the code that I use:

Mat src = imread("Images/00011_00025.ppm");
Rect crop(1, 1, 64, 67);
Mat rez = src(crop);

The image a 64x67 dimension, so I don't understand why I get the following error in the console:

Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows)

Any ideas of what is the cause of this error?

like image 765
sixfeet Avatar asked Mar 17 '18 20:03

sixfeet


1 Answers

Rect crop(1, 1, 64, 67);

The rectangles top left corner is at position (1,1) and its size is set to 64x67.

Mat rez = src(crop);

When using this rectangle to crop the image you're running out of bounds, since the rectangle has an offset of one pixel but the same size as the image to crop. You could either manually account for the offset on width and height, or, and this is my preferred solution for cropping, make use of a cv::Range.

With ranges you could define a row and column span to perform cropping:

cv::Range rows(1, 64);
cv::Range cols(1, 67);
Mat rez = src(rows, cols);
like image 183
s1hofmann Avatar answered Sep 30 '22 09:09

s1hofmann