- Home /
How to load an RGB image from the resource folder into an int/float[] containing only grayscale values?
what I've been able to do so far is to read an image as a texture2D using Resources.loadAll("") and then iterate through the image using nested for loop and get each individual pixel stored into a float[] I have the ability to access the the red, blue , green, alpha and even grayscale values individually but what I need to store the the black and white representation of the image that is merge the 3 layers of RBG into a single layer and get the grayscale values either 1 or 0 , how can I do that?
Texture2D[] images = Resources.LoadAll<Texture2D> ("");
float[] finalImage = new float[ images[0].width * images[0].height ];
int index = 0;
for (int i = 0; i < images [0].width; i++) {
for (int j = 0; j < images [0].height; j++) {
finalImage[index]= Mathf.Round(images [0].GetPixel (i, j).a);
if (finalImage[index] ==0 && index<100) {
Debug.Log (i + " " + j);
}
index++;
}
}
https://docs.unity3d.com/ScriptReference/Color-grayscale.html
Btw. GetPixel for each pixel is slow. Using GetPixels gets all pixels at once. Double loop over the result and you have your image too.
Answer by Orion_78 · Apr 11, 2018 at 02:41 PM
You can use a shader
Shader "Loreal/GeyScale"
{
Properties
{
_MainTex("MainTex", 2D) = "white" {}
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
Blend SrcAlpha OneMinusSrcAlpha
Tags{ "Queue" = "Transparent" }
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
fixed4 frag(v2f i) : SV_Target
{
fixed4 color = tex2D(_MainTex, i.uv);
float greyscaleAverage = (color.r + color.g + color.b) / 3.0f;
return greyscaleAverage;
}
ENDCG
}
}
}
Then "all you need to do" is to blit that render texture to your texture2d
RenderTexture rt = RenderTexture.GetTemporary(textureRGB.width, textureRGB.height));
Graphics.Blit(textureRGB rt, grayScaleMaterial);
textureA.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0, false);
// not used textureA.Apply();
Then you can use textureA.GetRawTextureData() to have an array of color and keep only the r/g/b or a of your texture...
Not sure this is the fasted way
Your answer
![](https://koobas.hobune.stream/wayback/20220612124345im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Blending two Texture2D 1 Answer
Assiging an Image to a Button 1 Answer
shown like 16bit color image 1 Answer
Scaling / Resizing an Image (Texture2D) 6 Answers
How do you crop a Texture2d 1 Answer