基于预训练Caffe模型的图像分类项目报错求助(VS+OpenCV3.4.0+C++)
Hey there! I see you're working on a Caffe-based image classification project with OpenCV 3.4.0 in Visual Studio, and you're stuck on two common DNN API errors. Let's fix them one by one:
1. "readNet: Identifier not found"
The readNet function you’re trying to use doesn’t exist in OpenCV 3.4.0 — it was introduced in OpenCV 4.x as a unified function for loading different model formats. In 3.4.0, you need to use the format-specific function for Caffe models.
Solution:
- Replace
readNetwithcv::dnn::readNetFromCaffe(this is the correct function for loading Caffe prototxt and model files in 3.4.0) - Make sure you’ve included the required header:
#include <opencv2/dnn.hpp> - Alternatively, add
using namespace cv::dnn;at the top of your file to avoid typingcv::dnn::every time (just be cautious with namespace pollution as your project grows).
Example correct call:
cv::dnn::Net net = cv::dnn::readNetFromCaffe("deploy.prototxt", "model.caffemodel");
2. "blobFromImage: function does not take 7 arguments"
OpenCV 3.4.0’s blobFromImage has a different parameter signature compared to newer OpenCV versions. The 3.4.0 version of the function looks like this:
cv::Mat blobFromImage( cv::InputArray image, double scalefactor = 1.0, const cv::Size& size = cv::Size(), const cv::Scalar& mean = cv::Scalar(), bool swapRB = false, bool crop = false, int ddepth = CV_32F );
The code you copied is likely written for OpenCV 4.x, which added extra parameters (like resizeKeepAspectRatio) or changed parameter order.
Solution:
Adjust your blobFromImage call to match the 3.4.0 parameter list. For a typical Caffe model (like AlexNet/VGG), a correct preprocessing call would be:
cv::Mat img = cv::imread("input.jpg"); cv::Mat blob = cv::dnn::blobFromImage( img, 1.0, // Scale factor cv::Size(224, 224), // Target size matching your Caffe model cv::Scalar(104, 117, 123), // Mean values for BGR (Caffe uses BGR order) true, // Swap RGB to BGR (OpenCV reads images as BGR) false // Don't crop the image );
Quick Additional Checks
- Double-check your Visual Studio project configuration:
- Ensure Additional Include Directories includes
<your-opencv-path>/includeand<your-opencv-path>/include/opencv2 - Ensure Additional Library Directories includes
<your-opencv-path>/lib - Add the correct DNN library to Linker > Input: use
opencv_dnn340.libfor release mode,opencv_dnn340d.libfor debug mode (oropencv_world340.lib/opencv_world340d.libif using the world package)
- Ensure Additional Include Directories includes
内容的提问来源于stack exchange,提问作者Sanjay Kumar

