HSV进行图片获取


Mat src;
//归一化图像
Mat bgr;
//HLS图像
Mat hls;
// 相
int hmin = 51;
int hmin_Max = 360;
int hmax = 360;
int hmax_Max = 360;
//亮度
int lmin = 26;
int lmin_Max = 255;
int lmax = 252;
int lmax_Max = 255;
//饱和度
int smin = 85;
int smin_Max = 255;
int smax = 255;
int smax_Max = 255;
//显示原图的窗口
string windowName = "src";
//颜色区间
string dstName = "dst";
Mat dst;//输出图像

void callBack(int, void*)
{
	//输出图像
	dst = Mat::zeros(bgr.size(), CV_32FC3);
	//掩码
	Mat mask;
	inRange(hls, Scalar(hmin, lmin / float(lmin_Max), smin / float(smin_Max)), Scalar(hmax, lmax / float(lmax_Max), smax / float(smax_Max)), mask);
	for (int r = 0; r < bgr.rows; r++)
	{
		for (int c = 0; c < bgr.cols; c++)
		{
			if (mask.at<uchar>(r, c) == 255)
			{
				dst.at<Vec3f>(r, c) = bgr.at<Vec3f>(r, c);
			}
		}
	}
	//输出图像
	imshow(dstName, dst);
	//保存输出图像
	//数据类型转换
	dst.convertTo(dst, CV_8UC3, 255, 0);
	//imwrite("dst.jpg", dst);
}

int main(int argc, char* argv[])
{
	//输入图像
	src = imread("F:/OpenCv/任务/NO4/A.jpg", IMREAD_COLOR);
	Mat clo = src.clone();
	resize(clo, clo, Size(640, 480));
	if (!clo.data || clo.channels() != 3)
		return -1;
	waitKey(0);


	//输入图像灰度值的归一化
	clo.convertTo(bgr, CV_32FC3, 1.0 / 255, 0);
	//颜色空间转换
	cvtColor(bgr, hls, COLOR_BGR2HSV);
	//输出图像
	namedWindow(dstName, WINDOW_GUI_NORMAL);
	namedWindow("Name", WINDOW_GUI_NORMAL);
	// 相
	createTrackbar("hmin", "Name", &hmin, hmin_Max, callBack);
	createTrackbar("hmax", "Name", &hmax, hmax_Max, callBack);
	//亮度
	createTrackbar("lmin", "Name", &lmin, lmin_Max, callBack);
	createTrackbar("lmax", "Name", &lmax, lmax_Max, callBack);
	//饱和度
	createTrackbar("smin", "Name", &smin, smin_Max, callBack);
	createTrackbar("smax", "Name", &smax, smax_Max, callBack);
	callBack(0, 0);
	
	Mat element = getStructuringElement(MORPH_RECT, Size(1, 1));
	morphologyEx(dst, dst, MORPH_OPEN, element);
	erode(dst, dst, element);
	//闭操作 (连接一些连通域)
	Mat element_re = getStructuringElement(MORPH_RECT, Size(1, 1));
	morphologyEx(dst, dst, MORPH_CLOSE, element_re);
	dilate(dst, dst, element_re);
	imshow(" ", dst);

	//imshow(" ", src);
	waitKey(0);
	return 0;
}

HSV进行图片获取

将值代入inrange
HSV进行图片获取

上一篇:外观和样式(04):【参】颜色空间


下一篇:RGB、HSV和HSL颜色空间