以下是将Python代码转换为C++版本的示例:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
// Function to fill holes in the binary image
Mat fillHole(Mat srcBw) {
Mat temp = srcBw.clone();
floodFill(temp, Point(0, 0), Scalar(255));
bitwise_not(temp, temp);
Mat out = srcBw | temp;
return out;
}
// Function to get the regions of interest (ROIs)
vector<Rect> getRoi(Mat im_out, Mat img) {
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(im_out.clone(), contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat image = img.clone();
vector<Rect> roiList;
for (int i = 0; i < contours.size(); ++i) {
double area = contourArea(contours[i]);
if (area < 500)
continue;
Rect roiRect = boundingRect(contours[i]);
// Draw center point
circle(image, Point(roiRect.x + roiRect.width / 2, roiRect.y + roiRect.height / 2), 2, Scalar(0, 255, 0), 2);
// Draw bounding rectangle
rectangle(image, roiRect.tl(), roiRect.br(), Scalar(0, 255, 0), 2);
roiList.push_back(roiRect);
}
return roiList;
}
int main() {
// Load image
Mat img = imread("money.png");
if (img.empty()) {
cout << "Failed to load image" << endl;
return -1;
}
// Preprocessing
Mat im_in, im_th;
cvtColor(img, im_in, COLOR_BGR2GRAY);
threshold(im_in, im_th, 0, 255, THRESH_BINARY | THRESH_OTSU);
// Invert binary image
bitwise_not(im_th, im_th);
// Fill holes in the binary image
Mat im_out = fillHole(im_th);
// Get the regions of interest (ROIs)
vector<Rect> roiList = getRoi(im_out, img);
// Save ROIs
for (int i = 0; i < roiList.size(); ++i) {
Rect roi = roiList[i];
Mat roiImg = img(roi);
stringstream filename;
filename << "money_roi/roi_" << setw(2) << setfill('0') << i << ".jpg";
imwrite(filename.str(), roiImg);
cout << "No." << setw(2) << setfill('0') << i << " Finished!" << endl;
}
// Display images.
imshow("Thresholded Image", im_th);
imwrite("money_connect_binary.jpg", im_th);
imshow("Foreground", img);
imwrite("money_connect_out.jpg", img);
waitKey(0);
destroyAllWindows();
return 0;
}
请注意,这只是一个示例,并且可能需要根据您的环境和需求进行适当的修改和调整。
内容由零声教学AI助手提供,问题来源于学员提问




