pythonimage-processingcartesian-coordinates

invert y axis and retain image python


I have a custom game engine I am writing, where I feed a sprite sheet into a python file to produce a JSON detailing which of the 8 adjacent spaces can have a given tile layer appear.

I am attempting to create a bounding outline of each sprite in a sprite sheet and I need to be able to translate opencv's imread from an origin of 0,0 being at the top left corner -> bottom left corner as the origin.

enter image description here

I know I can flip the image, but that's not what I'm looking for. I want to invert the y axis such that y increases from the bottom to top, while the x-axis remains unchanged.

Have also seen examples where, using MatPlotLib, the y axis itself can be inverted. But I need to be able to read pixel colors, which is why OpenCV was preferable.


Solution

  • Have you tried re-indexing the image array so that the Y-axis is inverted while the X-axis remains unchanged. In this case, you don't need to flip the image or manipulate the axes using Matplotlib. Instead, you can simply access the pixel values by inverting the Y-coordinate with respect to the image height.

    import cv2
    
    def get_inverted_y_pixel(image, x, y):
        inverted_y = image.shape[0] - 1 - y
        return image[inverted_y, x]
    
    def main():
        image_path = 'path/to/your/sprite_sheet.png'
        image = cv2.imread(image_path)
    
    # Accessing a pixel with inverted Y-axis
    x, y = 100, 50
    pixel_color = get_inverted_y_pixel(image, x, y)
    
    print(f"Pixel color at ({x}, {y}): {pixel_color}")
    
    if __name__ == "__main__":
        main()
    #In this example, the get_inverted_y_pixel function inverts the Y-axis 
    #for the given coordinates and returns the pixel color from the OpenCV image.