zoukankan      html  css  js  c++  java
  • 图像仿射变换之图像旋转实现

    一. 实验代码

    实验目标:实现输入图像绕中心点逆时针旋转30度

     1 import cv2
     2 import numpy as np
     3 
     4 # affine transformation -> rotation
     5 def affine(img, a, b, c, d, tx, ty):
     6     H, W, C = img.shape
     7 
     8     # temporary image
     9     tem = img.copy()
    10     img = np.zeros((H+2, W+2, C), dtype=np.float32)
    11     img[1:H+1, 1:W+1] = tem
    12 
    13     # get shape of new image
    14     H_new = np.round(H).astype(np.int)
    15     W_new = np.round(W).astype(np.int)
    16     out = np.zeros((H_new, W_new, C), dtype=np.float32)
    17 
    18     # get position of new image
    19     x_new = np.tile(np.arange(W_new), (H_new, 1))
    20     y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1)
    21 
    22     # get position of original image by affine
    23     adbc = a * d - b * c
    24     x = np.round((d * x_new  - b * y_new) / adbc).astype(np.int) - tx + 1
    25     y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1
    26 
    27     # adjust center by affine
    28     dcx = (x.max() + x.min()) // 2 - W//2
    29     dcy = (y.max() + y.min()) // 2 - H//2
    30 
    31     x -= dcx
    32     y -= dcy
    33 
    34     x = np.clip(x, 0, W + 1)
    35     y = np.clip(y, 0, H + 1)
    36 
    37     # assign pixcel
    38     out[y_new, x_new] = img[y, x]
    39     out = out.astype(np.uint8)
    40 
    41     return out
    42 
    43 # Read image
    44 img = cv2.imread("../paojie.jpg").astype(np.float32)
    45 
    46 # Affine
    47 A = 30.
    48 theta = - np.pi * A / 180.
    49 
    50 out = affine(img, a=np.cos(theta), b=-np.sin(theta), c=np.sin(theta), d=np.cos(theta),
    51  tx=0, ty=0)
    52 
    53 # Save result
    54 cv2.imshow("result", out)
    55 cv2.imwrite("out.jpg", out)
    56 cv2.waitKey(0)
    57 cv2.destroyAllWindows()

    二. 实验结果:


    原图 ↑
     

    逆时针旋转30度图像  ↑
     

    三. 实验难点突破:

            https://www.cnblogs.com/wojianxin/p/12519498.html

            https://www.jianshu.com/p/1cfb3fac3798


    四. 图像仿射变换简介:

            https://www.cnblogs.com/wojianxin/p/12518393.html

  • 相关阅读:
    socket的accept函数解析
    c socket(续)
    C socket指南
    网络字节序和本机字节序
    jar包
    RESTful API 设计指南[转]
    理解RESTful架构[转]
    c语言正则表达式
    Fedora设置中文
    创建框架结构的页面2
  • 原文地址:https://www.cnblogs.com/wojianxin/p/12522044.html
Copyright © 2011-2022 走看看