【问题标题】:Magick Pixel data garbled after minify缩小后Magick Pixel数据乱码
【发布时间】:2026-01-13 23:40:01
【问题描述】:

我需要读取任意大小的图像并将它们应用于 GL 纹理。我正在尝试使用 ImageMagick 调整图像大小,以使其适合最大 1024 维纹理。

这是我的代码:

Magick::Image image(filename);
int width = image.columns();
int height = image.rows();
cout << "Image dimensions: " << width << "x" << height << endl;

// resize it to fit a texture
while ( width>1024 || height>1024 ) {
  try {
    image.minify();
  }
  catch (exception &error) {
    cout << "Error minifying: " << error.what() << " Skipping." << endl; 
    return;         
  }
  width = image.columns();
  height = image.rows();
  cout << "  -- minified to: " << width << "x" << height << endl;
}

// transform the pixels to something GL can use
Magick::Pixels view(image);
GLubyte *pixels = (GLubyte*)malloc( sizeof(GLubyte)*width*height*3 );
for ( ssize_t row=0; row<height; row++ ) {
  Magick::PixelPacket *im_pixels = view.get(0,row,width,1);
  for ( ssize_t col=0; col<width; col++ ) {
    *(pixels+(row*width+col)*3+0) = (GLubyte)im_pixels[col].red;
    *(pixels+(row*width+col)*3+1) = (GLubyte)im_pixels[col].green;
    *(pixels+(row*width+col)*3+2) = (GLubyte)im_pixels[col].blue;
  }
}
texPhoto = LoadTexture( pixels, width, height );
free(pixels);

LoadTexure() 的代码如下所示:

GLuint LoadTexture(GLubyte* pixels, GLuint width, GLuint height) {
  GLuint textureId;
  glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
  glGenTextures( 1, &textureId );
  glBindTexture( GL_TEXTURE_2D, textureId );
  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, (unsigned int*)pixels );
  return textureId;
}

除了应用了 image.minify() 之外,所有纹理都工作得很好。一旦缩小,像素基本上只是随机噪声。一定有其他事情发生,我不知道。我可能在 ImageMagick 文档中遗漏了一些关于在我缩小像素数据后我应该做什么来获取像素数据的内容。

调用 minify() 后如何正确获取像素数据?

【问题讨论】:

  • 你试过用 getConst 代替 get 吗?你只需要读取像素。
  • @dlemstra 出于优化原因,这可能是一个好主意,但它对我的问题没有帮助。我怀疑这可能与将其发送到 GLES 纹理有关。

标签: c++ imagemagick opengl-es-2.0


【解决方案1】:

事实证明,问题出在库中,并且与我在 Raspberry Pi 嵌入式系统上运行的环境有关。也许只是重新编译源代码就足够了,但出于我的目的,我决定我还应该将量子大小减少到 8 位,而不是 Magick 的默认值 16。我还为我的场景选择了一些其他配置选项。

基本上可以归结为:

apt-get remove libmagick++-dev
wget http://www.imagemagick.org/download/ImageMagick.tar.gz
tar xvfz ImageMagick.tar.gz
cd IMageMagick-6.8.7-2
./configure --with-quantum-depth=8 --disable-openmp --disable-largefile --without-freetype --without-x
make
make install

然后针对这些库进行编译。我还需要在/usr/lib 中创建指向so 文件的软链接。

【讨论】: