在开放 cv 中实现 For 循环

Implementing For loop in open cv?

本文关键字:实现 For 循环 cv      更新时间:2023-10-16

我想在 open cv 中实现类似的循环。由于我是打开cv的新手,我不知道如何进行。任何人都可以给我想法来做到这一点C++

for m=1:10
 for n=1:20
    for l=1:Ns
       for k=1:Ns
            Y(l,k)=image1(m-Ns+l-1,n-Ns+k-1);
            DD(l,k)=image2(m-Ns+l-1,n-Ns+k-1);               
       end
    end  
  e=Y-DD ;     
 end
end

这里的图像 1 和图像 2 的大小为 300*300 像素。Y ,DD,image1,image2 al 是垫子图像。

在OpenCV中,图像可以表示为MatIplImage。您的问题未指定图像的类型。

如果 IplImage:

IplImage *img;
unsigned char *image = (unsigned char*)(img->imageData);
int imageStride = img->widthStep;
pixData = image[xCount + yCount*imageStride];

如果垫子:

Mat img;
unsigned char *image = (unsigned char*)(img.data);
int imageStride = img.step;
pixData = image[xCount + yCount*imageStride];

pixData将在 (xCount, yCount) 中包含该数据。您可以在 for 循环中使用这种理解。

正如您已经知道的逻辑一样,我只提到如何从图像中的特定点访问数据。

OpenCV 中访问 for 循环中像素的最有效方法是:

cv::Mat rgbImage;
cv::Mat grayImage;
for ( int i = 0; i < rgbImage.rows; ++i )
  {
    const uint8_t* rowRgbI = rgbImage.ptr<uint8_t> ( i );
    const uint8_t* rowGrayI = grayImage.ptr<uint8_t> ( i );
    for ( int j = 0; j < rgbImage.cols; ++j )
      {
        uint8_t redChannel = *rowRgbI++;
        uint8_t greenChannel = *rowRgbI++;
        uint8_t blueChannel = *rowRgbI++;
        uint8_t grayChannel = *rowGrayI++
      }
  }

根据您的图像是一个或多个通道,您可以修改上面的代码。

如果要实现窗口滑动,可以执行以下操作:

cv::Mat img;
int windowWidth = 5;
int windowHeight = 5;
for ( int i = 0; i < img.rows - windowHeight; ++i )
  {
    for ( int j = 0; j < img.cols - winddowWidth; ++j )
      {
        // either this
        cv::Mat currentWindow = img(cv::Range(j, i), cv::Range(j + windowWidth, i + windowHeight));
        // perform some operations on the currentWindow
        // or do this
        getRectSubPix(img, cv::Size(windowWidth, windowHeight), cv::Point2f(j, i), currentWindow));
        // perform some operations on the currentWindow
      }
  }

您可以阅读有关getRectSubPix()的更多信息。