【问题标题】:OpenCV: draw line with gradient colorOpenCV:用渐变颜色画线
【发布时间】:2021-06-18 00:10:33
【问题描述】:

假设,我有两个不同颜色的点。如何使用 OpenCV(无论是 python 还是 c++)在它们之间画线,以便线条的颜色从一种颜色渐变到另一种颜色?看来,用 OpenCV 不容易做到,但如果有人知道一个简单的解决方案,请帮助我)

谢谢。

【问题讨论】:

    标签: opencv


    【解决方案1】:

    OpenCV 包含一个LineIterator

    它处理数学并为您提供所有像素坐标。

    #include <string>
    #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;
    }
    

    【讨论】:

      【解决方案2】:

      一个简单的解决方案是生成中间点并在它们之间绘制更小的线,每条线都有以下渐变阴影。类似于以下的代码可能会完成这项工作:

      past_center = intermediate_points[0]
      for i, point in enumerate(intermediate_points, start=1):
              color_val = int(np.sqrt(64 / float(i + 1)) * 2)
              if color_val < 1:
                  color_val = 0                              
              cv2.line(frame, (int(past_point[0]), int(past_point[1])), (int(point[0]), int(point[1])), (color_val, color_val, color_val), thickness)
              past_point = point
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-09
        • 1970-01-01
        • 2015-07-13
        • 1970-01-01
        相关资源
        最近更新 更多