前言 :
建議先看這篇文章
https://blog.csdn.net/weixin_38884324/article/details/80457594
RAW 轉 RGB 解析度會是原圖的四分之一,這篇程式碼就是將四個像素合併成一個的範例
Main.cs :
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.UI;
public class Main : MonoBehaviour
{
public RawImage outputImage;
void Start()
{
Stopwatch time = new Stopwatch();
time.Start();
float[,,] rgb = Node_RawToRGB.Run("C:/A.raw", 4208, 3120);
time.Stop();
print("CPU 執行 " + time.Elapsed.TotalSeconds + " 秒");
outputImage.texture = RGB_To_Texture(rgb);
}
Texture2D RGB_To_Texture(float[,,] rgb)
{
int w = rgb.GetLength(0);
int h = rgb.GetLength(1);
Texture2D t = new Texture2D(w, h, TextureFormat.RGBAFloat, false);
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
float r = rgb[x, y, 0];
float g = rgb[x, y, 1];
float b = rgb[x, y, 2];
t.SetPixel(x, y, new Color(r, g, b));
}
}
t.Apply();
return t;
}
}
RawToRGB.cs :
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class RawToRGB : MonoBehaviour
{
public static float[,,] Run(string path, int width, int height)
{
// 檔案路徑
byte[] b = File.ReadAllBytes(path);
// 事先必須先輸入圖片的長寬
int i = 0;
int k = 0;
float[,,] rggb = new float[width, height, 4]; // R:0, Gr:1, Gb:2, B:3
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 / 1023.0f;
int mY = height - 1 - y;
if (y % 2 == 0)
{
if (x % 2 == 0)
{
rggb[x, mY, 1] = C; // Gr
}
else
{
rggb[x, mY, 0] = C; // R
}
}
else
{
if (x % 2 == 0)
{
rggb[x, mY, 3] = C; // B
}
else
{
rggb[x, mY, 2] = C; // B
}
}
k += 1;
i += 2;
}
}
//-----------------------------------------------------------------------------
// 將四個像素 (Gr, R, B, Gb) 合併成一個 RGB 像素,所以長寬都要除以二
// RAW 轉 RGB 後,解析度將是原圖的四分之一
int rgb_width = width / 2;
int rgb_height = height / 2;
float[,,] rgb = new float[rgb_width, rgb_height, 3];
for (int y = 0; y < rgb_height; y++)
{
for (int x = 0; x < rgb_width; x++)
{
int X = x * 2;
int Y = y * 2;
int mY = height - 1 - Y;
int my = rgb_height - 1 - y;
// R:0, Gr:1, Gb:2, B:3
float Gr = rggb[X, mY, 1];
float R = rggb[X + 1, mY, 0];
float B = rggb[X, mY - 1, 3];
float Gb = rggb[X + 1, mY - 1, 2];
float G = (Gr + Gb) / 2;
rgb[x, my, 0] = R;
rgb[x, my, 1] = G;
rgb[x, my, 2] = B;
}
}
return rgb;
}
}
結果 :
與前文結果明顯不同,要注意的是兩邊都是正確結果,只是螢幕的顯示沒辦法顯示那麼精確而已。
如果是完成度的話,還是 RGB 比較高。