图片双线性插值旋转任意角度(python)

看了很多文章都不完整,结合一下写了完整版

import numpy as np
import cv2
import math
import random
#双线性旋转
def bilinear_rotate(imgArray,theta):
    H, W, channel = imgArray.shape

    pi = math.pi
    #theta = random.randint(0,360)
    angle = theta * pi / 180

    matrix1 = np.array([[1, 0, 0],
                        [0, -1, 0],
                        [-0.5 * H, 0.5 * W, 1]])

    matrix2 = np.array([[math.cos(angle), -math.sin(angle), 0],
                        [math.sin(angle), math.cos(angle), 0],
                        [0, 0, 1]])

    matrix3 = np.array([[1, 0, 0],
                        [0, -1, 0],
                        [0.5 * H, 0.5 * W, 1]])

    new_data = np.zeros_like(imgArray,dtype=np.uint8)

    for i in range(H):
        for j in range(W):

            dot1 = np.matmul(np.array([i, j, 1]), matrix1)
            dot2 = np.matmul(dot1, matrix2)
            dot3 = np.matmul(dot2, matrix3)

            new_coordinate = dot3

            new_i = int(math.floor(new_coordinate[0]))
            new_j = int(math.floor(new_coordinate[1]))

            u = new_coordinate[0] - new_i
            v = new_coordinate[1] - new_j

            if new_j>=W or new_i >=H or new_i<1 or new_j<1 or (i+1)>=H or (j+1)>=W:
                continue

            if (new_i + 1)>=H or (new_j+1)>=W:
                new_data[i, j, :] = imgArray[new_i,new_j, :]

            else:
                new_data[i, j, :] = (1-u)*(1-v)*imgArray[new_i,new_j, :] + \
                                   (1-u)*v*imgArray[new_i,new_j+1, :] + \
                                   u*(1-v)*imgArray[new_i+1,new_j, :] +\
                                   u*v*imgArray[new_i+1,new_j+1, :]

    return new_data
def ratate(theta):
	imgdata = cv2.imread('test.jpg')
	cv2.imwrite('ans.jpg',bilinear_rotate(imgdata,theta))
	ans = cv2.imread('ans.jpg')
	cv2.imshow('旋转结果',ans)
	cv2.waitKey(0)
if __name__ == '__main__':
	ratate(180)

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值