実現したいこと
点群データを集めるためのシミュレーション環境を作る目的で最近Unityを勉強し始めた者です.深度画像を手に入れたいと思っています
説明
現時点できていること
C#スクリプト(PassDepth.cs)でカメラからのRGB, depthの情報をそれぞれcolorBuffer, depthBufferに割り当ててcolorRenderTexture, depthRenderTextureの2つを作成しました.Quadを作成し,depthRenderTextureを用いたMaterialを用いて深度バッファが正しくdepthRenderTextureに読み込まれていることを確認しました.
解決したいこと
上記のように作成したdepthRenderTextureを深度画像としてPNGファイルで保存することを試みましたが,シーンビューのような画像は得られず真っ白な画像が保存されました.
おそらく深度がdepthRenderTextureに反映されていないと思ったがどのように改善すればよいのか分かりません.用いたソースコードとスクリーンショットを以下に載せます.解決の手助けをしてくだされば幸いです.
該当のソースコード
PassDepth.cs
1using System.Collections; 2using System.Collections.Generic; 3using System.IO; 4 5using UnityEngine; 6 7public class PassDepth : MonoBehaviour 8{ 9 [SerializeField] 10 public Camera camera; 11 [SerializeField] 12 public RenderTexture colorRenderTexture; 13 [SerializeField] 14 public RenderTexture depthRenderTexture; 15 16 // Start is called before the first frame update 17 void Start() 18 { 19 var colorBuffer = colorRenderTexture.colorBuffer; 20 var depthBuffer = depthRenderTexture.depthBuffer; 21 22 camera.SetTargetBuffers(colorBuffer, depthBuffer); 23 24 } 25 26 // Update is called once per frame 27 void Update() 28 { 29 Graphics.SetRenderTarget(colorRenderTexture); 30 camera.Render(); 31 } 32}
QuadにアッタチするMaterialを作成する際に用いたShader
MyUnlit.shader
1Shader "Unlit/MyUnlit" 2{ 3 Properties 4 { 5 _MainTex ("Texture", 2D) = "white" {} 6 } 7 SubShader 8 { 9 Tags { "RenderType"="Opaque" } 10 LOD 100 11 12 Pass 13 { 14 CGPROGRAM 15 #pragma vertex vert 16 #pragma fragment frag 17 18 #include "UnityCG.cginc" 19 20 struct appdata 21 { 22 float4 vertex : POSITION; 23 float2 uv : TEXCOORD0; 24 }; 25 26 struct v2f 27 { 28 float2 uv : TEXCOORD0; 29 float4 vertex : SV_POSITION; 30 }; 31 32 sampler2D _MainTex; 33 float4 _MainTex_ST; 34 35 v2f vert (appdata v) 36 { 37 v2f o; 38 o.vertex = UnityObjectToClipPos(v.vertex); 39 o.uv = TRANSFORM_TEX(v.uv, _MainTex); 40 41 return o; 42 } 43 44 fixed4 frag (v2f i) : SV_Target 45 { 46 // sample the texture 47 fixed4 col = tex2D(_MainTex, i.uv); 48 col.g = col.r; 49 col.b = col.r; 50 51 return col; 52 } 53 ENDCG 54 } 55 } 56} 57
深度をPNG保存する際に試みたソースコード
Texture2D tex = new Texture2D(RenderTextureRef.width, RenderTextureRef.height, TextureFormat.RGB24, false); RenderTexture.active = RenderTextureRef; tex.ReadPixels(new Rect(0, 0, RenderTextureRef.width, RenderTextureRef.height), 0, 0); tex.Apply(); //RenderTexture.active = null; // Encode texture into PNG byte[] bytes = tex.EncodeToPNG(); Object.Destroy(tex); //Write to a file in the project folder File.WriteAllBytes(Application.dataPath + "/../DepthRenderTexture.png", bytes);
私のUnity画面のスクリーンショット
保存された画像
長文となってしまい申し訳ありません.Unity初心者なのでささいなアドバイスでもありがたいです.よろしくお願いいたします.

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2024/01/19 00:17