Skip to content

Instantly share code, notes, and snippets.

@DiKorsch
Last active June 17, 2018 00:10
Show Gist options
  • Save DiKorsch/97917b79beb332a65758 to your computer and use it in GitHub Desktop.
Save DiKorsch/97917b79beb332a65758 to your computer and use it in GitHub Desktop.
#include "rotation.hpp"
using namespace cv;
using namespace std;
void rotate(const Mat src, Mat &dest, double angle, int borderMode, const Scalar &borderValue){
int w = src.size().width, h = src.size().height;
Size2d new_size = Size2d(abs(w * COS((int)angle % 180)) + abs(h * SIN((int)angle % 180)), abs(w * SIN((int)angle % 180)) + abs(h * COS((int)angle % 180)));
dest = Mat(new_size, src.type());
Size2d old_size = src.size();
Point2d rot_point = Point2d(old_size.width / 2.0, old_size.height / 2.0);
double a = COS(angle), b = SIN(angle);
Mat rot_mat = (Mat_<double>(3,3) <<
a, b, (1 - a) * rot_point.x - b * rot_point.y,
-1 * b, a, b * rot_point.x + (1 - a) * rot_point.y,
0, 0, 1);
double offsetx = (new_size.width - old_size.width) / 2,
offsety = (new_size.height - old_size.height) / 2;
Mat trans_mat = (Mat_<double>(3,3) <<
1, 0, offsetx,
0, 1, offsety,
0, 0, 1);
Mat affine_mat = Mat(trans_mat * rot_mat).rowRange(0, 2);
warpAffine(src, dest, affine_mat, new_size, INTER_LINEAR, borderMode, borderValue);
}
#ifndef ROTATE_H
#define ROTATE_H
#include <opencv2/opencv.hpp>
#include <math.h>
#define WHITE 255
#define BLACK 0
#define PI 3.14159265
#define TAN(angle) tan(angle * PI / 180)
#define SIN(angle) sin(angle * PI / 180)
#define COS(angle) cos(angle * PI / 180)
void rotate(const cv::Mat src, cv::Mat &dest, double angle, int borderMode = cv::BORDER_CONSTANT, const cv::Scalar &borderValue = cv::Scalar(WHITE));
#endif // ROTATE_H
import math, numpy as np, cv2
__ANGLE_FUNC = lambda angle, func: round(func(angle * math.pi / 180), 10)
COS = lambda angle: __ANGLE_FUNC(angle, math.cos)
SIN = lambda angle: __ANGLE_FUNC(angle, math.sin)
def rotate(src, angle):
h, w, _ = src.shape
old_size = (w, h)
new_size = (
int(abs(w * COS(angle % 180)) + abs(h * SIN(angle % 180))),
int(abs(w * SIN(angle % 180)) + abs(h * COS(angle % 180))))
rot_point = (old_size[0] / 2, old_size[1] / 2)
a, b = COS(angle), SIN(angle)
rot_mat = np.matrix([
[a, b, (1 - a) * rot_point[0] - b * rot_point[1]],
[-1 * b, a, b * rot_point[0] + (1 - a) * rot_point[1]],
[0, 0, 1]
])
offsetx, offsety = (new_size[0] - old_size[0]) / 2, (new_size[1] - old_size[1]) / 2
trans_mat = np.matrix([
[1, 0, offsetx],
[0, 1, offsety],
[0, 0, 1]
])
affine_mat = (trans_mat * rot_mat)[:2]
return cv2.warpAffine(src, affine_mat, new_size, borderMode = cv2.BORDER_REPLICATE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment