OpenCV Error Messages Suck

OpenCV is a powerful image processing library that can make your project much more simple. However, when things go wrong with OpenCV, the errors that are returned are primarily useless without doing some serious digging into their code (which can be tricky in and of itself). I know every case is different, but here are some errors I’ve had, the largely cryptic messages, and how I fixed them.

Note that I’m using OpenCV 2.4.8 on a Macbook Pro with Xcode 5.0.2. I ought to write up some hints on how I got this to happen in the first place, as well…getting OpenCV working with Xcode isn’t really trivial. For now, here’s errors I faced and how I fixed them. My fixes may not be the same as yours, but hopefully they can give some direction if you’re getting the same error message.

I’d be happy to see some similar errors and fixes in the comments, I can always add them to the post itself over time. I intend to update with my own errors as I continue to encounter them. I’m certainly a far, far cry from an OpenCV expert, but if you have other questions please post them, myself or others may be able to help. Hopefully this post can be a good source for lots of fixes. My hope is that this post will appear when OpenCV coders search their error messages on Google, and can get ideas for how to debug.



Function: calibrateCamera

Error Message:
OpenCV Error: Assertion failed (nimages > 0 && nimages == (int) && (!imgPtMat2 || nimages == (int) in collectCalibrationData, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 3164

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp:3164: error: (-215) nimages > 0 && nimages == (int) && (!imgPtMat2 || nimages == (int) in function collectCalibrationData

The objectPoints (or 3D points) and imagePoints (or 2D points) vector of vectors (the first two arguments to the function) are not the same length.

Turns out I had 33 3D point vectors in my objectPoint vector of vectors, and 32 2D point vectors in my imagePoints vector of vectors (which is the correct amount). Adjust loops that fill these values to make sure they’re both 32. Used a print statement to sanity check the values to be accurate.



Function: calibrateCamera

OpenCV Error: Assertion failed (ni >= 0) in collectCalibrationData, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 3169

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp:3169: error: (-215) ni >= 0 in function collectCalibrationData

This one left me confused. It had to do with how I was filling my objectPoints (3D points) vector of vectors. I got this error when I tried to fill it by making a single vector of 3D points accurate, then duplicating that vector once within objectPoints for each image I had. In theory, the error tells you that the image count is 0. I confirmed that objectPoints was the correct length, so this is still a confusing error for me. AKA, I don’t really know the exact problem.

I tried to make the first vector within objectPoints accurate, then used the vector resize function to duplicate that one vector <number of images> times:
objectPoints.resize(imageCount, objectPoints[0]);



Function: undistort

OpenCV Error: Assertion failed ( != in undistort, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/imgproc/src/undistort.cpp, line 173

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/imgproc/src/undistort.cpp:173: error: (-215) != in function undistort

It checks if the source and destination Mats (the first two arguments) are the same; throws this error if they are.

In my case, this meant that, like the destination Mat, the source Mat was empty…I had written a wrong pathname to get the image data I wanted to undistort. I just had to fix this pathname so that the source Mat was a valid (non-empty) Mat.



Function: calibrateCamera

OpenCV Error: One of arguments’ values is out of range (image width and height must be positive) in cvCalibrateCamera2, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 1477

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp:1477: error: (-211) image width and height must be positive in function cvCalibrateCamera2

The image size (the third argument) must have a positive width and height (read: cannot equal 0).

I was doing an experiment to see if the “src” Mat I was repeatedly using in my loops to find chessboard corners in a group of images would behave better for me if .release()’d after every loop iteration. As a result, when I .size()’d it in calibrateCamera, it had a size of 0. I changed the src.size() argument to Size(max_col,max_row).



Function: calibrateCamera, findChessboardCorners, etc

Error: No specific message. When attempting to calibrate a stereo camera pair, I was having the oddest issue: running on my professor’s test images, I got imperfect but decent results. Running on my own, everything seemed totally screwed up. I eventually discovered that, for whatever reason, the chessboard corners on my images were being found in the opposite direction from the ones on the sample images.

Problem: The ordering of the found corners seems to depend on the orientation of the chessboard! In my images, the top left square is black…in the sample images I was provided, the top left square is white. Some googling found that others had seen this phenomena. Apparently this isn’t a consistent thing across the board…but it’s a start.

Fix: Create the objectImages 3D points vector of vectors backwards. In the loop that would create these points normally ascending (each “i” or “j” representing width or height being multiplied by the real-life size of each chessboard square), I needed to create them starting from the highest values and working down to 0’s. Incredibly. Annoying.



Function: calibrateCamera

OpenCV Error: Assertion failed (i < 0) in getMat, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp, line 963

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp:963: error: (-215) i < 0 in function getMat

Arguments rvecs and tvecs are of type Mat.

Make them type vector<Mat>.



Function: calibrateCamera

OpenCV Error: Bad argument (For non-planar calibration rigs the initial intrinsic matrix must be specified) in cvCalibrateCamera2, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 1592

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp:1592: error: (-5) For non-planar calibration rigs the initial intrinsic matrix must be specified in function cvCalibrateCamera2

I’m still not entirely sure what the happenings under the hood are for this problem, but the gist of it is that when you are calibrating the camera (a single camera) with 3D points (this is what is meant by “non-planar calibration rigs.” In other words, the “Z” coordinates in your objectPoints aren’t all equal to zero), there needs to be an initial value for your intrinsic parameters (the intrinsic matrix argument, cameraMatrix).

At first I thought this meant cameraMatrix needed to be initialized in some way, even with zeros or something, but that’s not quite the case…you simply need to use the flag CV_CALIB_USE_INTRINSIC_GUESS in the flags argument of the function call. Note that writing any flags in this argument (it’s the last argument of the function call) will overwrite the default set of flags that would be added if none are specified–this has given me problems in the past.



Function: solvePnP, Rodrigues (the same error applied to both in the same way)

OpenCV Error: Assertion failed (0 <= i && i < (int)vv.size()) in getMat, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp, line 977

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp:977: error: (-215) 0 <= i && i < (int)vv.size() in function getMat

This is essentially the opposite of the “(i < 0)” assertion problem I faced with calibrateCamera; unlike calibrateCamera, solvePnP and Rodrigues only take a single Mat and single vector of Points for the objectPoints, imagePoints, rvecs, and tvecs argument.

Just append an index to each of these arguments (ie, rvecs[0]). You may want to iterate through your entire set of parameters, rather than just analyze them for a single image at a time.



Function: cvtColor

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/imgproc/src/color.cpp, line 3737

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor

The source doesn’t have the right color format that the code (third argument in the function call) indicates it should. In my case, I was attempting to “CV_RGB2GRAY” my Mat image, but I’d already loaded it “CV_LOAD_IMAGE_GRAYSCALE.” I was trying to convert a grayscale image from color to grayscale; so cvtColor expected my source image to be color. This is I believe what is meant by the “scn == 3” thing….somehow saying the source doesn’t have at least 3 color channels.

Ensure that your source image is of the right color type to match the conversion process. In my case I brought in my images (when using imread) in color (code CV_LOAD_IMAGE_COLOR); I could also just bring them in in grayscale and skip the conversion entirely.



Function:, most any function with parameters

In this case, I wasn’t getting an error, which was part of the problem. However, the produced video would cause VLC media player to freeze if I attempted to watch it. The video file I attempted to produce was far too small for a video, as well.

Opening a VideoWriter is sort of complex; you need the proper codex (argument 2, typically of format such as “CV_FOURCC(‘D’, ‘I’, ‘V’, ‘X’)”), and you need the proper flags (the 5th/final argument). Otherwise your video just turns into a mess.

In my case, and I imagine the same is true a good amount of the time, the fix is to leave the 5th argument field (the flags) unfilled. As in, do not put an argument there at all–only have four arguments. Do not put zero. Zero means absolutely no flags; no argument field at all means default flags…and that is likely just fine.



Function: Rect (inside of matchTemplate, though that’s probably irrelevant)

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 Mat, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp, line 323

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp:323: error: (-215) 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 function Mat

The region of interest I was attempting to pull out of an image by using Rect extended beyond the bounds of the original image.

In my case I was using matchTemplate to try to track features, the Rect was intended to narrow the search window. I calculate the corners of the search window beforehand, and added conditionals to this calculation to bring the corner to an acceptable location on the edge (or appropriately spaced from it where necessary) if it attempted to go beyond it.



Function: findFundamentalMat

OpenCV Error: Assertion failed (mtype == type0 || (CV_MAT_CN(mtype) == CV_MAT_CN(type0) && ((1 << type0) & fixedDepthMask) != 0)) in create, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp, line 1486

libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp:1486: error: (-215) mtype == type0 || (CV_MAT_CN(mtype) == CV_MAT_CN(type0) && ((1 << type0) & fixedDepthMask) != 0) in function create

The status matrix that I was using as the final argument to findFundamentalMat  (available because I was using the FM_RANSAC flag) was a vector<int> instead of an OpenCV Mat. Why it is a Mat instead of a simple array is a mystery to me, but a Mat it must be.

Make status a Mat, alter functions that utilize the info in status accordingly.







Filed under Coding, Tech

37 responses to “OpenCV Error Messages Suck

  1. Ignas

    I woud be happy to be able find fixes for all those errors. I made a calibration program, which captures chessboards from webcam live feed, draws lines on found corners. Everything works fine till final calibrateCamera function call….. then I get “Assertion failed (nimages > 0) in calibrateCamera, file /home/ig/Downloads/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 3415 terminate called after throwing an instance of ‘cv::Exception’
    what(): /home/ig/Downloads/opencv-2.4.8/modules/calib3d/src/calibration.cpp:3415: error: (-215) nimages > 0 in function calibrateCamera”.
    It as bit strange that .cpp paths are where they were downloaded/built, but not where actually installed (usr/local/).
    OpenCV 2.4.8 under Ubuntu 12.04, gcc

    • Hey Ignas, I’m guessing you’ve found the solution to your error already? I apologize for not being more quick to respond. It looks like somehow either your objectPoints or imagePoints variable (first and second function arguments, respectively) isn’t getting filled with image data correctly. I believe nimages is “number of images,” so the assertion is failing because there isn’t a greater-than-zero number of images to calibrate.

  2. Judes

    Have you ever resolved the : “Assertion Failed (ni >= 0) in Calibration.cpp line 3173 on OpenCV 2.4.3 function “collectCalibrationData”
    My ObjectPoints and ImagePoints have the same length –> (BoardSize.width * BoardSize.length) * NumberImages !!
    It makes me crazy ^^
    Once, I follow the guide & try do construct by my self ObjectPoint to having capacity = size … But it changes nothing

    • Hey Judes (too easy…),

      “ni” is number of images…one of your image arrays is empty! It’s likely not your object or image points.

      Let me know if you figure it out.

  3. Judes


    Sorry, I don’t understand your answer !
    In the function calibrateCamera, there is no ArrayOfImage in the declaration, isn’t it?
    double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
    distCoeffs, rvecs, tvecs, flags|CV_CALIB_FIX_K4|CV_CALIB_FIX_K5);

    • Ah, sorry about that, you’re right, there technically aren’t any image arrays. I still believe “ni” stands for number of images; at any rate, I do believe it indicates an array of some kind is empty. Perhaps my assumption that it isn’t object- or image- points was wrong.

      • Judes

        Thanks for your Patience !
        Look at this Picture, it’s screenshot from my SPY on Visual

        Agree with you on the fact it’s connected to some number of images but I can’t find it !
        Have you look on the function collectionCalibrationData() in calibration.cpp?
        The “Assertion Failed” come from this function !

      • It does look like everything is in order there. Shoot, I’m stumped! Please let us know if/when you have it figured out!

      • Judes

        Apparently, it came from my configuration ! I upgraded to 2.4.9 with correct Debug & Release config file for project and then it works !!!
        Thanks for all 😉

  4. Amit

    Hi Bhale,
    I have been trying to work this out since last 40 hours, but couldn’t figure out why I OpenCV assertion is failed when callibrateCamera is called. I am getting the same error which you have mentioned on the very first of the list.
    OpenCV Error: Assertion failed (nimages > 0 && nimages == (int) && (!imgPtMat2 || nimages == (int) in collectCalibrationData, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 3164

    I have checked it many times, length of both imagePoints and objectPoints vector are equal. And both arrays are properly filled. I am taking 20 images of 9 x 6 chessboard to calibrate through live camera. pattern is also detected. everything works good but as code reaches at calibrateCamera part , same error is received. I am not sure if I still might be missing something to check at assertion part . Could you please suggest me what else I might be doing wrong or if there is something wrong to check with the code?

    • Hmmm sorry you’re having a tough time with this bug, Amit. I’m guessing you’re sanity checking each factor by printing out values at run time? Make sure to use reliable methods of filling your vector of vectors, too. You’ll notice in one of my bugs, filling the objectPoints vector one seemingly-obvious way actually didn’t work.

      Otherwise I’d say to just do some redundant sanity-checking. Print things out in different ways, make sure to print them out just before the calibrateCamera call, etc.

      Let me know what your solution was, or if there’s other ways I can help.

  5. Amit

    Actually I created a breakpoint just before calibrateCamera and while checking Local variables in debugging mode, I found that all objectPoints and ImagePoints variable are properly filled. Isn’t that reliable way to check values? I don’t know how to attach image in this blog, otherwise I can show you. But I ll also try to check each factor by printing out at run time as you said.

  6. BR

    This pages saved my day several times now. Thank you very much!

  7. Thank you SO MUCH. This page has helped me a lot. You saved me many hours of stupid trial and error.

  8. Ben

    Hey there, I’m getting error:
    OpenCV Error: Assertion failed (i < 0) in getMat, file /opt/local/var/macports/build/_opt_mports_dports_graphics_opencv/opencv/work/opencv-2.4.8/modules/core/src/matrix.cpp, line 963

    But my rvecs and tvecs are the right types. The check seems to be getting called on my objectPoints vector…but according to the for loop it is called from it should always fail. Help??

    • I remember thinking certain loops should always fail like that, but it has been a while since I’ve used OpenCV now. You mentioned your rvecs and tvecs are of the right type; are they properly filled? I don’t remember exactly anymore, but if I recall correctly the i<0 check is essentially ensuring the vectors are vectors, and vectors with proper data.

      I confess though that these are ideas based on a fuzzy recollection of dealing with the errors. Please let me know if you figure it out for others who may face the same problem!

  9. Ah ok, good to know. Thanks for updating us, and glad you solved it.

  10. Liam

    Hi, I’m getting the following error and don’t know why,

    cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp:3193: error: (-215) ni > 0 && ni == ni1 in function collectCalibrationData

    • Hey Liam, it’s been a while since I’ve gotten my hands dirty with OpenCV now, but that function does indicate that either the number of images (ni) is either 0 or negative, or that the number of images doesn’t match up (ni == ni1). Check out my article or other comments about how the number of images can be incorrectly loaded into your vectors. Have you made any progress?

      • Liam

        Thanks what you said and looking at some of the other errors helped, turned out when I was changing my list of image points into an array it was doing it incorrectly, I had a 1 long array containing all the points

  11. For error message:
    “For non-planar calibration rigs the initial intrinsic matrix must be specified”
    Appears to also happen if object z0.
    i.e. just claim your chess board is at z=0, and the problem may go away.

  12. Hi BHale, I have been trying to work this out all this week without succeed. I’m getting the same error that Liam mentioned before but I haven’t found the way to solve it. This is the message that appears:

    OpenCV Error: Assertion failed (ni == ni1) in cv::collectCalibrationData

    Everything seems to be right so I’m losing my mind. I have used the code that appears in the OpenCV documentation:

    Thanks in advance.

    • Hey Jose, sorry you’re stuck! That’s the worst. Unfortunately as I mentioned to Liam, I haven’t been using OpenCV for a long time. Lately I’ve been stuck on a lot of Python, Java, Vivado, etc. bugs of my own. The principles should be the same though. Have you done plenty of assumption checking? Printing out values, especially the length of your two image vectors? Make sure you’re doing this right before you pass them into the function that’s giving you issues. If possible isolate code to home in on the problem, that sort of thing. You could pass us your code and I could take a look at it, maybe some other people who have commented might see it and be able to help.

      Good luck!

      • Hi BHale, thanks for your quick response. I continued debugging and I think that I found something. It seems to be an error in the conversion of vector<vector> to InputArrayOfArrays. I have written the next code to find it out:

        cv::InputArrayOfArrays IMGPOINT = imagePoints; std::cout << (int) << std::endl;
        cv::InputArrayOfArrays OBJPOINT = objectPoints; std::cout << (int) << std::endl;

        for( int i = 0; i < 5; ++i ){
        std::cout << OBJPOINT.getMat(i).checkVector(3, CV_32F) << std::endl;
        std::cout << IMGPOINT.getMat(i).checkVector(2, CV_32F) << std::endl;

        And it printed out:

        When I tend to think that it should print the next:

        However, I have no idea how to fix it 😦

        Thanks in advance!

  13. Oh man that code is practically foreign language to me now, haha!

    First of all, shouldn’t I be seeing a total of 12 lines of printout? The two lengths, and two values from each array iterated 5 times?

    Also, I don’t remember if the image and object points are supposed to match up perfectly, but it does seem like those are some strange numbers you’re getting. Perhaps compare OBJPOINT to objectPoints and IMGPOINT to imagePoints? After you’re sure objectPoints and imagePoints were correct when they were still vectors? I don’t really remember why that conversion is necessary.

    Sorry, not terribly helpful I imagine. Hope you figure it out/update me when you do.

    • Hi BHale,

      You’re right, printout shows 12 lines but I didn’t write all of them because that information added nothing.

      Yes, objectPoints and imagePoints are supposed to match up perfectly, they have to have the same number of vectors and the same number of components for every vector. And yes, I have checked that they’re correct when they are still vectors.

      From what I understand, the problem is that the function calibrateCamera converts this two vectors of vectors internally into InputArrayOfArrays but for some strange reason it does wrong.

      Thank you for your interest!

      • I remember objectP and imageP need to be the same size arrays, but I’m just forgetting enough that it doesn’t make sense to me why the numbers within those arrays would be the same. Anyway.

        Sorry I wasn’t too much help! Let me know if you figure it out.

  14. Hi BHale! I finally solved the problem by rebuilding the libraries with Cmake. I was using OpenCV 3.1 and when I returned to OpenCV 3.0 the error disappeared.

    Thanks for your interest!

  15. Tinashe

    Hi i am getting the error shown below;
    cv2 error: ==
    What could be wrong there?

    • Hey Tinashe, sorry I haven’t kept up on comments here. Did you find a solution to your problem? Let us know if so! I’m afraid I’m quite stale on my OpenCV knowledge at this point.

  16. Hi BHale,
    I’m trying to make opencv detect a smile from a face-detection. I used harrcascade to detect a face and then use my smile detection xml to detect a smile. the thing is sometime i get a random error which i didn’t understand. I would be great if you can help me clarify which is which.

    – libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
    – Segmentation fault: 11
    – OpenCV Error: Assertion failed (0 <= scaleIdx && scaleIdx size()) in getScaleData
    – OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or unsupported array type) in cvGetMat
    – error: (-206) Unrecognized or unsupported array type in function cvGetMat
    Thank you in advance 😛

    • Hi Srettha, sorry for the delayed response. You may have already figured this out (please let us know what the solution was, if so!). I don’t know off the top of my head what the problem is, but looking at the error message, it seems like you may be using a wrong type to represent some data in a function. The first error, the failed assertion, kind of feels like a result of the second error. You can always double check though…as always, it’s a super confusing error message, but it appears the scaleIdx array must be non-zero size and the values must be non-negative. Seems like if the wrong type was passed in this would happen, as well, which is why I wonder if the second error is the real culprit. Good luck! Let me know if you figure it out.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s