OPENCV顏色檢測——庫函式版本
阿新 • • 發佈:2021-08-30
OPENCV顏色檢測——庫函式版本
這裡的opencv顏色檢測將類裡面的核心處理函式改為了呼叫opencv庫中自帶的cv::threshold函式
程式原始碼
#include <opencv2/opencv.hpp> #include <iostream> class ColorDetector{ private: //允許的最小差距 int maxDist; //目標顏色 cv::Vec3b target; public: //空的建構函式 //在此初始化預設引數 ColorDetector():maxDist(100),target(0,0,0){} //另一種建構函式,使用目標顏色和顏色距離作為引數 ColorDetector(uchar blue,uchar green,uchar red,int maxDist):target(blue,green,red),maxDist(maxDist){} //設定設定顏色差距的閾值 //閾值必須是整數否則為0 void setColorDistanceThreshold(int distance){ if(distance<0) distance = 0; maxDist = distance; } //獲取顏色差距的閾值 int getColorDistanceThreshold() const { return maxDist; } //設定需要檢測的顏色 void setTargetColor(uchar blue,uchar green,uchar red){ //次序為BGR target = cv::Vec3b(blue, green, red); } //設定需要檢測的顏色 void setTargetColor(cv::Vec3b color) { target = color; } //獲取需要檢測的顏色 cv::Vec3b getTargetColor() { return target; } //核心處理函式 cv::Mat process(cv::Mat &image){ cv::Mat output; //計算與目標顏色的距離的絕對值 cv::absdiff(image, cv::Scalar(target), output); //把影象分割進3幅影象 std::vector<cv::Mat> images; cv::split(output, images); //將三個通道相加(這裡可能出現飽和的情況) output = images[0] + images[1] + images[2]; //應用閾值 cv::threshold(output, output, maxDist, 255, cv::THRESH_BINARY_INV); return output; } }; int main(){ ColorDetector cdetect; //讀入影象 cv::Mat image = cv::imread("C:Pictures/Photo/wallhaven-3zw579.jpg"); cv::imshow("image", image); if(image.empty()) return 0; cdetect.setTargetColor(226, 180, 130); cv::namedWindow("result"); cv::Mat result = cdetect.process(image); cv::imshow("result", result); cv::waitKey(0); return 0; }