Background color changes for Opencv image processing contours

  • 2020-06-19 11:06:12
  • OfStack

This article shares the specific code of the background color change outside the Opencv contour for your reference. The specific content is as follows

I learned the simple code by myself, used the contour discovery and extraction in the image, and then drew it out to change the pixels outside the contour

First of all, the header file, write more, useless can be removed


#include <opencv2/core/core.hpp> 
#include<opencv2/highgui/highgui.hpp> 
#include"opencv2/imgproc/imgproc.hpp" 
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp> 

// The namespace 
using namespace cv;
using namespace std;

// Image data name, original image, grayscale image, 2 Value graph, histogram 
Mat src,src_gray,dst . src_equ;
// The statement 1 A function to create a slider 
static void on_trackbar(int, void*);

The main function


int main(int argc, char** argv)
{
  // Read the picture 
  src = imread("D:\\PersonWork\\OpenCV\\program\\picture data\\0400.bmp");

  // To determine whether there is 
  if (!src.data)
  {
    cout << "Image no find,error!" << endl;
  }

  // Gray level transformation 
  cvtColor(src,src_gray, CV_BGR2GRAY);

  // Original image window, display 
  namedWindow(" The original image ", 0);
  imshow(" The original image ", src);

  //2 Graph window 
  namedWindow("2 Value figure ", 0);

  //  slider   
  int nThreshold = 120;
  createTrackbar("graybar", "2 Value figure ", &nThreshold, 255,on_trackbar); 
  on_trackbar(nThreshold, 0);

  waitKey(0);
  destroyWindow(" The original image ");
  destroyWindow("2 Value figure ");
  destroyWindow("result");
  return 0;
}

The callback function


static void on_trackbar(int pos, void*)
{

  //2 threshold 
  threshold(src_gray, dst, pos, 255, CV_THRESH_BINARY);
  imshow("2 Value figure ", dst);

  // The straight square is homogenized 
  equalizeHist(dst, src_equ);

  // Identify outline 
  vector<vector<Point>> contours;
  vector<Vec4i> hierarchy;
  findContours(src_equ, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);    

  // The number of Outlines, but not 
  //int len=contours.size();
  //cout<<len<<endl;

  // Copy the image and traverse each pixel of the image 
  Mat secImg = src_gray.clone();
  const int np =secImg.rows * secImg.channels();
  const int nr = secImg.rows;
  for(int j=0;j<nr;j++){
    uchar *sdata = secImg.ptr<uchar>(j);
    for(int i=0;i<np;i++){

      // Determines if it is on or outside the outline. If it is, changes the pixel to 255 That white , Because what we need here is the outermost contour, so it is contours[0] If anything else is needed, contours[i],i  I could take some other value 
      if (pointPolygonTest(contours[0],Point(i,j),false) != 1)
        sdata[i]=255;
       }   
    }
  }

  //result Windows and display results 
  namedWindow("result",0);
  imshow("result",secImg);

}

Related articles: