Search code examples
pythonpandasopencvimage-processingpca

Extract x,y coordinates of each pixel from an image in Python


Let's say I have a color image that I've loaded into a numpy array of dimensions (200 x 300 x 3). In total, there are 60,000 pixels in the image. I'm trying to extract the width,height (x,y) coordinates of each pixel starting from the upper left top corner representing pixel 1 such that:

pixel#   x    y
1        0    0
2        1    0
.
.
301      0    1
302      1    1
.
.
60,000   299 199   

I'm tempted to use a for loop to do this in a more manual-nature but are there libraries or more effective ways to get those coordinate values for each pixel as such?


Solution

  • Since the format you're showing seems to be pandas, I'll present the output with pandas, but you could just use a mere print. :)

    I even included a n-dimension solution to your problem as comments.

    import numpy as np
    from itertools import product
    
    arr = np.array([
        list(range(300))
        for _ in range(200)
    ])
    
    print(arr.shape)
    # (200, 300)
    
    pixels = arr.reshape(-1)
    
    """ n-dimension solution
        coords = map(range, arr.shape)
        indices = np.array(list( product(*coords) ))
    """
    xs = range(arr.shape[0])
    ys = range(arr.shape[1])
    indices = np.array(list(product(xs, ys)))
    
    import pandas as pd
    pd.options.display.max_rows = 20
    
    index = pd.Series(pixels, name="pixels")
    df = pd.DataFrame({
        "x" : indices[:, 0],
        "y" : indices[:, 1]
    }, index=index)
    print(df)
    #           x    y
    # pixels          
    # 0         0    0
    # 1         0    1
    # 2         0    2
    # 3         0    3
    # 4         0    4
    # 5         0    5
    # 6         0    6
    # 7         0    7
    # 8         0    8
    # 9         0    9
    # ...     ...  ...
    # 290     199  290
    # 291     199  291
    # 292     199  292
    # 293     199  293
    # 294     199  294
    # 295     199  295
    # 296     199  296
    # 297     199  297
    # 298     199  298
    # 299     199  299
    
    # [60000 rows x 2 columns]