# How to find the pixels of a texture for a certain face

I'm making a script that determines the color of a face, based on the texture. I have an object that is UV unwrapped and has a texture assigned. What I would like to do is find the pixels that are in the UV space of a certain face.

I have something that works, but it is terribly slow. For every face I loop over all pixels of the texture image and determine if they are inside the UV space of the face. Not the best method I think :D

In the Python API documentation I found something about MeshTextureFace and this seems exactly what I need. But I have no idea how I could use this.

Any ideas?

By the sounds of it, you just need to optimize what you have.

Some suggestions.

• Don't check every pixel, at the very least calculate a bounding box around the face's UV's and only check those pixels.
• Rather then do a point-in-polygon test for each pixel. Use a scan-line method. See: Darel Rex Finley's Efficient Polygon Fill, Or Blenders version of it fill_poly_v2i_n

Note that being a scripting language Python isn't ideal for these tasks - but it can likely be sped up enough to be usable as long as you don't need real-time feedback.

Update, made a more efficient version of Darel Rex's algorithm, see link.
(avoids looping over all coordinates for each y-pixel).

• Thanks Campbell, I will try to use the method of Darel Rex Finely. So there is no 'easy' way? No access to some already existing functionality in Blender I could use? – jasperge Dec 6 '13 at 23:14
• @jasperge, no, generally per-pixel operations are not very good to do in Python, so we dont provide helper functions for these kinds of tasks. It shouldn't be too hard to port fill_poly_v2i_n to Python (think it reads a little easier then the original). – ideasman42 Dec 7 '13 at 2:52
• Sorry, for slow reaction. I finally got around to implement the fill_poly_v2i_n. Together with some other optimizations (still no bounding box), the processing time went from a few hours to a few minutes! – jasperge Feb 19 '14 at 12:36
• @jasperge would be good if you could post the code here, or at least a link to it. – ideasman42 Feb 19 '14 at 13:21
• Indeed it would. But the problem is it's too much tied in with the rest of the code. I will see if I can get the core part out and post it here. – jasperge Feb 19 '14 at 13:30