繁体   English   中英

Python和C ++之间的OpenCV图像旋转不一致

[英]OpenCV Inconsistent Image Rotation between Python and C++

我正在使用OpenCV将图像逆时针旋转90度。 我从Python实现( rotate.py )开始,然后将其转换为C ++( rotate.cpp )。 问题是我得到的结果不一致。 我在下面的两个版本中都在getRotationMatrix2D(...)行附近注释了这两个版本,以描述不一致之处。 如果我不遵循下面描述的方法,则会得到旋转但移出帧的图像。

我正在使用OpenCV 2.4和opencv-python 3.4.0.12。
编辑:我现在也尝试过使用OpenCV 3.4,结果相同。


该图像通过rotate.cpp旋转,旋转中心在Point(x/2, y/2)

旋转不良


旋转

import sys
import os
import cv2

i = sys.argv[1]
im = cv2.imread(i)
y,x = im.shape[:2]  

# x/2, y/2 can be used for the center
# but then the two lower are required
# This follows a tutorial I read
M = cv2.getRotationMatrix2D((x/2,y/2), 90, 1)
M[0, 2] += (y / 2) - x/2
M[1, 2] += (x / 2) - y/2

# The center also works as x/2, x/2
# but only if the two lines after are commented out
M = cv2.getRotationMatrix2D((x/2,x/2), 90, 1)
#M[0, 2] += (y / 2) - x/2
#M[1, 2] += (x / 2) - y/2  

im = cv2.warpAffine(im, M, (y, x))

try:
    cv2.imwrite(i+'~'+'.png', im, params=(cv2.IMWRITE_PNG_COMPRESSION, 5))
except:
    os.remove(i+'~'+'.png')
    continue

try:
    os.rename(i+'~'+'.png', i)
except KeyboardInterrupt:
    os.rename(i+'~'+'.png', i)
    raise

rotation.cpp

#include <opencv2/opencv.hpp>
#include <iostream>

int main(int argc, char** argv) {
    const auto in_img = cv::imread(argv[1]);
    const auto in_size = in_img.size();

    const auto& x = in_size.width;
    const auto& y = in_size.height;

    decltype(in_img) out_img(x, y, in_img.type());
    const auto out_size = out_img.size();

    //       Only works if these are both x/2      v    v
    cv::Mat M = cv::getRotationMatrix2D(cv::Point(x/2, x/2), 90, 1.0);
    //M.at<int>(0, 2) += ((y/1) - x/2);
    //M.at<int>(1, 2) += ((x/1) - y/2);
    //   ^   Were not having any effect

    cv::warpAffine(in_img, out_img, M, out_size);

    cv::imwrite(std::string(argv[1]) + "~.png", out_img, {CV_IMWRITE_PNG_COMPRESSION, 5});

}

仿射矩阵变换的数据类型为double not int at语句必须为M.at<double(...)

为了进行以(x/2, x/2)为中心的CCW旋转,矩阵需要移位1 M.at<double>(1,2) -= 1; 这是因为OpenCV认为左上角是(0, 0)

作为替代方案,仿射矩阵可以使用矩阵旋转完全绕过,以90°为单位旋转。 以python为例,例如img.rot90()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM