您的代码有很多事情没有做好。我将尝试列出它们:
namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.
int numFrames = endFrame - startFrame; // Total number of frames
Mat imgArr[100];
第一个问题:如果您的帧数numFrames
大于100
怎么办?这会更安全:
std::vector<Mat> imgVector;
imgVector.reserve(numFrames);
然后在每个新帧上你都有push_back
一个图像。让我们继续。
for(long int FrameNumber = startFrame; FrameNumber < endFrame; FrameNumber++){
fp.seekg( BytesPerFrame*(FrameNumber), std::ios::beg); //Hmmm, when did you compute BytesPerFrame?
char buffer[BytesPerImage]; //This is actually not C++, you probably even got a warning
您应该替换char buffer[BytesPerImage]
为char* buffer = new char[BytesPerImage];
. 您还应该在循环之前预先分配此中间缓冲区,以便您只需分配一次并多次使用它。然后,在循环之后,你释放它:delete[] buffer;
.
fp.read(buffer, BytesPerImage); //This seems fine
short image[512*512]; //What's this?
是什么512
?我可以理解稍后查看您的代码,但您应该在某个地方定义如下内容:
const int MYWIDTH = 512;
const int MYHEIGHT = 512;
const int BYTES_PER_IMAGE = MYWIDTH * MYHEIGHT * 2; //Maybe also the 2 should be a constant named `BYTES_PER_PIXEL`
此外,在这种情况下,让我们使用short* image = new short[MYWIDTH*MYHEIGHT];
. 但是,这不会正常工作:不幸的是,如果您Mat
从外部缓冲区构造 a ,则不会自动管理释放。最好以相反的方式进行:创建您的Mat
,然后将其用作您的缓冲区。它看起来像这样:
Mat img(MYHEIGHT, MYWIDTH, CV_16S); //
short* image = static_cast<short*> img.ptr();
进一步操作的一个问题是可能存在“填充字节”。512x512 图像不太可能,但谁知道呢。请断言以下将是正确的(参见doc):
(img.cols == img.step1() )
然后:
short min = 20000, max=1000;
为什么不max=0
呢?此外,min
可以初始化为 32767,或者更优雅地初始化为std::numeric_limits<short>::max()
( #include <limits.h>
)
for ( int i = 0; i < BytesPerImage; i=i+2 )
{
int a;
a = floor(i/2)+1;
// take first character
image[a] = (static_cast<unsigned int>(static_cast<unsigned char>(buffer[i+1]))*256+static_cast<unsigned int>(static_cast<unsigned char>(buffer[i])));
if(image[a] < min){
min = image[a];
}
if(image[a] > max){
max = image[a];
}
}
我的理解是:您的输入缓冲区是以大端表示的 16 位图像(最重要的字节在最不重要的字节之前)。我看到的问题:
- 如果最高有效字节超过 127 怎么办?然后你的输出值会溢出,如
128*256=32768 > 32767
.
floor(i/2)
. floor
没有必要:当你除一个整数值时,它总是返回结果的整数部分。此外,给定for
循环的定义,i
它始终是偶数(增加 2),因此该floor
操作是不必要的两倍。
int a; a = floor(i/2)+1;
删除+1
: think 到0
索引像素,您会立即看到您将值分配给错误的像素。对于最后一个像素,您实际上会遇到分段错误。你的指令变成:const int a = i/2;
(Ehi,多么简单!:))
image[a] = [...];
:你正在做的一些演员实际上是必要的,尤其是演员unsigned char
。不过,我想知道,您为什么不首先将其buffer
作为缓冲区读取unsigned char
。所有unsigned int
转换都可以省略,因为最低有效字节不需要它,而使用整数值256
已经提升了像素数据
一个客串:min
and max
update 函数可以写成:
min = std::min(min,image[a]);
max = std::max(max,image[a]);
让我们继续:
// Processing the image
Mat img(512, 512, CV_16S, image); //Already done, now remove
垫子的创作已经被照顾好了。
img -= (min);
img *= (32767/max); // (330000/2500);
好的,这有一个使用 opencv 库的更简单的等价物,我们稍后会谈到它。这里有一个问题:这次你真的应该使用 afloat
作为你的部门
img *= (float(32767)/max);
顺便说一句,我认为在这种情况下你想要max-min
分母:
img *= (float(32767)/(max-min));
以下我不明白:
img *= ((max/min)/2) + 2; // 16;
进一步看,
imgArr[FrameNumber-startFrame] = img;
鉴于我上面建议的更改(std::vector
图像),这变为:
imgVector.push_back(img);
完成的!
最后一点:在我看来,你想要做的事情可以通过cv::normalize
. 你可以这样做:
cv::normalize(img, img, 0, 32767, NORM_MINMAX, CV_16UC1);