pyvips icon indicating copy to clipboard operation
pyvips copied to clipboard

Dont know how to use affine function, could not get the same result which I got from opencv

Open d5423197 opened this issue 2 years ago • 3 comments

Hello author,

I have read the doc but could not fully understand affine API.

For example,

I want to rotate an image around its center. I used to use opencv getRotationMatrix2D get the rotation matrix, which is a 2 by 3 matrix. Then I will use opencv warpaffine to transform the image.

I know how to convert the angle part which is the first argument in pyvips affine function. But I don't know how to assign the 3rd column which is the translation part in pyvips affine function.

Example

angle = 45
scale = 1
image = cv2.imread(img_path, -1)
image_size = image.shape[1], image.shape[0] # (2432, 2038)
image_center = tuple(np.array(image_size / 2) # (1216, 1019)
rot_mat = cv2.getRotationMatrix2D(image_center, angle, scale)
result = cv2.warpAffine(
        image,
        affine_mat,
        (new_w, new_h),
        flags=cv2.INTER_LINEAR,
    )

rotation matrix is like: [[ 0.70710678, 0.70710678, -364.38365595], [ -0.70710678, 0.70710678, 1158.30003589]]

I think this is a general question. How to use the general transformation matrix in pyvips.

Thanks for any help

d5423197 avatar Feb 27 '23 10:02 d5423197

Hello, did you see:

https://www.libvips.org/API/current/libvips-resample.html#vips-affine

jcupitt avatar Feb 27 '23 11:02 jcupitt

Hello there,

Do you have any examples or tutorials?

Thanks,

d5423197 avatar Feb 28 '23 01:02 d5423197

That's the main documentation. In python you could write:

#!/usr/bin/python3

import sys
import pyvips

x = pyvips.Image.new_from_file(sys.argv[1])
if not x.hasalpha():
    x = x.addalpha()
y = x.affine([0.70710678, 0.70710678, -0.70710678, 0.70710678])
y.write_to_file(sys.argv[2])

Then:

$ ./affine.py ~/pics/astronauts.png x.png

To make:

x

Notes:

  • The 2x2 matrix [[a, b], [c, d]] is passed as [a, b, c, d].
  • Adding the alpha gives a transparent background on rotate. You might prefer some solid colour instead, see the background option to affine.
  • By default, affine outputs the bounding box of output pixels, ie. will rotate about the centre.
  • You can set a different output area with oarea.
  • See image.rotate() or image.similarity() for convenience functions.
  • You can also translate the input and output coordinate systems if you want to change the sampling convention.

jcupitt avatar Feb 28 '23 10:02 jcupitt