問題描述
我正在使用 C++ 和 OpenCV 制作一個函數,該函數將檢測圖像中像素的顏色,確定它所在的顏色范圍,并將其替換為通用顏色.例如,綠色的范圍可以從深綠色到淺綠色,程序會確定它仍然是綠色并用簡單的綠色替換它,從而使輸出圖像看起來非常簡單.一切都已設置,但我無法定義每個范圍的特征,并且很好奇是否有人知道或公式可以根據 BGR 值確定像素的整體顏色.如果沒有,我將不得不做很多實驗并自己制作,但如果已經存在可以節省時間的東西.我已經做了很多研究,但到目前為止還沒有發現任何東西.
I am making a function using C++ and OpenCV that will detect the color of a pixel in an image, determine what color range it is in, and replace it with a generic color. For example, green could range from dark green to light green, the program would determine that its still green and replace it with a simple green, making the output image very simple looking. everything is set up but I'm having trouble defining the characteristics of each range and was curious if anyone knows or a formula that, given BGR values, could determine the overall color of a pixel. If not I'll have to do much experimentation and make it myself, but if something already exists that'd save time. I've done plenty of research and haven't found anything so far.
推薦答案
如果你想讓你的圖像更簡單(即顏色更少),但好看,你有幾個選擇:
If you want to make your image simpler (i.e. with less colors), but good looking, you have a few options:
一個簡單的方法是將圖像除以(整數除法)一個因子
N
,然后乘以一個因子N代碼>.
A simple approach would be to divide (integer division) by a factor
N
the image, and then multiply by a factorN
.
或者您可以使用一些聚類算法(例如此處顯示的 kmeans
或中值切割算法)將圖像劃分為 K
種顏色.
Or you can divide your image into K
colors, using some clustering algorithm such as kmeans
showed here, or median-cut algorithm.
原圖:
減少顏色(量化,N = 64
):
減少顏色(聚集,K = 8
):
代碼量化:
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat3b img = imread("path_to_image");
imshow("Original", img);
uchar N = 64;
img /= N;
img *= N;
imshow("Reduced", img);
waitKey();
return 0;
}
代碼kmeans:
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat3b img = imread("path_to_image");
imshow("Original", img);
// Cluster
int K = 8;
int n = img.rows * img.cols;
Mat data = img.reshape(1, n);
data.convertTo(data, CV_32F);
vector<int> labels;
Mat1f colors;
kmeans(data, K, labels, cv::TermCriteria(), 1, cv::KMEANS_PP_CENTERS, colors);
for (int i = 0; i < n; ++i)
{
data.at<float>(i, 0) = colors(labels[i], 0);
data.at<float>(i, 1) = colors(labels[i], 1);
data.at<float>(i, 2) = colors(labels[i], 2);
}
Mat reduced = data.reshape(3, img.rows);
reduced.convertTo(reduced, CV_8U);
imshow("Reduced", reduced);
waitKey();
return 0;
}
這篇關于是否有公式可以確定給定 BGR 值的整體顏色?(OpenCV 和 C++)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!