简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM