实现原理
怀旧色可以通过调整RGB三通道数值实现,具体公式:
功能函数代码
// 怀旧色 cv::Mat Nostalgic(cv::Mat src) { CV_Assert(src.channels() == 3); int row = src.rows; int col = src.cols; cv::Mat temp = src.clone(); for (int i = 0; i < row; ++i) { uchar *s = src.ptr<uchar>(i); uchar *t = temp.ptr<uchar>(i); for (int j = 0; j < col; ++j) { int B = s[3 * j]; int G = s[3 * j + 1]; int R = s[3 * j + 2]; // 怀旧调色 float newB = 0.272f*R + 0.534f*G + 0.131f*B; float newG = 0.349f*R + 0.686f*G + 0.168f*B; float newR = 0.393f*R + 0.769f*G + 0.189f*B; if (newB < 0) newB = 0; if (newB > 255) newB = 255; if (newG < 0) newG = 0; if (newG > 255) newG = 255; if (newR < 0) newR = 0; if (newR > 255) newR = 255; t[3 * j] = (uchar)newB; t[3 * j + 1] = (uchar)newG; t[3 * j + 2] = (uchar)newR; } } return temp; }
C++测试代码
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; cv::Mat Nostalgic(cv::Mat src); int main() { cv::Mat src = imread("test2.jpg"); cv::Mat result1 = Nostalgic(src); cv::Mat gray; cvtColor(src, gray, COLOR_BGR2GRAY); cv::imshow("original", src); cv::imshow("gray", gray); cv::imshow("result", result); waitKey(0); return 0; } // 怀旧色 cv::Mat Nostalgic(cv::Mat src) { CV_Assert(src.channels() == 3); int row = src.rows; int col = src.cols; cv::Mat temp = src.clone(); for (int i = 0; i < row; ++i) { uchar *s = src.ptr<uchar>(i); uchar *t = temp.ptr<uchar>(i); for (int j = 0; j < col; ++j) { int B = s[3 * j]; int G = s[3 * j + 1]; int R = s[3 * j + 2]; // 怀旧调色 float newB = 0.272f*R + 0.534f*G + 0.131f*B; float newG = 0.349f*R + 0.686f*G + 0.168f*B; float newR = 0.393f*R + 0.769f*G + 0.189f*B; if (newB < 0) newB = 0; if (newB > 255) newB = 255; if (newG < 0) newG = 0; if (newG > 255) newG = 255; if (newR < 0) newR = 0; if (newR > 255) newR = 255; t[3 * j] = (uchar)newB; t[3 * j + 1] = (uchar)newG; t[3 * j + 2] = (uchar)newR; } } return temp; }
测试效果
图1 原图
图2 怀旧色滤镜
图3 灰度图
怀旧色滤镜完成,与灰度图相比,有种古典萧瑟的感觉~
如果函数有什么可以改进完善的地方,非常欢迎大家指出,一同进步何乐而不为呢~
如果文章帮助到你了,可以点个赞让我知道,我会很快乐~加油!