Get normalized device coordinate of an image pixel I have an image rendered to the screen, and based on the normalized device coordinates of the cursor I would like to pick the pixel of the image under the cursor.
Say the image has four channels, I then define a pixel struct:
struct Pixel {
  unsigned char r, g, b, a;
};

I can then get the closest index of the pixel under cursor like this:
int getPixel(float normalX, float normalY, float imageWidth, float imageHeight) {
  return (int)(normalY*imHeight)*imageWidth + normalX*imageWidth;
}

Now how would I do it the other way around, basically given the pixel index get its normalized device coordinates?
You can modulus by row length to retrieve the x coordinate (think about the x coordinate &quot;wrapping around&quot; after each line), and division by row length to get the y coordinate (inverting the multiply you have by imageWidth). We subtract one from the width and height to ensure the last pixel in the row/column maps to 1.0. Note that this isn't &quot;Normalized Device Coordinates&quot;, since that implies a 3D quantity which also stores depth, and that all coordinates lie in [-1,1].
struct Point2D { float x; float y; };

Point2D GetNormalizedPixelCoords(int pixelIdx, int imageWidth, int imageHeight) {
    Point2D point;
    point.x = (pixelIdx % imageWidth) / (float)(imageWidth-1);
    point.y = (pixelIdx / imageWidth) / (float)(imageHeight-1);
    return point;
}