- Home /
How do I get the average color among 3 points in a texture?
I'm building an application that polygonize a picture. I still have to work on the actual geometry but in the meanwhile:
Let's suppose I've got 3 coordinates of a texture. How do I find the average color inside that triangle? Thank you.
(Possibly for Unity Free)
Answer by sschaem · Jul 07, 2014 at 07:01 AM
If its offline (simplest and shortest code):
Make a loop that covers the bounding box of the triangle
Check each point if its inside the triangle, if yes accumulate and keep that count.
When the loop end divide the accumulated RGB value by the number of points. Done.
Pseudo code:
x0 = min(p0.x, p1.x, p2.x); x1 = max(p0.x, p1.x, p2.x);
y0 = min(p0.y, p1.y, p2.y); y1 = max(p0.y, p1.y, p2.y);
color.rgb = 0; count = 0;
for(y=y0; y<y1; y++)
for(x=x0; x<x1; x++)
if(IsInside(float2(x, y), p0, p1, p2)) { color.rgb += texture.GetPixel(x,y); count += 1; }
if(count>1) color.rgb /= count;
See this if you need the barycentric logic for IsInside(): http://www.blackpawn.com/texts/pointinpoly/
If this is done at runtime and you need optimal performance will need to write a simple triangle rasterizer and use that to accumulate value.
note: one important thing. If the texture hold gamma compressed values you 'cant' accumulate the value without first decompressing them. They should be actually sRGB encoded, so use the opengl sRGB function to decompress to linear before accumulating. Then after you do the average, you need to compress back to sRGB. Follow the formula in this link to decode the texture RGB color data. https://www.opengl.org/registry/specs/EXT/texture_sRGB.txt
Answer by legion_44 · Jul 05, 2014 at 02:21 PM
Using Texture2D you can use GetPixel to get pixel color from specified position. Then You just add all color values (r,g,b) and divide them by their count. Example, you have 3 pixels:
Color c1;
Color c2;
Color c3;
Texture2D tex;
void Awake()
{
c1 = tex.GetPixel(0,0);
c2 = tex.GetPixel(0,1);
c3 = tex.GetPixel(1,1);
float Raverage = c1.r + c2.r + c3.r;
float Gaverage = c1.g + c2.g + c3.g;
float Baverage = c1.b + c2.b + c3.b;
Color average = new Color(Raverage / 3, Gaverage / 3, Baverage / 3);
}
Hope that helps,
Paul
Thanks, Sure, this gives the average among 3 pixels, I was looking for the average of ALL pixels inside a triangle with defined vertexes.
Just so you know, it's way simpler just to do average = (c1 + c2 + c3) / 3;
.
Your answer
Follow this Question
Related Questions
Getting triangles of a single gameobject (one prefab instance, not all) 1 Answer
Changing two different objects renderer colour 1 Answer
How do I get the color of a certain mesh vertex? 0 Answers
Merge mesh triangles into polygons: need help with vertex ordering 1 Answer
Overlapping Polygon Triangulation 0 Answers