3

I have a greyscale image in Julia and I'd like to draw a straight line on the image. I have two pairs of coordinates. They represent the start (x1,y1) and end (x2,y2) pixel positions of where the line should start and end. I'm not sure how to find the pixel positions that fall between these two points that need to be coloured in so that my line appears on the image.

I don't want to do this using an interactive tool or annotation for example because I need to do this for many images based on the exact coordinates specified for the image.

My code looks like this so far:

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)

I've tried looking at Interpolation.jl and some image processing posts on here and blogs etc but I can't seem to get this working.

What I have (ignore the colours) An image which I convert to greyscale What I want (ignore the colours)Greyscale version of this

lara
  • 835
  • 1
  • 8
  • 20

1 Answers1

5

Thanks Tasos Papastylianou I found the Python code here and was easily able to modify it for 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)
lara
  • 835
  • 1
  • 8
  • 20