您当前的位置:首页 > 计算机 > 编程开发 > Python

Python旋转图片

时间:07-29来源:作者:点击数:

Python通过旋转一个个像素点来实现旋转图片

(课堂作业,有感而发,如有错误,敬请斧正!)

def rotate_image(input_image, theta):
    input_rows, input_cols, channels = input_image.shape
    assert channels == 3

    # 1. Create an output image with the same shape as the input
    output_image = np.zeros_like(input_image)
    #获取中点坐标,具体参照np.shape()
    x0 = input_image.shape[1]/2
    y0 = input_image.shape[0]/2

    for i in range(input_image.shape[1]):#width
        for j in range(input_image.shape[0]):#heigh
        	"""
            (i,j)旋转后的坐标为(x,y),公式 数学推导
            一点(x,y)绕点(x0,y0)旋转θ角度后的坐标(x`,y`)为:
            { x` = (x - x0)*cos - (y - y0)*sin + x0
			{ y` = (x - x0)*sin + (y - y0)*cos + y0
			"""
            x = (int)((i - x0)*np.cos(theta) - (j - y0)*np.sin(theta) + x0)
            y = (int)((i - x0)*np.sin(theta) + (j - y0)*np.cos(theta) + y0)
            if x < 300 and y < 300 and x >= 0 and y >= 0:#满足的所有条件
                output_image[i][j] = input_image[x][y]
    return output_image

测试:

def display(img):
    # Show image
    plt.figure(figsize = (5,5))
    plt.imshow(img)
    plt.axis('off')
    plt.show()
    
def load(image_path):
    out = None
    image = skimage.io.imread(image_path)#读入图片
    out = np.array(image)
    pass
    out = out.astype(np.float64) / 255
    return out
    
if __name__ == '__main__':
    image1_path = './image1.jpg'
    image1 = load(image1_path)
    display(rotate_image(image1, np.pi / 4.0))
    

旋转后的你:

在这里插入图片描述
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门