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++函数的示例:

  1. #include <opencv2/opencv.hpp>
  2. #include <iostream>
  3. #include <vector>
  4. cv::Mat fillHole(const cv::Mat& srcBw) {
  5. cv::Mat temp = srcBw.clone();
  6. // Floodfill from point (0, 0)
  7. cv::floodFill(temp, cv::Point(0, 0), cv::Scalar(255));
  8. // Invert floodfilled image
  9. temp = ~temp;
  10. cv::imshow("temp", temp);
  11. // Invert floodfilled image
  12. cv::Mat out = srcBw | temp;
  13. return out;
  14. }
  15. void getRoi(const cv::Mat& im_out, const cv::Mat& img, std::vector<cv::Rect>& roi_list) {
  16. std::vector<std::vector<cv::Point>> contours;
  17. std::vector<cv::Vec4i> hierarchy;
  18. cv::findContours(im_out, contours, hierarchy, cv::RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE);
  19. for (size_t i = 0; i < contours.size(); ++i) {
  20. double area = cv:contourArea(contours[i]);
  21. if (area < 500)
  22. continue;
  23. cv:Rect roi = boundingRect(contours[i]);
  24. roi_list.push_back(roi);
  25. // Draw center point
  26. cv:circle(img, roi.tl() + roi.br() / 2, 2, CV_RGB(0, 255, 0), -1);
  27. // Draw bounding rectangle
  28. cv:rectangle(img, roi.tl(), roi.br(), CV_RGB(0, 255, 0), 2);
  29. // Save ROI image
  30. std:string filename = "money_roi/roi_" + std::to_string(i) + ".jpg";
  31. cv:imwrite(filename, img(roi));
  32. std:cout << "No." << std::setw(2) << std::setfill('0') << i << " Finished! " << std::endl;
  33. }
  34. }
  35. int main() {
  36. cv::Mat img = cv::imread("money.png");
  37. cv::Mat im_in, im_th, im_out;
  38. cv::cvtColor(img, im_in, cv::COLOR_BGR2GRAY);
  39. double otsu_threshold = cv:threshold(im_in, im_th, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
  40. // Foreground is set to white, background is set to black
  41. im_th = ~im_th;
  42. // Call fillHole function
  43. im_out = fillHole(im_th);
  44. std::vector<cv:Rect> roi_list;
  45. // Find ROIs using the connected components method
  46. getRoi(im_out, img, roi_list);
  47. // Display images.
  48. cv:imshow("Thresholded Image", im_th);
  49. cv:imwrite("money_connect_binary.jpg", im_th);
  50. cv:imshow("Foreground", img);
  51. // Save the colorful image
  52. cv::
  53. std:string color_image_filename = "money_connect_color.jpg";
  54. cv2.imwrite(color_image_filename.c_str(), color_image);
  55. return 0;
  56. }

请注意,这只是一个大致的转换示例,可能需要根据您的实际需求进行一些修改和调整。此外,请确保已正确安装OpenCV库并在C++代码中包含相应的头文件。


内容由零声教学AI助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?