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 <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助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?