Ask Your Question
1

Cropping of images in c++ vs python

asked 2017-11-28 04:44:43 -0500

charles1208 gravatar image

I got a strange error that I couldn't figure out where i went wrong.. I am trying to port from Python over to C++ the following cropping code:

In Python:

# x, y, w, h refers to the ROI for which the image is to be cropped.
img = cv2.imread('test.jpg')
cropped_img = img[y: y + h, x: x + w]

In C++:

auto img = cv::imread("test.jpg");
auto resized_img = img(cv::Rect(x, y, w, h));

The values used are exactly the same. However the c++ version throws the exception:

OpenCV Error: 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) in cv::Mat::Mat
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
3

answered 2017-11-28 05:09:17 -0500

berak gravatar image

updated 2017-11-28 05:11:40 -0500

there are indeed differences between c++ and python(numpy) code.

numpy will just silently "cut off" overlapping or out-of-bounds regions, while opencv will throw an exception, if parts of your roi are outside.

here's an example (using the opencv logo above):

# python
print(ocv.shape)
(99, 82, 4)

roi = ocv[30:120,22:88] # partly outside
print(roi.shape)
(69, 60, 4)

if you wanted the same behaviour in c++, you would use the intersection of your roi, and the image bounds, like:

// c++
Mat img = ...
Rect bounds(0,0,img.cols,img.rows);
Rect r(22,30,66,90); // partly outside
Mat roi = img( r & bounds ); // cropped to fit image
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2017-11-28 04:37:58 -0500

Seen: 253 times

Last updated: Nov 28 '17