Color Gradient 根據四個角落的顏色,以雙線性插值生成平滑過渡的漸層影像。四角顏色分別為:左上(NW)、右上(NE)、左下(SW)、右下(SE)。
rNW, gNW, bNW 等 12 個浮點值(0~1 正規化)。(x, y),計算歸一化座標:fx = x / width,fy = y / height。p = 1 - fx,q = 1 - fy。r = p*q*rNW + (1-p)*q*rNE + p*(1-q)*rSW + (1-p)*(1-q)*rSE#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void showImage(const Mat& img, const string& name) {
namedWindow(name, WINDOW_AUTOSIZE);
imshow(name, img);
}
int main() {
int w = 512, h = 512;
Mat dst(h, w, CV_8UC3);
// 四角顏色 (R,G,B) 0~1
float rNW=1.0, gNW=0.0, bNW=0.0; // 紅
float rNE=1.0, gNE=1.0, bNE=0.0; // 黃
float rSW=0.0, gSW=0.0, bSW=1.0; // 藍
float rSE=0.0, gSE=1.0, bSE=0.0; // 綠
for (int y = 0; y < h; ++y) {
float fy = (float)y / h;
float q = 1.0f - fy;
for (int x = 0; x < w; ++x) {
float fx = (float)x / w;
float p = 1.0f - fx;
float r = p*q*rNW + fx*q*rNE + p*fy*rSW + fx*fy*rSE;
float g = p*q*gNW + fx*q*gNE + p*fy*gSW + fx*fy*gSE;
float b = p*q*bNW + fx*q*bNE + p*fy*bSW + fx*fy*bSE;
dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(b * 255);
dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(g * 255);
dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(r * 255);
}
}
showImage(dst, "Bilinear Gradient");
waitKey(0);
return 0;
}
若需更複雜漸層,可:
cv::applyColorMap 配合灰階漸層圖快速生成偽彩色漸層。