【问题标题】:OpenCV: How to iterate each pixel in a specific area of an imageOpenCV:如何迭代图像特定区域中的每个像素
【发布时间】:2016-05-02 03:22:30
【问题描述】:

我有一个用两条平行的绿线标记的图像(见下文)。该图像是在 C++ 中的 OpenCV Mat 中读取的,绿线的斜率及其到图像中心的距离是已知的。

现在我想迭代这两条绿线之间区域中的所有像素。我怎么解决这个问题?如果有人可以给我一个代码示例,这将非常有帮助。

非常感谢。

【问题讨论】:

    标签: c++ opencv pixel


    【解决方案1】:

    斜率的公式如下:

    y = mx + b
    

    既然你有两个,你应该有两个斜率公式:

    y1 = m1x1 + b1
    y2 = m2x2 + b2
    

    m1, m2, b1, b2 应该是已知的。

    您所要做的就是从y1 = 0 和y2 = 0 开始,并在x1 到x2 之间从上到下为每个y1 = y2 迭代。

    示例代码:

    for (int y = 0; y < imageHeight; ++y)
    {
        int x1 = (y - b1) / m1;
        int x2 = (y - b2) / m2;
    
        for (int x = x1; x < x2; ++x)
        {
            // Do something.
        }
    }
    

    【讨论】:

    • 感谢您提供这么好的解决方案。然而,对于每个循环,应计算 x 坐标。我想要一个计算图像矩阵中每个像素的位置偏移的解决方案。
    • 我不太明白,你能解释一下你在找什么吗?
    【解决方案2】:

    你可以使用LineIterator

    看看下面的示例代码

    #include "opencv2/highgui/highgui.hpp"
    #include "opencv2/imgproc/imgproc.hpp"
    #include <iostream>
    
    using namespace std;
    using namespace cv;
    
    int main( int, char** argv )
    {
        Mat src;
        src = imread( argv[1] );
    
        if( src.empty() )
        {
            return -1;
        }
    
        Point pt1 = Point( (src.cols / 5) + (src.cols / 8), src.rows);
        Point pt2 = Point( (src.cols ) - (src.cols / 8), 0);
    
        LineIterator it(src, pt1, pt2, 8);
    
        for(int y = 0; y < it.count; y++, ++it)
        {
            Point it_pos = it.pos();
            for(int x = it_pos.x; x < it_pos.x+(src.cols / 5) & x < src.cols; x++)
            {
                Vec3b & pixel = src.at<Vec3b>(it_pos.y,x);
                pixel = pixel * 1.3;
                pixel[0] = 0;
            }
    
        }
    
        imshow("result", src );
        waitKey(0);
    
        return 0;
    
    }
    

    结果图像(查看编辑历史以更好地了解更改):

    【讨论】:

      猜你喜欢
      • 2011-09-25
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多