内容へ移動
講義(山本裕樹)
ユーザ用ツール
ログイン
サイト用ツール
検索
ツール
文書の表示
バックリンク
最近の変更
メディアマネージャー
サイトマップ
ログイン
>
最近の変更
メディアマネージャー
サイトマップ
トレース:
numericalipb:ans4
この文書は読取専用です。文書のソースを閲覧することは可能ですが、変更はできません。もし変更したい場合は管理者に連絡してください。
====== 【数値情報処理b】第4回の答え ====== ===== 課題 ===== boats の画像を「右上角を中心に-20度回転したあと垂直反転」して表示するプログラムを作成しなさい。 ''for'' で一つ一つの画素を処理し、''imshift()'' , ''imrotate()'' , ''mirror()'' を使わないこと。 「」の部分は人によって違う。 ---- ==== 解答例 ==== 右上角を中心に回転には、「任意の座標中心の回転」を使う。 逆変換の計算式は以下の通り。 \begin{eqnarray} x_{0}&=&\left\{x_{1}-c_{x}(1-\cos\theta)-c_{y}\sin\theta\right\}\cos\theta+\left\{y_{1}+c_{x}\sin\theta-c_{y}(1-\cos\theta)\right\}\sin\theta\\ y_{0}&=&-\left\{x_{1}-c_{x}(1-\cos\theta)-c_{y}\sin\theta\right\}\sin\theta+\left\{y_{1}+c_{x}\sin\theta-c_{y}(1-\cos\theta)\right\}\cos\theta \end{eqnarray} もしくは以下でも良い。 \begin{eqnarray} x_{0}&=&\left(x_{1}-c_{x}\right)\cos\theta+\left(y_{1}-c_{y}\right)\sin\theta+c_{x}\\ y_{0}&=&-\left(x_{1}-c_{x}\right)\sin\theta+\left(y_{1}-c_{y}\right)\cos\theta+c_{y} \end{eqnarray} さらに、右上角を中心に回転のあとに垂直反転を行う必要がある。 <file rsplus report4.R[enable_line_numbers="true"]> # レポート # 右上角を中心に-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) </file> 回転中心を変えるには 24,25 行目を以下のように変更する。 * 右下角を中心に回転の場合 <code rsplus> cx <- dim0[1] cy <- dim0[2] </code> * 左下角を中心に回転の場合 <code rsplus> cx <- 0 cy <- dim0[2] </code> 垂直反転の後に回転の場合は、39行目と54行目を入れ替えたあとに 20-41 行目と 43-56 行目を入れ替える。
numericalipb/ans4.txt
· 最終更新: 2025/07/09 23:50 by
yuki
ページ用ツール
文書の表示
バックリンク
文書の先頭へ