# レポート # 右上角を中心に-20度回転したあと垂直反転 library(imager) # 度からラジアンに変換する関数 rad <- function(deg) { return(deg * pi / 180) } im <- grayscale(boats) dim0 <- dim(im) # cimg変数で処理すると遅いので配列で処理する g0 <- array(im, dim0) g1 <- array(0, dim0) g2 <- array(0, dim0) # 回転角(度) theta <- -20 # 回転の中心座標 cx <- dim0[1] cy <- 0 # 任意の座標中心の回転 ct <- cos(rad(theta)) st <- sin(rad(theta)) for (x1 in 1 : dim0[1]) { for (y1 in 1 : dim0[2]) { x2 <- x1 - cx * (1 - ct) - cy * st y2 <- y1 + cx * st - cy * (1 - ct) x0 <- round( x2 * ct + y2 * st) # もしくは x0 <- round( (x1 - cx) * ct + (y1 - cy) * st + cx) y0 <- round(-x2 * st + y2 * ct) # もしくは y0 <- round(-(x1 - cx) * st + (y1 - cy) * ct + cy) if (x0 < 1 || x0 > dim0[1] || y0 < 1 || y0 > dim0[2]) next g1[x1, y1, ,] <- g0[x0, y0, ,] } } # 移動量 bx <- 0 by <- -dim0[2] # 垂直反転と平行移動 for (x1 in 1 : dim0[1]) { x0 <- x1 - bx if (x0 < 1 || x0 > dim0[1]) next for (y1 in 1 : dim0[2]) { y0 <- -y1 - by # 垂直反転と平行移動 if (y0 < 1 || y0 > dim0[2]) next g2[x1, y1, ,] <- g1[x0, y0, ,] } } # 配列→cimg変数 im.rotate <- as.cimg(g2) # 同時に2枚並べるレイアウト layout(t(1 : 2)) plot(im, interpolate = FALSE, main = "元の画像") plot(im.rotate, interpolate = FALSE, main = "回転後の画像") # レイアウトを元に戻す layout(1)