Search code examples
matlabopencvmatplotlibimportimporterror

MATLAB — Unable to Import cv2 Library


I'm a beginner at OpenCV, and trying to run an open-source program. http://asrl.utias.utoronto.ca/code/gpusurf/index.html

I currently have the Computer Vision Toolbox OpenCV Interface 20.1.0 installed and Computer Vision Toolbox 9.2.

I cannot run this simple open-source feature matching algorithm without encountering errors.

import cv2
import matplotlib.pyplot as plt
%matplotlib inline

% read images
img1 = cv2.imread('[INSERT PATH #1]');  
img2 = cv2.imread('[INSERT PATH #2]');

img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY);
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY);

%sift
sift = cv2.xfeatures2d.SIFT_create();

keypoints_1, descriptors_1 = sift.detectAndCompute(img1,None);
keypoints_2, descriptors_2 = sift.detectAndCompute(img2,None);

len(keypoints_1), len(keypoints_2)

The following message is returned:

Error: File: Keypoints.m Line: 1 Column: 8
The import statement 'import cv2' cannot be found or cannot be imported. Imported names must end with '.*' or be
fully qualified.

However, when I remove Line 1, I instead get the following error.

Error: File: Keypoints.m Line: 2 Column: 8
The import statement 'import matplotlib.pyplot' cannot be found or cannot be imported. Imported names must end
with '.*' or be fully qualified.

Finally, following the error message only results in a sequence of further errors from the cv2 library. Any ideas?


Solution

  • That's because the code you've used isn't MATLAB code, it's python code.

    As per the website you've linked:

    From within Matlab

    The parallel implementation coded in Matlab can be run by using the surf_find_keypoints() function. The output keypoints can be sorted by strength using surf_best_n_keypoints(), and plotted using surf_plot_keypoints().

    Check that you've downloaded the correct files and try again.

    Furthermore, the Matlab OpenCV Interface is designed to integrate C++ OpenCV code, not python. Documentations here.