convert an opencv affine matrix to CGAffineTransform

余生颓废 提交于 2020-02-21 05:57:14

问题


I'd like to take an affine matrix that I have from OpenCV:

Mat T = getAffineTransform(src_pt, dst_pt);

and then convert it into a CGAffineTransform for use in Core Graphics/Objective-C/iOS. (CGAffineTransform docs)

I've tried:

CGAffineTransform t = CGAffineTransformIdentity;
t.a = T.at<float>(0,0);
t.b = T.at<float>(0,1);
t.c = T.at<float>(1,0);
t.d = T.at<float>(1,1);
t.tx = T.at<float>(0,2);
t.ty = T.at<float>(1,2);

This works fine for x and y translations, but NOT if there is any rotation in the matrix. Something seems to be missing since the resulting image seems to be skewed strangely. I've tried multiplying .b and .c by -1 and switching .b and .c, but neither of those seemed to work. The image still appeared incorrectly skewed.

Edit: I should mention that it's almost rotated correctly. When I switch b and c it's at least rotated in the right direction. It just seems a bit off, as in rotated a little too far.


回答1:


Your problem is that opencv is row major and CGAffineTransform is column major you want

t.a = T.at<float>(0,0);
t.b = T.at<float>(1,0);
t.c = T.at<float>(0,1);
t.d = T.at<float>(1,1);

you can tell because in the documentation CGAffineTransform takes the form

[a  b  0
 c  d  0
 tx ty 1]

note that tx and ty are in the bottom row. In standard row major matrices the translation components go in the rightmost column

[a c tx
 b d ty
 0 0 1]

If the problem persists after making this change (which your question suggests you have already tried) then you need to post more information. As you suggest the problem could be in the origin of your coordinate system but without any information about your origin nobody will be able to help you.



来源:https://stackoverflow.com/questions/14387806/convert-an-opencv-affine-matrix-to-cgaffinetransform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!