树上松果分析出RGB,进行RGB色差运算,通过使用二值化初步分割果实和背景,怎么使用opencv的c++去实现
参考一下,不喜勿喷
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char **argv) {
// 读入原始图像
Mat img = imread("pinecone.png");
if (img.empty()) {
cerr << "Failed to load image!" << endl;
return -1;
}
// 提取RGB通道
vector<Mat> channels;
split(img, channels);
// 计算色差图像
Mat diff1, diff2;
subtract(channels[0], channels[1], diff1); // R - G
subtract(channels[1], channels[2], diff2); // G - B
// 合并色差图像
Mat diff;
addWeighted(diff1, 0.5, diff2, 0.5, 0, diff);
// 二值化分割
Mat binary;
threshold(diff, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
// 显示结果
namedWindow("Original", WINDOW_NORMAL);
namedWindow("Diff", WINDOW_NORMAL);
namedWindow("Binary", WINDOW_NORMAL);
imshow("Original", img);
imshow("Diff", diff);
imshow("Binary", binary);
waitKey(0);
destroyAllWindows();
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat image = imread("tree_with_pine_nuts.jpg");
if (image.empty())
{
cout << "Failed to read image" << endl;
return -1;
}
// 分割图像
Mat gray;
cvtColor(image, gray, COLOR_BGR2GRAY);
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY+THRESH_OTSU);
// 计算色差
Mat color;
cvtColor(binary, color, COLOR_GRAY2BGR);
Mat diff;
absdiff(color, color, diff);
// 显示结果
namedWindow("Pine Nuts", WINDOW_NORMAL);
imshow("Pine Nuts", color);
namedWindow("Difference", WINDOW_NORMAL);
imshow("Difference", diff);
waitKey(0);
return 0;
}