Search code examples
rimage-processingimagemagickcamera-distortion

Perspective transformation using R and magick


I am trying prescriptive transformation with R magick package.

I want to deskew and correct the prespective in the following image.

enter image description here

I am not able to get the desired result. What am I doing wrong here ?

library(magick)

imgfile <- "test_skew.jpg"
img <- magick::image_read(imgfile)

# input coordinates
inp <- list(x = c(29.5740973594396, -6.62134003951859, 322.64038081552, 
                  307.461649003054), 
            y = c(-5.74456619364109, 515.002694449434, 
                  490.483204598527, -2.24178192922578))


plot(img)
polygon(inp$x, inp$y, border = "red")

text(inp$x[1], inp$y[1], label = "1", col = 'red')
text(inp$x[2], inp$y[2], label = "2", col = 'red')
text(inp$x[3], inp$y[3], label = "3", col = 'red')
text(inp$x[4], inp$y[4], label = "4", col = 'red')


# output coordinates
outp <- list(y = c(0, 520, 520, 0),
             x = c(0, 0, 334, 334))

polygon(outp$x, outp$y, border = "blue")

text(outp$x[1]+10, outp$y[1]+10, label = "1", col = 'blue')
text(outp$x[2]+10, outp$y[2]-10, label = "2", col = 'blue')
text(outp$x[3]-10, outp$y[3]-10, label = "3", col = 'blue')
text(outp$x[4]-10, outp$y[4]+10, label = "4", col = 'blue')

I want to make the black border a perfect rectangle by distorting the input coordinates (red) to the output coordinates (blue).

enter image description here

# inx1,iny1 outx1,outy1 .... inx4,iny4 outx4,outy4
distc <- c(inp$x[1], inp$y[1], outp$x[1], outp$y[1],
           inp$x[2], inp$y[2], outp$x[2], outp$y[2],
           inp$x[3], inp$y[3], outp$x[3], outp$y[3],
           inp$x[4], inp$y[4], outp$x[4], outp$y[4])

magick::image_distort(img, 
                      "perspective", distc)

enter image description here

The desired result is as follows.

enter image description here


Solution

  • I can't read R so a lot of your code is lost on me, however, I can tell you the command-line parameters you would need to use to make ImageMagick do what you want. So hopefully you can adapt that to solve your question.

    The parameters to -distort perspective are 4 pairs of points:

    [x,y] coords of point 1, [x,y] coords where it must be mapped to
    [x,y] coords of point 2, [x,y] coords where it must be mapped to
    [x,y] coords of point 3, [x,y] coords where it must be mapped to 
    [x,y] coords of point 4, [x,y] coords where it must be mapped to
    

    So for your specific image:

    magick FgvGK.png -distort perspective "271,520 238,524 241,91 238,78 507,111 524,78 495,518 524,524" true.jpg 
    

    which yields:

    enter image description here

    and hopefully you can see the black frame is now rectangular.