Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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

print(ocv.shape,roi.shape)
(99, 82, 4)

roi = ocv[30:120,22:88]
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:

Mat img = ...
Rect bounds(0,0,img.cols,img.rows);
Rect r(22,30,66,90); // partly outside
Mat roi = img( r & bounds );

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

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

roi = ocv[30:120,22:88]
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 );

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