使用OpenCV3.4+VS2017实现KNN时遇非静态成员引用错误求助
Hey there! Let's sort out that frustrating error you're running into with your KNN implementation.
What's causing this error?
The "A nonstatic member reference must be relative to a specific object" error pops up when you try to call a non-static member function (or access a non-static variable) directly using the class name, instead of using an actual instance (object) of that class.
In OpenCV 3.4's ml module, the KNearest class (the one handling KNN logic) doesn't let you call methods like train() or findNearest() directly on the class itself—you need to create an instance first.
How to fix it
Here's the step-by-step fix tailored to your code:
Create a KNN instance
Before you try to train the model, initialize aKNearestobject using OpenCV's smart pointer:cv::Ptr<cv::ml::KNearest> knn = cv::ml::KNearest::create();This creates a valid instance of the KNN class that you can interact with.
Use the instance to train your model
Instead of callingKNearest::train(...)(which would trigger the error), use the instance you just created:// Make sure trainData is your feature matrix (CV_32F type, correct dimensions) knn->train(trainData, cv::ml::ROW_SAMPLE, trainClasses);trainDatashould be acv::Matwhere each row represents a training sample's features, and it needs to be of typeCV_32F.cv::ml::ROW_SAMPLEtells OpenCV that each row is a separate sample (adjust toCOL_SAMPLEif your data is column-oriented).- Your existing
trainClassesmatrix is the label set for your training data, which looks like you've already set that up correctly.
Use the instance for predictions (if needed)
When you want to classify test samples, again use the instance:cv::Mat results; knn->findNearest(testData, k, results); // k is your chosen number of neighbors
Quick check for your code
Double-check that you're not trying to call any other KNearest methods directly on the class name. All operations should be done through the knn instance you created.
内容的提问来源于stack exchange,提问作者Carlos Hernandez Perez

