当前位置: 动力学知识库 > 问答 > 编程问答 >

ImageMagick - calculate perspective without knowing image dimensions

问题描述:

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'

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: