目录
1.准备:
创建ColorDetector类
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_OpenCVQtGui.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/types_c.h>
class ColorDector
{
public:
ColorDector() :minDist(100)
{
target[0] = target[1] = target[2] = 0;
}
cv::Mat process(const cv::Mat &image);
int getDistance(const cv::Vec3b &color);
void setColorDistanceThreshold(int distance);
int getColorDistanceThreshold();
void setTargetColor(uchar red, uchar green, uchar blue);
void setTargetColor(cv::Vec3b color);
cv::Vec3b getTargetColor();
private:
int minDist;
cv::Vec3b target;
cv::Mat result;
};
#include "ColorDetector.h"
cv::Mat ColorDector::process(const cv::Mat &image)
{
cv::Mat result;
result.create(image.rows,image.cols,CV_8U);
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 ColorDector::getDistance(const cv::Vec3b &color)
{
return abs(color[0] - target[0])
+ abs(color[1] - target[1])
+ abs(color[2] - target[2]);
}
void ColorDector::setColorDistanceThreshold(int distance)
{
if (distance < 0)
{
distance = 0;
}
minDist = distance;
}
int ColorDector::getColorDistanceThreshold()
{
return minDist;
}
void ColorDector::setTargetColor(uchar red, uchar green, uchar blue)
{
target[2] = red;
target[1] = green;
target[0] = blue;
}
void ColorDector::setTargetColor(cv::Vec3b color)
{
target = color;
}
cv::Vec3b ColorDector::getTargetColor()
{
return target;
}
在处理中添加调用ColorDetector类,进图片处理
void OpenCVQtGui::ColorDetector_clicked()
{
cv::Mat Result = image;
cdetector.setTargetColor(130, 190, 230);
Result = cdetector.process(Result);
cvtColor(Result, Result, CV_BGR2RGB);(切记在图片处理完显示进行调整)
QImage img1 = QImage((const unsigned char*)(Result.data), Result.cols, Result.rows, QImage::Format_RGB888);
ui.label_2->setPixmap(QPixmap::fromImage(img1));
ui.label_2->resize(QSize(img1.width(), img1.height()));
}