zoukankan      html  css  js  c++  java
  • 颜色空间转换

    #include<opencv2corecore.hpp>
    #include<opencv2imgprocimgproc.hpp>
    #include<opencv2highguihighgui.hpp>
    #include<iostream>
    
    using namespace std;
    using namespace cv;
    
    
    class ColorDetector
    {
    public:
    	ColorDetector():minDist(100)
    	{
    		target[0]=target[1]=target[0]=0;
    	};
    	void setColorDistanceThreshold(int distance)
    	{
    		if(distance<0)
    			distance=0;
    		minDist=distance;
    	};
    	int getColorDistanceThreshold() const
    	{
    	return minDist;
    	};
    	void setTargetColor(unsigned char red,
    	                    unsigned char green,
    						unsigned char blue)
    	{
    		cv::Mat tmp(1,1,CV_8UC3);
    		tmp.at<cv::Vec3b>(0,0)[0]=blue;
    		tmp.at<cv::Vec3b>(0,0)[1]=green;
    		tmp.at<cv::Vec3b>(0,0)[2]=red;
    		cv::cvtColor(tmp,tmp,CV_BGR2Lab);//转换目标到Lab空间
    		target=tmp.at<cv::Vec3b>(0,0);
    	};
    	void setTargetColor(cv::Vec3b color)
    	{
    		target=color;
    	};
    	cv::Vec3b getTargetColor() const
    	{
    		return target;
    	};
    	int getDistance(const cv::Vec3b& color) const
    {
    	return abs(color[0]-target[0])+abs(color[1]-target[1])+abs(color[2]-target[2]);
    };
    	cv::Mat process(const cv::Mat &image);//核心算法,在类外实现
    private:
    	int minDist;
    	cv::Vec3b target;
    	cv::Mat result;
    	cv::Mat converted;
    };
    cv::Mat ColorDetector::process(const cv::Mat &image)
    {
    	result.create(image.rows,image.cols,CV_8U);
    	converted.create(image.rows,image.cols,image.type());
    	cv::cvtColor(image,converted,CV_BGR2Lab);
    	cv::Mat_<cv::Vec3b>::const_iterator it=image.begin<cv::Vec3b>();
    	cv::Mat_<cv::Vec3b>::const_iterator itend=image.end<cv::Vec3b>();
    	cv::Mat_<uchar>::iterator itout=result.begin<uchar>();
    	for(;it!=itend;++it,++itout)
    	{
    		if(getDistance(*it)<minDist)
    		{
    			*itout=255;
    		}
    		else
    		{
    			*itout=0;
    		}
    	}
    	return result;
    }
    int main()
    {
    	ColorDetector cdetect;
    	cv::Mat image=imread("d:/test/opencv/img.jpg");
    	if(!image.data)
    	{
    		cout<<"picture read failure"<<endl;
    		return 0;
    	}
    	cdetect.setTargetColor(130,190,230);
    	cv::namedWindow("result");
    	cv::imshow("result",cdetect.process(image));
    	cv::waitKey();
    	return 0;
    }



  • 相关阅读:
    apue学习笔记(第十五章 进程间通信)
    apue学习笔记(第十四章 高级I/O)
    apue学习笔记(第十三章 守护进程)
    各种仪器销售说明网站
    专业英语分类和查询
    c#网格控件,Excel控件
    sqlite支持linq
    使WebDev.WebServer.exe 当web服务器
    zip压缩文件测试
    c++爬虫子
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5144324.html
Copyright © 2011-2022 走看看