[Python] OpenCV KNN training - ml_StatModel.train() takes at most 2 arguments (3 given)...

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    I'm attempting to train and test a simple image classifier, using OpenCV's KNN classifier. Here's my current code:

    trainImages = imageDf[[0]].iloc[trainIndecies]
    trainClasses = imageDf[[1]].iloc[trainIndecies]
    testImages = imageDf[[0]].iloc[testIndecies]
    knn = cv.ml.KNearest_create()
    knn.train(trainImages.to_numpy(), cv.ml.ROW_SAMPLE, trainClasses.to_numpy())
    ret, results, neighbours, dist = knn.findNearest(testImages[0], 3)
    print(f"PredictedClass: " + results)


    ImageDf is a pandas DataFrame containing a column of 128x128 images, and a column of class names for the corresponding image. TrainIndecies is a python list containing indices (rows) of the dataframe to use for training, and testIndecies is the same but for test data.

    - trainImages.to_numpy() DataType: object

    - trainImages.to_numpy() shape: (53292, 1)

    - trainClasses.to_numpy() DataType: object

    - trainClasses.to_numpy() shape: (53292, 1)

    - testImages.to_numpy() DataType: object

    - testImages.to_numpy() shape: (13323, 1)


    I'm getting the following error, and I'm uncertain why.

    cv2.error: OpenCV(4.11.0) :-1: error: (-5:Bad argument) in function 'train'
    > Overload resolution failed:
    > - ml_StatModel.train() takes at most 2 arguments (3 given)
    > - samples data type = object is not supported
    > - Expected Ptr<cv::UMat> for argument 'samples'


    I have looked at the OpenCV documentation, as well as examples on the openCV website, and they all pass 3 arguments to ml_StatModel.train(), so i'm not sure why my code is throwing this error.

    Version Numbers:


    • pandas==2.2.3


    • numpy==2.2.3


    • opencv-python==4.11.0.86

    Continue reading...

Compartilhe esta Página