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;
    }



  • 相关阅读:
    Java基于数据源的数据库访问
    新手接触java
    完成了第一个java
    Mysql服务器相互作用的通讯协议包括TCP/IP,Socket,共享内存,命名管道
    SQL 根据IF判断,SET字段值
    MyBatis SQL 生成方法 增删改查
    JAVA 文件转字节数组转字符串
    Word内容修改,以及转PDF
    SpringBoot编辑代码时不重启服务
    java 图片转换工具
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5144324.html
Copyright © 2011-2022 走看看