Unable to Utilize SURF function in OpenCV after Manual Build

I’m encountering issues with using the SURF algorithm in OpenCV, even after manually building opencv-contrib-python. Following the steps outlined below:

  1. Cloned the repository:
    git clone --recursive GitHub - opencv/opencv-python: Automated CI toolchain to produce precompiled opencv-python, opencv-python-headless, opencv-contrib-python and opencv-contrib-python-headless packages.

  2. Navigated to the opencv-python directory:
    cd opencv-python

  3. Selected the package flavor:
    export ENABLE_CONTRIB=1

  4. Ran pip wheel:
    pip wheel . --verbose

Even though I managed to build it successfully, I’m still unable to use the SURF function and keep getting the error message 'AttributeError: module ‘cv2.cv2’ has no attribute ‘xfeatures2d’.’ I’m reaching out for help to resolve this issue.

don’t build the package yourself. it’s prebuilt. use the existing packages.

you installed opencv-python and opencv-contrib-python side by side, didn’t you?

if you did, that’s the issue.

1 Like

Thank you for your prompt reply. I followed your suggestion and uninstalled both opencv-python and opencv-contrib-python. Then, I reinstalled opencv-contrib-python. However, I’m still encountering the same error. Do you have any further suggestions on how to resolve this issue?

  • don’t build a pip wheel, you dont need it to use cv2
  • ignore the opencv-python github repo
  • download opencv & opencv_contrib repos
  • build with contrib modules & nonfree (!!) flag:
$ cmake -DOPENCV_ENABLE_NONFREE=ON -DOPENCV_EXTRA_MODULES_PATH=<opencv_contrib>/modules <opencv_source_directory>
$ make -j5
$ make install
1 Like

That doesn’t happen with my opencv-contrib-python 4.9

what version do you use? what is the exact python code that causes this exception?

I tried your suggestion, but unfortunately, I’m still encountering the same issue. Specifically, I’m getting an AttributeError: module ‘cv2’ has no attribute ‘xfeatures2d’ when running my code.

I use opencv-contrib-python 4.9.0.80

Code:

import cv2

# Read input image
image_path = '/Users/fommumac/Desktop/surf/NSW01_2024-04-22_09.30.32.png' 
img = cv2.imread(image_path)

# Convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Initialize SURF detector
surf = cv2.xfeatures2d.SURF_create()

# Detect SURF keypoints and descriptors
keypoints, descriptors = surf.detectAndCompute(gray, None)

# Draw keypoints on the input image
img_with_keypoints = cv2.drawKeypoints(img, keypoints, None, (255, 0, 0), 4)

# Display the input image with keypoints
cv2.imshow('SURF Keypoints', img_with_keypoints)
cv2.waitKey(0)
cv2.destroyAllWindows()

please show cmake output from your build attempt

I successfully build cmake file and this’s the output

sorry, but that’s a useless screenshot, it’s truncated, and it does not show, which modules are built or not. (or even if you had contrib repos or not)