Converting TIFF Image to XY Coordinates

Viewed 491

I am trying to deconstruct a TIFF image to XY coordinates in Python. The first column in dataframe should be X and second column as Y. A sample file is attached. Would it be done the same way as a JPEG? So far, I have tried the code below.

Sample Tiff Image: https://file-examples.com/index.php/sample-images-download/sample-tiff-download/

Sample Code (can't figure out what I'm missing to get coordinates):

from PIL import Image
import numpy as np
import pandas as pd
image= Image.open(r"file_example_TIFF_1MB.tiff")
mypixels= colourImg.convert("RGB")
colors = np.array(mypixels.getdata()).reshape(image.size + (3,))
1 Answers

colors is a WxHx3 array. Let's look at colors[:, :, 0], which is the red channel. The X coordinate is the column-index, and the Y-coordinate is the row index. To create the dataframe you want, you need to iterate over these.

result = []

h, w, _ = colors.shape
for x in range(w):
    for y in range(h):
        result.append([x, y, *colors[y, x, :]])

Then, create your dataframe

df = pd.DataFrame(result, columns=["X", "Y", "R", "G", "B"])

Alternatively, use numpy.meshgrid() to create the x and y numbers for you, and then flatten them into a column vector. This will be much faster than the loopy approach for larger images.

result = np.zeros((w * h, 5))
h, w, c = colors.shape

xg, yg = np.meshgrid(range(w), range(h))

result[:, 0] = xg.flatten()
result[:, 1] = yg.flatten()

for i in range(c):
   result[:, 2 + i] = colors[:, :, i].flatten()

Now you have the same thing as before in result, so you can convert it to a dataframe.

Related