Assuming that your (u,v) coordinates are supposed to be within the range [0,1] x [0,1], your computation is not quite right. It should be
u = X/texture_width
v = 1 - Y/texture_height
Given an image pixel coordinate (X,Y), this will compute the corresponding texture (u,v) coordinate. However, if you pick a random image pixel and convert its (X,Y) coordinate into a (u,v) coordinate, this coordinate will most likely not show up in the list of vt
entries in the OBJ file.
The reason is that (u,v) coordinates in the OBJ file are only specified at the corners of the faces of your 3D object. The coordinates that you compute from image pixels likely lie in the interior of the faces.
Assuming your OBJ file represents a triangle mesh with positions and texture coordinates, the entries for faces will look something like this:
f p1/t1 p2/t2 p3/t3
where p1
, p2
, p3
are position indices and t1
, t2
, t3
are texture coordinate indices.
To find whether your computed (u,v) coordinate maps to a given triangle, you'll need to
- find the texture coordinates (u1,v1), (u2,v2), (u3,v3) of the corners by looking up the
vt
entries with the indices t1
, t2
, t3
,
- find out whether the point (u,v) lies inside the triangle with corners (u1,v1), (u2,v2), (u3,v3). There are several ways to compute this.
If you repeat this check for all f
entries of the OBJ file, you'll find the triangle(s) which the given image pixel maps to. If you don't find any matches then the pixel does not appear on the surface of the object.