c++ - opencv图像窗口/imshow

标签 c++ opencv

我刚刚开始使用 Open CV 库,我的第一个代码是一个简单的负变换函数。

#include <stdio.h>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void negative(Mat& input,Mat& output)
{
  int row = input.rows;
  int col = input.cols;
  int x,y;
  uchar *input_data=input.data;
  uchar *output_data= output.data;


  for( x=0;x<row;x++)
    for( y=0;y<col;y++)
      output_data[x*col+y]=255-input_data[x*col+y];

    cout<<x<<y;



}

int main( int argc, char** argv )
{
  Mat image;
  image = imread( argv[1], 1 );

  Mat output=image.clone();

  negative(image,output);

  namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
  imshow( "Display Image", output );

  waitKey(0);

  return 0;
}

我添加了额外的行来检查是否处理了整个图像。我的输出图像面临的问题是负变换仅应用于图像的上半部分。

现在发生的是 x 和 y 的值仅在我按下一个键后显示(即一旦显示图像)

我的问题是为什么在执行函数之前调用窗口?

最佳答案

您代码中的根本问题是您正在读取彩色图像,但您尝试将其处理为灰度图像。因此索引发生变化,真正发生的是您只处理图像的前三分之一(由于 3 channel 格式)。

See opencv imread manual

flags – Specifies color type of the loaded image:
>0 the loaded image is forced to be a 3-channel color image
=0 the loaded image is forced to be grayscale

您已指定 flags=1。

这里有一个方法:

Vec3b v(255, 255, 255);
for(int i=0;i<input.rows;i++) //search for edges
{
    for (int j=0 ;j<input.cols;j++)
    {
        output.at<Vec3b>(i,j) = v - input.at<Vec3b>(i,j);
    }
}

请注意,这里的 Vec3b 是 3 channel 像素值,而 uchar 是 1 channel 值。
要获得更有效的实现,您可以查看 Mat.ptr<Vec3b>(i) .

编辑: 如果您要处理大量图像, 对于像素的一般迭代,最快的方法是:

Vec3b v(255, 255, 255); // or maybe Scalar v(255,255,255) Im not sure
for(int i=0;i<input.rows;i++) //search for edges
{
    Vec3b *p=input.ptr<Vec3b>(i);
    Vec3b *q=output.ptr<Vec3b>(i);
    for (int j=0 ;j<input.cols;j++)
    {
        q[j] = v - p[j];
    }
}

请参阅“The OpenCV Tutorials”——“The efficient way”部分。

关于c++ - opencv图像窗口/imshow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16623353/

相关文章:

c++ - 我可以默认第一个模板参数吗?

c++ - 检查 Makefile 中使用的 g++ 版本

python - opencv python在存在间隙的表中添加网格线

c++ Bag Of Words聚集数组大小问题

c++ - 为什么 erase() 函数如此昂贵?

c++ - C++ Concurrency in action 中关于parallel_accumulate 的困惑

opencv - opencv for tegra(Jetson TK1)是否在下面使用npp和openvx?

python - 为什么我的代码只写最后一个变量?

c++ .h 和 .cpp 文件 - 关于方法

c++ - Sobel 的梯度是什么意思?