前言 :
此範例使用 RAW 10 bit。
你將網頁往下拉可以直接看結果,為啥是一片綠油油 ? 因為 RAW 檔案是 Gr, R, Gb, B 排列,綠色佔兩個阿 ! 整張圖片綠色分布是50%,紅色25%,藍色 25%。如下圖是本範例 RAW 檔案格式的排列方式。
題外話:
另外如果你已經熟悉本篇文章,你想要前往更高境界,可以看這邊 https://blog.csdn.net/weixin_38884324/article/details/80462246
這是我用這篇程式碼的 GPU 改良版,運行速度飛快。
好了,我們直接來看程式碼吧 !
C # :
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class RAW_Original : MonoBehaviour
{
public RawImage img;
void Start()
{
System.Diagnostics.Stopwatch time = new System.Diagnostics.Stopwatch();
time.Start();
byte[] b = File.ReadAllBytes("C:/FFMPEG/Hello.raw");
time.Stop();
print("檔案讀取 " + time.Elapsed.TotalSeconds + " 秒");
time.Reset();
time.Start();
// 預先必須要先知道圖片寬高,因為 RAW 檔案沒有寬高的資訊
int width = 4208;
int height = 3120;
Texture2D t = new Texture2D(width, height, TextureFormat.RGBAFloat, false, false);
int i = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int L = b[i];
int H = b[i + 1];
int D = (H << 8) + L;
float C = D / 1024.0f;
if (y % 2 == 0)
{
if (x % 2 == 0)
{
// height - 1 - y 是將原先 Texture2D 原點從左下角改為左上角
t.SetPixel(x, height - 1 - y, new Color(0, C, 0, 1));
}
else
{
t.SetPixel(x, height - 1 - y, new Color(C, 0, 0, 1));
}
}
else
{
if (x % 2 == 0)
{
t.SetPixel(x, height - 1 - y, new Color(0, 0, C, 1));
}
else
{
t.SetPixel(x, height - 1 - y, new Color(0, C, 0, 1));
}
}
i += 2;
}
}
t.Apply();
img.texture = t;
// File.WriteAllBytes("C:/FFMPEG/AR1335.png", t.EncodeToPNG()); // 保存成 PNG 檔案
time.Stop();
print("執行 " + time.Elapsed.TotalSeconds + " 秒");
}
}