Home > front end >  Labeling coordinates on an image using Python
Labeling coordinates on an image using Python

Time:08-18

I have an input image and a dataframe with 1000 rows and 3 columns, an X coordinate, Y coordinate, and a Label (0-5).

I want to read in my image, find each of the coordinates on the image from the dataframe and label them by to color depending on the label column and display the image.

My DataFrame is something like this.

   data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]}

 df = pd.DataFrame(data)

 

I can plot a single point (200, 200)

import matplotlib.pyplot as plt
img = plt.imread('../data/textures/test/test_image.jpg')

fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 400, 0, 300])
ax.plot(200, 200, 'x', color='firebrick')

enter image description here

CodePudding user response:

As far as I understood you want to mark certain pixels based on a label and you have the pixel/label as a data frame. You only need to define markers and colors and iterate over your data frame. The following will do this

import pandas as pd
import matplotlib.pyplot as plt

data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]}
data = pd.DataFrame(data)
img = plt.imread("img.jpg")
# Define symbols and colors as you want.
# Item at ith index corresponds to that label in 'Texture'.
color = ['y', 'r', 'b', 'g', 'm']
marker = ['o', 'v', '1', 's', 'p']

#
fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 400, 0, 300])
# 
for _, row in data.iterrows():
    ax.plot(row['X'], row['Y'], marker[row['Texture']],color=color[row['Texture']])
plt.show()

If you have your data as python dictionary, you can Zip the dictionary values and iterate over them. The following will do it,

import matplotlib.pyplot as plt

data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]}
img = plt.imread("img.jpg")
# Define symbols and colors as you want.
# Item at ith index corresponds to that label in 'Texture'.
color = ['y', 'r', 'b', 'g', 'm']
marker = ['o', 'v', '1', 's', 'p']
# Zip the data, returns a generator of paired (x_i, y_i, texture_i)
data_zipped = zip(*(data[col] for col in data))
#
fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 400, 0, 300])
# 
for x,y, texture in data_zipped:
    ax.plot(x, y, marker[texture],color=color[texture])
plt.show()
  • Related