在 Julia 中的灰度图像上的两个像素之间画一条线

Draw a line between two pixels on a grayscale image in Julia

我在 Julia 中有一张灰度图像,我想在图像上画一条直线。我有两对坐标。它们表示线条应该开始和结束的位置的开始 (x1,y1) 和结束 (x2,y2) 像素位置。我不确定如何找到需要着色的这两点之间的像素位置,以便我的线出现在图像上。

我不想使用交互式工具或注释来执行此操作,因为我需要根据为图像指定的确切坐标对许多图像执行此操作。

到目前为止,我的代码如下所示:

using Images, Colors, ImageView

function convert_rgb_image_to_greyscale(imagefilepath)
    img = load(imagefilepath)
    my_img_grey = convert(Image{Gray}, my_img)
    view(my_img_grey, pixelspacing = [1,1])

    return my_img_grey
end

imagefilepath = "myimage.jpg"
my_img_grey = convert_rgb_image_to_greyscale(imagefilepath)

start_pos = [1048 48] # (x1,y1)
end_pos = [1050 155] # (x2,y2)

我已经尝试查看 Interpolation.jl 以及此处和博客等上的一些图像处理帖子,但我似乎无法正常工作。

我有什么(忽略颜色) 我想要的(忽略颜色)

感谢 Tasos Papastylianou 我找到了 Python 代码 here 并且能够轻松地为 Julia 修改它:

function bresenhams_line_algorithm(x1::Int, y1::Int, x2::Int, y2::Int)
# Calculate distances
dx = x2 - x1
dy = y2 - y1

# Determine how steep the line is
is_steep = abs(dy) > abs(dx)

# Rotate line
if is_steep == true
    x1, y1 = y1, x1
    x2, y2 = y2, x2
end

# Swap start and end points if necessary and store swap state
swapped = false
if x1 > x2
    x1, x2 = x2, x1
    y1, y2 = y2, y1
    swapped = true
end
# Recalculate differentials
dx = x2 - x1
dy = y2 - y1

# Calculate error
error = round(Int, dx/2.0)

if y1 < y2
    ystep = 1
else
    ystep = -1
end

# Iterate over bounding box generating points between start and end
y = y1
points = []
for x in x1:(x2+1)
    if is_steep == true
        coord = (y, x)
    else
        coord = (x, y)
    end
    push!(points,coord)
    error -= abs(dy)

    if error < 0
        y += ystep
        error += dx
    end
end

# Reverse the list if the coordinates were swapped
if swapped == true
    points = points[end:-1:1]
end

    return points
end

# Small test
x1 = 0
y1 = 0
x2 = 5
y2 = 5

points = bresenhams_line_algorithm(x1, y1, x2, y2)