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

时间:2016-10-26 23:45:47

标签: image image-processing julia bresenham

我在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和一些图像处理帖子以及博客等,但我似乎无法让这个工作。

我有什么(忽略颜色)An image which I convert to greyscale 我想要的(忽略颜色)Greyscale version of this

1 个答案:

答案 0 :(得分:5)

感谢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)