C++和opencv实现图像分割(一)

一、目标图片:

C++和opencv实现图像分割(一)_第1张图片

二、分割目的:

检测并分割图中的皮革部分

三、实现思路及步骤:

C++和opencv实现图像分割(一)_第2张图片

将图像转化位HSV色彩域,肉眼能够清晰看见皮革表面轮廓

 

C++和opencv实现图像分割(一)_第3张图片

设置滑动条选取合适HSV上下边界阈值分割皮革轮廓区域

 

只用腐蚀处理去除小噪点,使用多边形逼近画出皮革边界

C++和opencv实现图像分割(一)_第4张图片

 

四、完整代码实例:

#include 
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include 


using namespace std;
using namespace cv;



int m_h_up = 107;
int m_h_down = 90;
int m_s_up = 153;
int m_s_down = 115;
int m_v_up = 255;
int m_v_down = 18;


float EpsilonThd = 0.0008;

void SaveToDxf(vector approx);
void on_mouse(int EVENT, int x, int y, int flags, void* userdata);

int main()
{
	Mat image_source = imread("D:\\photoclub\\1\\bmp\\2.bmp", IMREAD_COLOR);
	if (!image_source.data)
	{
		cout << "图像加载失败" << endl;
		return -1;
	}

	GaussianBlur(image_source, image_source, Size(3, 3), 0, 0);//高斯滤波

	Mat image_hsv, image_result;
	vector hsvSplit;

	cvtColor(image_source, image_hsv, COLOR_BGR2HSV);      //颜色空间转换,输出hsv图像

	split(image_hsv, hsvSplit);      //图像分离三通道,
	equalizeHist(hsvSplit[2], hsvSplit[2]);//直方图均衡化,对比均衡化
	merge(hsvSplit, image_hsv);//合并三通道

	//int spatialRad = 30;  //空间窗口大小
	//int colorRad = 25;   //色彩窗口大小
	//int maxPyrLevel = 2;  //金字塔层数

	inRange(image_hsv, Scalar(m_h_down, m_s_down, m_v_down), Scalar(m_h_up, m_s_up, m_v_up), image_result);       //取出指定颜色区域

	Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(5, 5));
	morphologyEx(image_result, image_result, MORPH_OPEN, kernel, Point(-1, -1));

	vector> contours;        //寻找轮廓
	findContours(image_result, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);

	int imax = 0; //代表最大轮廓的序号
	int imaxcontour = -1; //代表最大轮廓的大小

	for (int i = 0; i < contours.size(); i++)
	{
		if (contourArea(contours[i]) > imaxcontour)
		{
			imax = i;
			imaxcontour = contourArea(contours[i]);
		}
	}

	Mat image_display;
	vector approx;

	image_source.copyTo(image_display);
	approxPolyDP(Mat(contours[imax]), approx, arcLength(Mat(contours[imax]), true)*EpsilonThd, true);      //多边形拟合
	//drawContours(image_display, contours, imax, Scalar(0, 0, 255), 3);
	const Point* p = &approx[0];
	int m = (int)approx.size();

	polylines(image_display, &p, &m, 1, true, Scalar(0, 0, 255), 3);


	//SaveToDxf(approx);

	imshow("HSVDetect", image_display);
	namedWindow("Result", WINDOW_NORMAL);
	imshow("Result", image_result);
	namedWindow("Display", WINDOW_NORMAL);
	imshow("Display", image_display);
	namedWindow("image_hsv", WINDOW_NORMAL);
	imshow("image_hsv", image_hsv);
	imwrite("8.jpg", image_display);
	waitKey(40);


	waitKey();
}

 

 

 

 

你可能感兴趣的:(opencv)