OpenCV contains a LineIterator
.
it handles the math and gives you all the pixel coordinates.
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
int main()
{
cv::Mat canvas { 50, 50, CV_32FC3, cv::Scalar::all(0.2) };
cv::Point pt1 { 10,30 };
cv::Point pt2 { 40,20 };
cv::Vec3f color1 { 0,1,1 }; // yellow
cv::Vec3f color2 { 1,1,0 }; // cyan
// see https://docs.opencv.org/master/dc/dd2/classcv_1_1LineIterator.html
cv::LineIterator it { canvas, pt1, pt2, 8 };
for (int i = 0; i < it.count; ++i, ++it)
{
float alpha = i / (float)(it.count - 1); // 0..1 along the line
cv::Vec3f blended = color1 * (1-alpha) + color2 * (alpha);
canvas.at<cv::Vec3f>(it.pos()) = blended;
}
// show picture
cv::namedWindow("canvas", cv::WINDOW_NORMAL);
cv::resizeWindow("canvas", 500, 500);
cv::imshow("canvas", canvas);
cv::waitKey(-1);
return 0;
}
