简体   繁体   English

16 位灰度图像的像素值

[英]Pixel value for 16 bits grayscale images

I know this is mostly an image question not code, but I'll give it a shot here.我知道这主要是图像问题而不是代码,但我会在这里试一试。

So first I have a 8bits/pixel grayscale image(bitmap).所以首先我有一个 8 位/像素的灰度图像(位图)。 Which means that each pixel is represented into 1 byte.这意味着每个像素都表示为 1 个字节。 This means that the the pixel value is the byte value.这意味着像素值是字节值。 Clear enough.够清楚。

But then...但是之后...

I have a 16bits/pixel grayscale image (bitmap).我有一个 16 位/像素的灰度图像(位图)。 Which means that each pixel is represented into 2 bytes.这意味着每个像素表示为 2 个字节。 This is clear for me.这对我来说很清楚。 Now I create a byte[] array that will hold each byte value.现在我创建一个 byte[] 数组来保存每个字节值。

For an 1024x1024 image I will have 2097152 bytes.对于 1024x1024 图像,我将有 2097152 字节。 It's 1024*1024*2.它是 1024*1024*2。

My question is now, how do I get the pixel value for a specific pixel.我现在的问题是,如何获取特定像素的像素值。

Let's say for pixel at position(X|Y) the bytes are 84 and 77. How do I transform these 2 values into the pixel value.假设对于位置 (X|Y) 处的像素,字节为 84 和 77。如何将这 2 个值转换为像素值。

Firstly I need this for some calculation where I need the pixel value, then I want to change the color palette of the bitmap and it works fine with 8 bitsperpixel images, but doesn't for 16bitsperpixel images.首先,我需要这个来进行一些需要像素值的计算,然后我想更改位图的调色板,它适用于 8 位每像素图像,但不适用于 16 位每像素图像。

Any help would be nice.你能帮忙的话,我会很高兴。

 var width = bitmap.PixelWidth;
            var height = bitmap.PixelHeight;
            var dpiX = bitmap.DpiX;
            var dpiY = bitmap.DpiY;

            byte[] pixels = new byte[
                     bitmap.PixelHeight * bitmap.PixelWidth *
                         bitmap.Format.BitsPerPixel / 8];

            bitmap.CopyPixels(pixels, bitmap.PixelWidth * bitmap.Format.BitsPerPixel / 8, 0);

This is how I create the array of pixels.这就是我创建像素数组的方式。

It may be easier to use a 2-byte type for the pixel array:对像素数组使用 2 字节类型可能更容易:

var width = bitmap.PixelWidth;
var height = bitmap.PixelHeight;
var pixels = new ushort[width * height];

bitmap.CopyPixels(pixels, 2 * width, 0);

Access an individual pixel value directly from that array:直接从该数组访问单个像素值:

var x = 100;
var y = 200;
var pixel = (int)pixels[width * y + x];

In order to convert the 16bpp pixel array into a 8bpp array, just divide each pixel value by 256为了将 16bpp 像素阵列转换为 8bpp 阵列,只需将每个像素值除以 256

var pixels8bpp = pixels.Select(p => (byte)(p / 256)).ToArray();

and create a 8bpp BitmapSource by并创建一个 8bpp BitmapSource

var bitmap8bpp = BitmapSource.Create(
    width, height, 96, 96, PixelFormats.Gray8, null, pixels8bpp, width);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM