软件编程
位置:首页>> 软件编程>> C语言>> Opencv图像处理之轮廓外背景颜色改变

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

作者:hihushine  发布时间:2022-02-17 01:33:34 

标签:opencv,背景,颜色

本文实例为大家分享了Opencv轮廓外背景颜色改变的具体代码,供大家参考,具体内容如下

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

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


#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);

}

来源:https://blog.csdn.net/hihushine/article/details/78267343

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com