首页 > 解决方案 > 无法使用 cimg 访问图像中的像素强度(返回 0)

问题描述

我试图访问 Cimg 像素值以打印出我的鼠标所在的像素强度,以及计算直方图。但是,我从 Cimg 对象中得到了全零。

cimg 图像从内存缓冲区启动,它是 12 位灰度图像,但填充到 16 位以保存在内存中。下面的代码是在一个被多次调用的函数中定义的。我想刷新当前显示中的图像,而不是每次调用该函数时都生成一个新图像。所以 Cimgdisp 是在函数之外定义的。

#include "include\CImg.h"
int main(){
    CImg <unsigned short> image(width,height,1,1);
    CImgDisplay           disp(image);
//showImg() get called multiple times here

}

void showImg(){
    unsigned short* imgPtr = (unsigned short*) (getImagePtr());
    CImg <unsigned short> img(imgPtr,width,height);

    img*=(65535/4095);//Renormalise from 12 bit input to 16bit for better display

    //Display 
    disp->render(img);
    disp->paint();
    img*=(4095/65535);//Normalise back to get corect intensities

    CImg <float> hist(img.histogram(100));
    hist.display_graph(0,3);

    //find mouse position and disp intensity
    mouseX = disp->mouse_x()*width/disp->width();//Rescale the position of the mouse to true position of the image
    mouseY = disp->mouse_y()*height/disp->height();
    if (mouseX>0&mouseY>0){
        PxIntensity = img(mouseX,mouseY,0,0);}
    else {
        PxIntensity = -1;}
}

我检索到的所有强度都为零,直方图也为零。

标签: c++cimg

解决方案


img*=(4095/65535);//Normalise back to get corect intensities是不正确的,如(4095/65535)=0在 C/C++ 中(一个整数除以一个更大的整数)。

也许img*=(4095/65535.);


推荐阅读