ImageMagick - calculate perspective without knowin

2020-03-31 03:49发布

How can I get the maximum width and height of an image, perform some maths on it, then use it in my perspective distortion?

I have a bunch of images to which I want to apply a perspective distortion.

The only problem is, each image is a different size.

This code works on an image where I know the size (1440 * 900).

convert test.jpg -matte \ 
    -virtual-pixel transparent \ 
    -distort Perspective '0,0        75,0 \ 
                          0,900      0,450 \ 
                          1440,0     1440,200 \ 
                          1440,900   1200,900' \ 
    distorted.jpg

I know I can get the maximum values by using %h and %w - but I can't find a way to multiply those numbers.

Essentially, what I want to do is define the points like this:

    -distort Perspective '0,0        75,0 \ 
                          0,%h       0,(%h/2) \ 
                          %w,0       %w,200 \ 
                          %w,%h      (%w*0.75),%h'

For bonus points, I'd like to be able to call the perspective using -distort Perspective '@points.txt'

1条回答
▲ chillily
2楼-- · 2020-03-31 04:14

You can use ImageMagick's built-in fx operator to do maths for you, without involving bash mathematics, bc or eval.

Like this:

persp=$(convert image.jpg -format "0,0 75,0 0,%h 0,%[fx:int(h/2)] %w,0,%w,200 %w,%h %[fx:int(w*0.75)],%h" info:)

echo $persp
0,0 75,0 0,900 0,450 1440,0,1440,200 1440,900 1080,900

Then do:

convert image.jpg ... -distort Perspective "$persp" ... distorted.jpg

Oh, for those bonus points... ;-)

convert image.jpg -format "0,0 75,0 0,%h 0,%[fx:int(h/2)] %w,0,%w,200 %w,%h %[fx:int(w*0.75)],%h" info: > points.txt
convert image.jpg ... -distort Perspective @points.txt distorted.jpg
查看更多
登录 后发表回答