Search code examples
pythonnumpyopencv

OpenCV error img is incompatible with cv::Mat


Just realized of a surprising thing when using the following code:

import cv2
import numpy as np

a = np.zeros((720, 1280, 2), dtype=np.uint8)
b = np.zeros((720, 1280), dtype=np.uint8)

cv2.circle(b, (100,100),3,1,-1)   # works
cv2.circle(a[..., 0], (100,100),3,1,-1)  # does not work

Calling exactly same function with exactly same arguments is not working. Is this related with how numpy deals with arrays internally?


Solution

  • I opened an issue on Github and it seems the reason is due to OpenCV cv::Mat and cv::Umat support per-row step, but not per-element step. It means that elements in a row should be compact without holes. a[..., 0] creates array with per-element step. This memory layout cannnot be converted to cv::Mat automatically and the only solution is data copy.

    See https://github.com/opencv/opencv-python/issues/741