Skip to content Skip to sidebar Skip to footer

Pixel Coordinates From Point A To B

I have a gray scale 50 x 50 pixels picture as a numpy 2D array. Each pixel is a coordinate starting top left [ 0 , 0 ] to bottom right [ 50 , 50 ]. How do i get coordinates of eac

Solution 1:

You can interpolate your image to extract a line profile if that is what you wish to do, this way the coordinates need not be integers:

from scipy.ndimage import map_coordinates 
from skimage.data import coins 
from matplotlib import pyplot as plt 
import numpy as np

npts = 128 
rr = np.linspace(30, 243, npts) # coordinates of points defined here 
cc = np.linspace(73, 270, npts) 

image = coins() 
# this line extracts the line profile from the image 
profile = map_coordinates(image, np.stack((rr, cc))) 

# can visualise as 
fig, ax = plt.subplots(ncols=2) 
ax[0].matshow(image) 
ax[0].plot(cc, rr, 'w--') 
ax[1].plot(profile) # profile is the value in the image along the line

output

Solution 2:

What I figure out helps is to calculate pixel value at a curtain point on the line (vector). Code below:

coordA = [0,0]
coordB = [3,4]


defintermid_pix(coorA, coorB, nb_points=8):
    x_axis = (coorB[0] - coorA[0]) / (nb_points + 1)
    y_axis = (coorB[1] - coorA[1]) / (nb_points + 1)
    rounded = [[round(coorA[0] + i * x_axis), round(coorA[1] + i * y_axis)]
              for i inrange(1, nb_points + 1)]
    rounded_trim = []
    [rounded_trim.append(x) for x in rounded if x notin rounded_trim]
    return rounded_trim
coordinates = intermed_pix(coordA, coordB, nb_points=8)

print(coordinates)

output:

[[0, 0], [1, 1], [1, 2], [2, 2], [2, 3], [3, 4]]

Solution 3:

With scikit-image line() like this:

import numpy as np
from skimage.draw import line
from skimage import io

# Create image
img = np.zeros((50, 50), dtype=np.uint8)

# Get row and col of pixels making line from (4,9) to (12,30)
rr, cc = line(4, 9, 12, 30)

print(rr)

array([ 4,  4,  5,  5,  6,  6,  6,  7,  7,  7,  8,  8,  9,  9,  9, 10, 10,
   10, 11, 11, 12, 12])

print(cc)
array([ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
   26, 27, 28, 29, 30])

# Visualise as image instead of list
img[rr, cc] = 255
io.imsave('result.jpg',img)

enter image description here

Post a Comment for "Pixel Coordinates From Point A To B"