【发布时间】:2013-03-25 18:56:46
【问题描述】:
我想从我的 WPF 程序中的数据值创建一个 16 位灰度图像。目前我一直在研究使用带有 PixelFormats.Gray16 集的 WriteableBitmap。
但是我无法让它工作,微软页面 (http://msdn.microsoft.com/en-us/magazine/cc534995.aspx) 将 Gray16 格式列为不可通过 WriteableBitmap 写入,但是不建议如何以这种方式制作一个。
目前我的代码在一个循环中运行,其中i 表示图像高度,j 表示宽度,看起来像这样:
short dataValue = GetDataSamplePixelValue(myDataValue);
//the pixel to fill with this data value:
int pixelOffset = ((i * imageWidth) + j) * bytesPerPixel;
//set the pixel colour values:
pixels[pixelOffset] = dataValue;
我确实得到了一张图片,但它只是一堆垂直的黑白线条。如果只使用 8 位灰度数据,我没有问题(在这种情况下,在上面的示例中,short 更改为byte)。
有谁知道如何使用 WPF 创建每像素 16 位或更高灰度的图像?这张图片最终也需要保存。
非常感谢任何建议。
编辑
除此之外,我还进行了一些编辑,现在使用 Gray16 PixelFormat 获得了一个合理的图像。我很难判断它是否实际上是 16 位,因为图像程序的颜色计数为 256,我不确定这是否是因为图像受到 WPF 的约束,或者图像程序确实如此不支持它,因为显然许多图像程序忽略了低 8 位。现在我会坚持我所拥有的。
代码如下:
myBitmap = new WriteableBitmap((int)visualRect.Width, (int)visualRect.Height, 96, 96, PixelFormats.Gray16, null);
int bytesPerPixel = myBitmap.Format.BitsPerPixel / 8;
ushort[] pixels = new ushort[(int)myBitmap.PixelWidth * (int)myBitmap.PixelHeight];
//if there is a shift factor, set the background colour to white:
if (shiftFactor > 0)
{
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = 255;
}
}
//the area to be drawn to:
Int32Rect drawRegionRect = new Int32Rect(0, 0, (int)myBitmap.PixelWidth, (int)myBitmap.PixelHeight);
//the number of samples available at this line (reduced by one so that the picked sample can't lie beyond the array):
double availableSamples = myDataFile.DataSamples.Length - 1;
for (int i = 0; i < numDataLinesOnDisplay; i++)
{
//the current line to use:
int currentLine = ((numDataLinesOnDisplay - 1) - i) + startLine < 0 ? 0 : ((numDataLinesOnDisplay- 1) - i) + startLine;
for (int j = 0; j < myBitmap.PixelWidth; j++)
{
//data sample to use:
int sampleToUse = (int)(Math.Floor((availableSamples / myBitmap.PixelWidth) * j));
//get the data value:
ushort dataValue = GetDataSamplePixelValue(sampleToUse);
//the pixel to fill with this data value:
int pixelOffset = (((i + shiftFactor) * (int)myBitmap.PixelWidth) + j);
//set the pixel colour values:
pixels[pixelOffset] = dataValue;
}
}
//copy the byte array into the image:
int stride = myBitmap.PixelWidth * bytesPerPixel;
myBitmap.WritePixels(drawRegionRect, pixels, stride, 0);
在这个例子中 startLine 和 shiftFactor 已经设置好了,并且取决于用户从数据文件中的哪个点开始查看,shiftFactor 仅在数据文件小于屏幕的情况下为非零,在这种情况下,我我正在使用此值将图像垂直居中。
【问题讨论】:
-
我没有看到任何证据表明 WriteableBitmap 会对 PixelFormats.Gray16 产生问题,您的问题到底是什么?一些处理图像并试图解释你得到的无效结果的代码怎么样?
-
我不确定我是否理解; 2^16 给出 65536 种独特的颜色,2^8 给出 256。
-
保存图像,加载保存的图像,并在代码中生成您自己的直方图,看看您是否真的获得了正确数量的颜色。如果您不能信任其他程序,请自己制作!