opencv图像处理之轮廓外背景颜色改变

来源:互联网 发布:淘宝五心需要多少好评 编辑:程序博客网 时间:2024/05/22 04:56

自行学习弄得简单代码,使用了图像中的轮廓发现以及提取,再绘制出来,改变轮廓外的像素


首先,头文件,写的比较多,没用的可以自己去除

#include <opencv2/core/core.hpp>  #include<opencv2/highgui/highgui.hpp>  #include"opencv2/imgproc/imgproc.hpp"  #include <iostream>#include <fstream>#include <opencv2/opencv.hpp>  //命名空间using namespace cv;using namespace std;

//图片数据名字,原图,灰度图,二值图,直方图Mat src,src_gray,dst,src_equ;//声明一个函数,建立滑动条static void on_trackbar(int, void*);

主函数

int main(int argc, char** argv){    //图片读入    src = imread("D:\\PersonWork\\OpenCV\\program\\picture data\\0400.bmp");    //判断是否存在    if (!src.data)    {        cout << "Image no find,error!" << endl;    }    //灰度转换    cvtColor(src,src_gray, CV_BGR2GRAY);    //原图窗口,显示    namedWindow("原图", 0);    imshow("原图", src);    //二值图窗口    namedWindow("二值图", 0);    // 滑动条        int nThreshold = 120;    createTrackbar("graybar", "二值图", &nThreshold, 255,on_trackbar);     on_trackbar(nThreshold, 0);    waitKey(0);    destroyWindow("原图");    destroyWindow("二值图");    destroyWindow("result");    return 0;}

回调函数

static void on_trackbar(int pos, void*){    //二值化    threshold(src_gray, dst, pos, 255, CV_THRESH_BINARY);    imshow("二值图", dst);    //直方均匀化    equalizeHist(dst, src_equ);     //识别轮廓    vector<vector<Point>> contours;    vector<Vec4i> hierarchy;    findContours(src_equ, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);            //轮廓数量,可没有    //int len=contours.size();    //cout<<len<<endl;    //将图拷贝,进行遍历图片每个像素    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++){            //判断是否在轮廓上或者外面,如果在便将像素变为255,即白色,因为这里需要的是最外轮廓,所以为contours[0],如果还需要别的,contours[i],i 可以取其他值            if (pointPolygonTest(contours[0],Point(i,j),false) != 1)                sdata[i]=255;             }              }    }    //result窗口以及显示结果    namedWindow("result",0);    imshow("result",secImg);}

轮廓数量

原图

二值图

result

如有不足,敬请谅解!

阅读全文
0 0