下面是将给定的Python代码转换为C++函数的示例:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
cv::Mat fillHole(const cv::Mat& srcBw) {
cv::Mat temp = srcBw.clone();
// Floodfill from point (0, 0)
cv::floodFill(temp, cv::Point(0, 0), cv::Scalar(255));
// Invert floodfilled image
temp = ~temp;
cv::imshow("temp", temp);
// Invert floodfilled image
cv::Mat out = srcBw | temp;
return out;
}
void getRoi(const cv::Mat& im_out, const cv::Mat& img, std::vector<cv::Rect>& roi_list) {
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(im_out, contours, hierarchy, cv::RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE);
for (size_t i = 0; i < contours.size(); ++i) {
double area = cv:contourArea(contours[i]);
if (area < 500)
continue;
cv:Rect roi = boundingRect(contours[i]);
roi_list.push_back(roi);
// Draw center point
cv:circle(img, roi.tl() + roi.br() / 2, 2, CV_RGB(0, 255, 0), -1);
// Draw bounding rectangle
cv:rectangle(img, roi.tl(), roi.br(), CV_RGB(0, 255, 0), 2);
// Save ROI image
std:string filename = "money_roi/roi_" + std::to_string(i) + ".jpg";
cv:imwrite(filename, img(roi));
std:cout << "No." << std::setw(2) << std::setfill('0') << i << " Finished! " << std::endl;
}
}
int main() {
cv::Mat img = cv::imread("money.png");
cv::Mat im_in, im_th, im_out;
cv::cvtColor(img, im_in, cv::COLOR_BGR2GRAY);
double otsu_threshold = cv:threshold(im_in, im_th, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
// Foreground is set to white, background is set to black
im_th = ~im_th;
// Call fillHole function
im_out = fillHole(im_th);
std::vector<cv:Rect> roi_list;
// Find ROIs using the connected components method
getRoi(im_out, img, roi_list);
// Display images.
cv:imshow("Thresholded Image", im_th);
cv:imwrite("money_connect_binary.jpg", im_th);
cv:imshow("Foreground", img);
// Save the colorful image
cv::
std:string color_image_filename = "money_connect_color.jpg";
cv2.imwrite(color_image_filename.c_str(), color_image);
return 0;
}
请注意,这只是一个大致的转换示例,可能需要根据您的实际需求进行一些修改和调整。此外,请确保已正确安装OpenCV库并在C++代码中包含相应的头文件。
内容由零声教学AI助手提供,问题来源于学员提问