墨香年少 32 发布于 7月24日 #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; int main() { // 读取图像 Mat image = imread("your_image_path.jpg"); if (image.empty()) { std::cerr << "Error: Could not read the image file." << std::endl; return -1; } // 将图像转换为HSV颜色空间 Mat hsv_image; cvtColor(image, hsv_image, COLOR_BGR2HSV); // 计算直方图 int hbins = 30, sbins = 32; int histSize[] = {hbins, sbins}; float hranges[] = {0, 180}; // hue的范围 float sranges[] = {0, 256}; // saturation的范围 const float* ranges[] = {hranges, sranges}; MatND hist; int channels[] = {0, 1}; calcHist(&hsv_image, 1, channels, Mat(), hist, 2, histSize, ranges, true, false); // 找到直方图中的最大值 double maxVal = 0; Point maxLoc; minMaxLoc(hist, nullptr, &maxVal, nullptr, &maxLoc); // 最大值对应的色调(hue)和饱和度(saturation) int hmax = maxLoc.x; int smax = maxLoc.y; // 转换回BGR颜色空间 Mat dominant_color_hsv = Mat::zeros(1, 1, CV_8UC3); dominant_color_hsv.at<Vec3b>(0, 0) = Vec3b(hmax, smax, 255); // Value为255 Mat dominant_color_bgr; cvtColor(dominant_color_hsv, dominant_color_bgr, COLOR_HSV2BGR); // 提取主要颜色的BGR值 Vec3b main_color = dominant_color_bgr.at<Vec3b>(0, 0); int b = main_color[0]; int g = main_color[1]; int r = main_color[2]; // 输出主要颜色的BGR值 std::cout << "Main color BGR: (" << b << ", " << g << ", " << r << ")" << std::endl; return 0; } 目之所及,皆是回忆,心之所想,皆是过往 分享这篇帖子 链接帖子 分享到其他站点