【问题标题】:How to assign values already stored in fixed memory to a cimg object如何将已存储在固定内存中的值分配给 cimg 对象
【发布时间】:2013-11-01 15:25:12
【问题描述】:

我正在使用 Cimg 库进行图像处理工作。我有一个由 GPU 返回的数组的指针,我想让 Cimg 对象直接取数组的值。现在,我正在使用 for 循环来完成这项工作,但效率不高。

我现在使用的示例代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "CImg.h"

using namespace std;
using namespace cimg_library;

int main(){
    char pause;
    int width=3; int height=3;//Dimension of the Cimg matrix
    int size = width * height * sizeof(int); // number of bytes in total in arrays
    int *ptr = (int*) malloc(size);

    //Assign the array some example value; 
    for (int m=0;m<width*height;m++){
        *(ptr+m)=m;
    }

    CImg<int> img(width,height,1,1);

    //This is how I assign the value of the array to the Cimg object
    for (int i=0;i<width;i++)
        for (int j=0;j<height;j++)
        {
            img.atXY(i,j)=*(ptr+j*width+i);
        }

        img.save_bmp("img.bmp");
        cout<<"Pause:";
        cin>>pause;
    }
}

我厌倦了这段代码,但它不起作用:

img.begin()=ptr;

谁能帮我消除for循环并提高速度?提前谢谢大家。

【问题讨论】:

    标签: c++ cimg


    【解决方案1】:

    你可以做一些简单的事情:

    img._data = ptr;
    

    但请注意,像素缓冲区中值的顺序可能与输入缓冲区中的值不同,这可能会导致图像看起来很奇怪。

    【讨论】:

    • 你的意思是我可以做 img.data()=ptr 吗?但是,代码无法继续,因为它表明 img.data() 是一个常量指针
    • 不,data() 是 CImg 类的一个方法,它基本上返回字段 CImg&lt;T&gt;::_data。但是如果你愿意,你可以直接修改_data(有点hacky,但这应该可以)。还要注意在对象销毁之前将_data设置为0,否则析构函数会尝试释放你新设置的_data指针。
    【解决方案2】:

    最后我决定切换到opencv。这样,指针就可以很容易地分配给图像垫,然后存储在图像中。

    我还在寻找cimg的解决方案。 cimg的指针不能修改,我觉得有点奇怪。

    【讨论】:

      【解决方案3】:

      来自https://devolio.net/fish2000/cimg-fltkhpp/

      /* Generates a w*h*4 CImg<uchar> image from the given rgb data. */
      static inline cimg_library::CImg<uchar> cimg_from_rgba(
          uchar const* rgb,
          const uint dimw, const uint dimh
      )
      {
          cimg_library::CImg<uchar> res(dimw,dimh,1,4);
      
          uchar *pR = res.data(0,0,0,0),
                *pG = res.data(0,0,0,1),
                *pB = res.data(0,0,0,2),
                *pA = res.data(0,0,0,3);
      
          const uchar *ptrs   = rgb;
      
          for ( uint off = dimw*dimh; off>0; --off )
          {
              *(pR++) = (uchar)*(ptrs++);
              *(pG++) = (uchar)*(ptrs++);
              *(pB++) = (uchar)*(ptrs++);
              *(pA++) = (uchar)*(ptrs++);
          }
      
          return res;
      }
      

      【讨论】:

        【解决方案4】:

        现在有了可以使用指针作为内部存储的构造函数。

        例如

        cimg_library::CImg<unsigned char> img(ptr, 640, 480, 1, 3, true);
        

        将最后一个参数设置为true 很重要,因为它表明指针ptr 应该用作内部存储,而不是从指针复制值。

        更多信息在这里:

        http://cimg.eu/reference/structcimg__library_1_1CImg.html#a24f3b43daa4444b94a973c2c3fff82c5

        【讨论】:

          猜你喜欢
          • 2011-07-14
          • 1970-01-01
          • 1970-01-01
          • 2012-05-21
          • 1970-01-01
          • 2019-11-27
          • 2021-10-27
          • 1970-01-01
          相关资源
          最近更新 更多