main.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #include <opencv2/imgproc.hpp>
  2. #include <opencv2/highgui.hpp>
  3. #include <opencv2/opencv.hpp>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <tuple>
  7. #include <iostream>
  8. using namespace cv;
  9. struct comparator{
  10. bool operator() (std::tuple<std::vector<cv::Point>, bool, double> t1,
  11. std::tuple<std::vector<cv::Point>, bool, double> t2) {
  12. return std::get<2>(t1) > std::get<2>(t2);
  13. }
  14. } comparator;
  15. int main(int, char**)
  16. {
  17. // get image
  18. cv::Mat image = cv::imread("C:\\Users\\Sky\\Downloads\\name.png");
  19. cv::Mat grayImg;
  20. // convert to greyscale
  21. cv::cvtColor(image, grayImg, COLOR_BGRA2GRAY);
  22. // cv::Mat canny;
  23. // cv::Canny(grayImg,canny, 120, 255, 3);
  24. // finding threshes
  25. cv::Mat thresh;
  26. cv::threshold(grayImg,thresh, 127, 255, THRESH_BINARY_INV | THRESH_OTSU);
  27. // finding contours
  28. std::vector<std::vector<cv::Point>> contours;
  29. std::vector<cv::Vec4i> hierarchy;
  30. findContours( thresh, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
  31. // finding max contour
  32. std::vector<std::tuple<std::vector<cv::Point>, bool, double>> vec;
  33. for(size_t i = 0; i < contours.size(); ++i){
  34. vec.push_back(std::make_tuple(contours.at(i), cv::isContourConvex(contours.at(i)),cv::contourArea(contours.at(i))));
  35. }
  36. std::sort(vec.begin(), vec.end(), comparator);
  37. std::tuple<std::vector<cv::Point>, bool, double> maxContour;
  38. maxContour = vec.at(0);
  39. // create mask
  40. cv::Mat mask = Mat::zeros(thresh.size(), CV_8U);
  41. for(size_t i = 0; i < contours.size(); ++i){
  42. cv::fillConvexPoly(mask, std::get<0>(vec.at(i)), Scalar(255,0,0),8,0);
  43. }
  44. // cv::fillConvexPoly(mask, std::get<0>(maxContour), Scalar(255,0,0),8,0);
  45. // bitwise
  46. cv::Mat res;
  47. cv::bitwise_and(image, image, res, mask);
  48. // show process
  49. imshow("result", res);
  50. imshow("mask", mask);
  51. imshow("canny", thresh);
  52. imshow("source", image);
  53. // create transparent background
  54. Mat dst;
  55. Mat rgb[3];
  56. split(res,rgb);
  57. Mat rgba[4]={rgb[0],rgb[1],rgb[2], mask};
  58. merge(rgba,4,dst);
  59. // save to file transparent and cropped images
  60. imwrite("C:/Documents/1.png", res);
  61. imwrite("C:/Documents/dst.png",dst);
  62. imwrite("C:/Documents/mask.png",mask);
  63. imwrite("C:/Documents/thresh.png",thresh);
  64. imwrite("C:/Documents/src.png",image);
  65. while (true) {
  66. if (waitKey() == 27) { //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
  67. std::cout << "esc key is pressed by user";
  68. break;
  69. }
  70. }
  71. return 0;
  72. }