C++ opencv4 CNN(卷積神經網路) 範例
C++ opencv4 CNN(卷積神經網路) 範例
資料來源: chatgpt/gemini
chatgpt code
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>
using namespace cv;
using namespace cv::dnn;
using namespace std;
int main()
{
// Load the MNIST dataset - OpenCV can work with pre-trained models.
// For simplicity, this example assumes that you are using a pre-trained model.
// You can use any other CNN architecture if needed.
// Example of loading a pre-trained model (in this case, from TensorFlow or a similar source)
String modelConfiguration = "path_to_model/config.prototxt"; // Replace with your model configuration file
String modelWeights = "path_to_model/weights.caffemodel"; // Replace with your model weights file
// Load the pre-trained model
Net net = readNetFromCaffe(modelConfiguration, modelWeights);
// Check if the network was loaded correctly
if (net.empty()) {
cerr << "Failed to load the network!" << endl;
return -1;
}
// Load an image (for testing, using a sample image from MNIST or another dataset)
Mat img = imread("path_to_sample_image.jpg", IMREAD_GRAYSCALE); // Replace with your image path
if (img.empty()) {
cerr << "Failed to load image!" << endl;
return -1;
}
// Preprocessing: Resize and normalize image
Mat blob = blobFromImage(img, 1.0, Size(28, 28), Scalar(0), true, false);
// Set the input to the network
net.setInput(blob);
// Run forward pass to get the output
Mat output = net.forward();
// Post-process the output to get the classification result
Point classId;
double confidence;
minMaxLoc(output, 0, &confidence, 0, &classId);
// Output the result
cout << "Predicted class: " << classId.x << ", Confidence: " << confidence << endl;
return 0;
}
gemini code
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace cv::dnn;
using namespace std;
int main() {
// 1. 設定模型和類別名稱檔案的路徑
string modelPath = "path/to/your/pretrained_model.pb"; // 替換成你的模型檔案路徑
string classesPath = "path/to/your/synset_words.txt"; // 替換成你的類別名稱檔案路徑
string imagePath = "path/to/your/image.jpg"; // 替換成你想測試的圖像路徑
// 2. 載入類別名稱
vector<string> classes;
ifstream ifs(classesPath.c_str());
string line;
while (getline(ifs, line)) {
classes.push_back(line);
}
// 3. 載入預訓練模型
Net net = readNet(modelPath);
// 檢查模型是否成功載入
if (net.empty()) {
cerr << "Error: Could not load network." << endl;
return -1;
}
// 4. 讀取輸入圖像
Mat frame = imread(imagePath);
if (frame.empty()) {
cerr << "Error: Could not read image." << endl;
return -1;
}
// 5. 創建一個 blob 作為模型的輸入
Mat blob = blobFromImage(frame, 1.0/255.0, Size(224, 224), Scalar(0, 0, 0), true, false);
// 6. 將 blob 設定為網路的輸入
net.setInput(blob);
// 7. 進行前向傳播以獲得輸出
Mat outputs = net.forward();
// 8. 尋找具有最高信心的類別
Mat prob;
Point classIdPoint;
double confidence;
minMaxLoc(outputs.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
int classId = classIdPoint.x;
// 9. 取得預測的類別名稱
string label = classes[classId];
// 10. 在圖像上繪製預測結果
stringstream ss;
ss << fixed << setprecision(2) << confidence * 100;
string text = label + " : " + ss.str() + "%";
putText(frame, text, Point(10, 30), FONT_HERSHEY_SIMPLEX, 0.8, Scalar(0, 255, 0), 2);
// 11. 顯示結果圖像
imshow("CNN Output", frame);
waitKey(0);
destroyAllWindows();
return 0;
}