图像旋转 python实现(针对mxn长方形尺寸图像)

实现对图像(mxn m n 不等)进行90 180  270 三个角度的旋转(不引进黑色无像素区域并且保持图像尺寸不变。)

原图:


对正方行尺寸的图像进行90 180 270 角度的旋转完全不出现问题(不出现黑色无像素区域),但是长方形尺寸图像就会出现黑块。如:


解决的方法:

先利用 img.transpose(1, 0)  

transpose()函数把图像的0 1 维转置,图像的尺寸就从mxn变成了nxm,这就避免了出现黑色无像素区域的问题。

然后观察结果发现,图像不仅旋转了并且左右也对称镜像了,

所以还需要一步操作:

img1.transpose(Image.FLIP_LEFT_RIGHT)  #再进行一次左右镜像,把左右对调回来,就得到旋转90°后的图像.



csdn上一篇比较好的博客用了自己转换坐标来实现图像旋转,逻辑感觉通篇是对的,但是旋转会出错,代码见下,有时间再更正好。

链接: http://www.cnblogs.com/xianglan/archive/2010/12/26/1917247.html

对方的代码:

#coding=utf-8
import cv2
import math
import numpy as np


def LRotate(image, angle):
    size = image.shape
    h = size[0]
    w = size[1]
    print (size)

    anglePi = angle * math.pi / 180.0
    cosA = math.cos(anglePi)
    sinA = math.sin(anglePi)
    X1 = math.ceil(abs(0.5 * h * cosA + 0.5 * w * sinA))
    X2 = math.ceil(abs(0.5 * h * cosA - 0.5 * w * sinA))
    Y1 = math.ceil(abs(-0.5 * h * sinA + 0.5 * w * cosA))
    Y2 = math.ceil(abs(-0.5 * h * sinA - 0.5 * w * cosA))
    #H = int(2 * max(Y1, Y2))
    #W = int(2 * max(X1, X2))
    #size = (W + 1, H + 1)
    if angle == 90:
        iLRotate = np.zeros([w, h], np.uint8)




    for i in range(h):
        for j in range(w):
            #x = int(cosA * i - sinA * j - 0.5 * w * cosA + 0.5 * h * sinA + 0.5 * W)
            #y = int(sinA * i + cosA * j - 0.5 * w * sinA - 0.5 * h * cosA + 0.5 * H)
            x = int(cosA * i - sinA * j - 0.5 * w * cosA + 0.5 * h * sinA + 0.5 * w)
            y = int(sinA * i + cosA * j - 0.5 * w * sinA - 0.5 * h * cosA + 0.5 * h)
            print (x, y)
            #if x>-1 and x<h and y>-1 and y<w:
            iLRotate[x, y] = image[i, j]
    return iLRotate


image = cv2.imread('/...../1/x_0.png', -1)
iLRotate90 = LRotate(image, 90)
cv2.imwrite('....../x_90.png', iLRotate90)


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值