OpenCV throws errors after applying numpy transformations

Viewed 45

I've run into a curious error. After applying np.flip, cv2.rectangle is throwing an error. Here's a minimal reproducible example:

image = np.random.choice(255,(50,50,3)).astype(np.uint8)
image_180 = np.flip(image.copy())
x1,y1,x2,y2 = 20,20,30,30
cv2.rectangle(image,(x1,y1),(x2,y2),(0,255,0),1)
cv2.rectangle(image_180,(x1,y1),(x2,y2),(0,255,0),1)

Both image and image_180 are of the type numpy.ndarray, and are of dtype np.uint8. However, the second call to rectangle throws the following error:

TypeError: an integer is required (got type tuple)

Which makes no sense. I'm assuming this is a bug or something with a lazy fix.

2 Answers

Indeed, this error message is very confusing.

According to the official NumPy documentation, np.flip() returns a view of the input array. Presumably, this causes problems for OpenCV.

A simple fix is to pass a deep copy of the returned view, i.e.:

r = cv2.rectangle(image_180.copy(), (x1, y1), (x2, y2), (0, 255, 0), 1)

Strangely enough, cv2.rectangle() does sometimes work with views, e.g.:

r = cv2.rectangle(image[:10], (x1, y1), (x2, y2), (0, 255, 0), 1)

This suggests to me there is some kind of a bug in either NumPy or OpenCV. Either way, using .copy() on your array will fix your issue.

image_180 = np.flip(image.copy())

your code is slightly confused (deep copy position),

below code works for me:

image_180 = np.flip(image).copy()
Related