ZBLOG

import cv2; import numpy as np; # get the front image def fillHole(srcBw): ''' srcBw: 二值图,前景为白色 ''' temp = srcBw.copy() # Floodfill from point (0, 0) cv2.floodFill(temp, None, (0,0), 255) # Invert floodfilled image ...

下面是将给定的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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=11232

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?