- Home /
How do I iterate over a large Texture2d quickly?
I have a large Texture2d image (5632 x 2048) that I need to iterate through and split into colours, but given that there are over 11 million pixels, doing this through a traditional foreach loop is taking over half an hour. Is there a better approach I can take?
Are you literally using a foreach loop? How are you actually declaring the loop? Also, what kinds of things are you doing within the loop? A few examples from your script could go a long way in helping understand why it would take such a dramatically long time to cycle through the loop. (For reference, a few million loops, in a "simple" scenario, should take no more than a few seconds)
Like Eno said, you must be doing something wrong or you have some very expensive operation going on. However half an hour seems way too long. Over here I made an image resampler that can crop the image and also shrink or upscale an image. In my test I upscaled an image with a resolution of 1338x2000 up to 5000x5000. It does perform a bilinear lookup for each target pixel. The straight forward implementation took 16 seconds while the optimised version took only 2 seconds.
If your process really takes 30 $$anonymous$$utes to process an image of that size, you would only process 6408 pixel per second which would be horribly slow. Do you use GetPixel and SetPixel? If you do, that would explain this horrible result ^^.
Apologies, I only just saw these comments. I am using a literal foreach loop, but I also tried the foreach function of the list. I am using GetPixels(), is there something about this function that is particularly slow?
Edit: Here is the code that I am running in the Start() function:
color32s = map.GetPixels();
colors = new List<Color>();
foreach (Color c in color32s)
{
if (!colors.Contains(c))
{
colors.Add(c);
}
}
Edit 2: Is it possible that Contains() is causing the long processing time?
Answer by ashjack · Jun 11, 2021 at 09:29 AM
The issue wasn't the fact that I was iterating over a large list, it was that I was calling List.Contains() for every single loop on a growing second list. According to this StackOverflow question, Contains on a List is quite slow, and I instead used a HashSet, which shortened the entire iteration to a few seconds.
Your answer
Follow this Question
Related Questions
Problem when loading texture from folder 0 Answers
Scaling / Resizing an Image (Texture2D) 6 Answers
How to convert texture2D to image in C# 3 Answers
How do you crop a Texture2d 1 Answer
Image is not loading into Texture 0 Answers