web123456

opencv removes small areas of connected areas

  • #include "opencv.hpp"

  • #include "iostream"

  • using namespace std;

  • using namespace cv;

  •  
  • int main()

  • {

  • Mat srcImage, grayImage, dstImage,imgHSVMask;

  • int size = 800; //area factor

  • //srcImage = imread("");

  • /*imshow("original image", srcImage).

  • cvtColor(srcImage, grayImage, COLOR_RGB2GRAY);

  • threshold(grayImage, dstImage, 100, 255, THRESH_BINARY);

  • imshow("binary image", dstImage);*/

  •  
  • Mat img = imread("");

  • cvtColor(img, grayImage, COLOR_RGB2GRAY);

  • threshold(grayImage, imgHSVMask, 100, 255, THRESH_BINARY);

  • //imshow("Original image", imgHSVMask);

  •  
  • Mat element = getStructuringElement(MORPH_RECT, Size(3, 3)); // for the highlighted section

  • erode(imgHSVMask, imgHSVMask, element);

  • imshow("Corrosion", imgHSVMask);

  •  
  • // Extraction of connected areas and elimination of small connected areas

  • vector<vector<Point>> contours; //container for binary image contours

  • vector<Vec4i> hierarchy; //4 int vectors representing the index numbers of the back, front, parent, and child, respectively

  • findContours(imgHSVMask, contours, hierarchy,RETR_LIST, CHAIN_APPROX_NONE); // detect all contours

  • //(remove_if((), (),[](const vector<Point>& c) {return contourArea(c) < 800; }), ()); // Delete element

  • // Display the image and save it

  • /*(0);

  • drawContours(imgHSVMask, contours, -1, Scalar(255), FILLED);

  • imshow("Processing Map", imgHSVMask); */

  •  
  • Mat ImageContours = Mat::zeros((), CV_8UC1); //plotting

  • Mat ImgContours= Mat::zeros((), CV_8UC1);

  •  
  • vector<vector<Point>>::iterator k; // iterator that accesses container data

  •  
  • for (k = (); k ! = ();) // traverse the container, set the area factor

  • {

  • if (contourArea(*k, false) < size)

  • {// Deletes the specified element, returning an iterator pointing to the position of the next element of the deleted element.

  • k = (k);

  • }

  • else

  • ++k;

  • }

  •  
  • //contours[i] represents the ith contour, contours[i].size() represents all pixel points on the ith contour

  • for (int i = 0; i < (); i++)

  • {

  • for (int j = 0; j < contours[i].size(); j++)

  • {

  • //Get the coordinates of the points on the contour.

  • Point P = Point(contours[i][j].x, contours[i][j].y);

  • <uchar>(P) = 255;

  • }

  • drawContours(ImageContours, contours,i, Scalar(255), -1, 8);

  • }

  •  
  • imshow("Contours", ImageContours);

  • imshow("Contour Points Collection", ImgContours);

  • waitKey(0);

  • return 0;

  • }