Last active
October 10, 2021 07:21
-
-
Save scottrogowski/1b9aa327c1b571354224 to your computer and use it in GitHub Desktop.
Add a gradient to an image using c++ and opencv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
To compile: | |
$ g++ gradient_adder.cpp -lm -lopencv_core -lopencv_highgui -lopencv_imgproc -o gradient_adder | |
To run: | |
$ ./gradient_adder non_grad_image.png | |
This will take a black and white input image and seperately apply opposite up/down | |
gradients to the white and the black portions | |
*/ | |
#include <iostream> | |
#include <opencv2/core/core.hpp> | |
#include <opencv2/highgui/highgui.hpp> | |
using namespace std; | |
using namespace cv; | |
#define FROM_GRAD_BLACK 10 | |
#define TO_GRAD_BLACK 35 | |
#define FROM_GRAD_WHITE 10 | |
#define TO_GRAD_WHITE 60 | |
#define BLACK_WHITE_CUTOFF 128 | |
int main(int argc, char* argv[]) { | |
Mat img = imread(argv[1], 0); | |
for (int j=0; j<img.rows; j++) { | |
int black_grad = FROM_GRAD_BLACK + ((TO_GRAD_BLACK - FROM_GRAD_BLACK) * j/img.rows); | |
int white_grad = FROM_GRAD_WHITE + ((TO_GRAD_WHITE - FROM_GRAD_WHITE) * j/img.rows); | |
for (int i=0; i<img.cols; i++) { | |
int pixel_val = img.at<uchar>(j, i); | |
if (pixel_val < BLACK_WHITE_CUTOFF) { | |
img.at<uchar>(j, i) = pixel_val + black_grad; | |
} | |
else { | |
img.at<uchar>(j, i) = pixel_val - white_grad; | |
} | |
} | |
} | |
string out_filename = "gradient.png"; | |
imwrite(out_filename, img); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment