pyvips
pyvips copied to clipboard
Dont know how to use affine function, could not get the same result which I got from opencv
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
Hello, did you see:
https://www.libvips.org/API/current/libvips-resample.html#vips-affine
Hello there,
Do you have any examples or tutorials?
Thanks,
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:

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
backgroundoption toaffine. - 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()orimage.similarity()for convenience functions. - You can also translate the input and output coordinate systems if you want to change the sampling convention.