Member 13142768 Ответов: 1

Как дисплей 24 бита RAW изображений с использованием C#


Привет ребята ,
Я использую raw image Displayer, который имеет 16-битную и 8-битную опцию для отображения raw-изображений в виде серого 8/16, но я хотел отобразить изображение в 24bpp rgb /bgr. код, который я использую, прилагается ниже.

Что я уже пробовал:

private void DisplayImage16(string fileName)
{    
    // Open a binary reader to read in the pixel data. 
    // We cannot use the usual image loading mechanisms since this is raw 
    // image data.
    try
    {

        BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open));
        ushort pixShort;
        int i;
        long iTotalSize = br.BaseStream.Length;
        int iNumberOfPixels = (int)(iTotalSize /2);

        // Get the dimensions of the image from the user
        ID = new ImageDimensions(iNumberOfPixels);
        if (ID.ShowDialog() == true)
        {
            width = Convert.ToInt32(ID.tbWidth.Text);
            height = Convert.ToInt32(ID.tbHeight.Text);
            canvas.Width = width;
            canvas.Height = height;
            img.Width = width;
            img.Height = height;
            pix16 = new ushort[iNumberOfPixels];

            for (i = 0; i < iNumberOfPixels; ++i)
            {
                pixShort = (ushort)(br.ReadUInt16());
                //pix16[i] = pixShort;
            }
            br.Close();

            int bitsPerPixel = 24;
            stride = (width * bitsPerPixel *3);

            // Single step creation of the image
            bmps = BitmapSource.Create(width, height, 96, 96, PixelFormats.Gray16, null,
                pix16, stride);
            img.Source = bmps;
            bnSaveJPG.IsEnabled = true;
            bnSavePNG.IsEnabled = true;
        }
      //  else
        {
            br.Close();
        }

    }
    catch (Exception e)
    {
       // continue;
       // MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

    }
}     


private void DisplayImage08(string fileName)
{
    // Open a binary reader to read in the pixel data. 
    // We cannot use the usual image loading mechanisms since this is raw 
    // image data.         
    try
    {
        BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open));
        byte pixByte;
        int i;
        int iTotalSize = (int)br.BaseStream.Length;

        // Get the dimensions of the image from the user
        ID = new ImageDimensions(iTotalSize);
        if (ID.ShowDialog() == true)
        {
            width = Convert.ToInt32(ID.tbWidth.Text);
            height = Convert.ToInt32(ID.tbHeight.Text);
            canvas.Width = width;
            canvas.Height = height;
            img.Width = width;
            img.Height = height;
            pix08 = new byte[iTotalSize];

            for (i = 0; i < iTotalSize; ++i)
            {
                pixByte = (byte)(br.ReadByte());
               pix08[i] = pixByte;
            }
            br.Close();

            int bitsPerPixel = 24;
            stride = (width * bitsPerPixel +7)/24;

            // Single step creation of the image
            bmps = BitmapSource.Create(width, height, 96, 96, PixelFormats.Gray8, null,
                pix08, stride);
            img.Source = bmps;
            bnSaveJPG.IsEnabled = true;
            bnSavePNG.IsEnabled = true;
        }
      //  else
        {
            //br.Close();
        }
    }
    catch (Exception e)
    {
        //MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

private void bnSavePNG_Click(object sender, RoutedEventArgs e)
{
    SaveFileDialog dlg = new SaveFileDialog();
    dlg.Filter = "PNG Images (.png)|*.png";

    // Show save file dialog box
    Nullable<bool> result = dlg.ShowDialog();
    string targetPath = "";

    // Process save file dialog box results
    if (result == true)
    {
        // Save document
        targetPath = dlg.FileName;
        FileStream fs = new FileStream(targetPath, FileMode.Create);
        BitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmps));
        encoder.Save(fs);
        fs.Close();
    }
}

Richard MacCutchan

Пожалуйста, не просто сбрасывайте груз неформатированного кода и не ожидайте, что кто-то отладит его для вас. Пожалуйста, отредактируйте свой вопрос, удалите весь код, не относящийся к вашему вопросу, добавьте теги " pre " вокруг оставшейся части и объясните точно, где и в чем ваша проблема.

Member 13142768

спасибо за ваше предложение ,
теперь вы можете увидеть отредактированный вопрос
на самом деле я знаю серое изображение 8bpp и 16bpp для dislpay, взяв файл, который имеет данные bixel в формате raw(имя файла veer. raw )
я хочу, чтобы отобразить в 24 бита, так что вы можете помочь мне, чтобы отобразить сырья imgage, прочитав файл из памяти и дисплей как изображения .надеюсь, вы поможете мне

Karthik_Mahalingam

использовать  Ответить  кнопка, чтобы отправить комментарии / запрос пользователю, чтобы пользователь получил уведомление и ответил на ваш текст.

1 Ответов

Рейтинг:
2

Fueled By Caffeine

Вы можете заполнить цветовые данные для растрового источника следующим образом:

PixelFormat pf = PixelFormats.Bgr24;
int rawStride = (width * pf.BitsPerPixel + 7) / 8;
byte[] rawImage = new byte[rawStride * height];
int rgbIndex = 0;
for (int lineIndex = 0; lineIndex < height; lineIndex++)
{
    int lineStart = lineIndex * rawStride;
    for (int pixelIndex = 0; pixelIndex < width; pixelIndex++)
    {
        rawImage[lineStart++] = (byte)(br.ReadByte()); // Red
        rawImage[lineStart++] = (byte)(br.ReadByte()); // Green
        rawImage[lineStart++] = (byte)(br.ReadByte()); // Blue
    }
}
image = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride);


Не зная, в каком формате находятся необработанные данные, я не могу посоветовать вам правильный способ чтения файла. Приведенный выше код предполагает, что данные хранятся в RGBRGB.и т. д. без каких-либо пробелов.