yuuho.wiki

カオスの欠片を集めて知恵の泉を作る

ユーザ用ツール

サイト用ツール


tips:python:numpy:start

文書の過去の版を表示しています。


numpy

裏技

座標を得る

画像は高さ方向下向きにHで幅方向右向きにWと決まっている. 画像は(H,W,C)の形である. コンピューターで使われる二次元座標はほとんどの場合右方向にX,下方向にYとなっている. つまり画像中の座標は(Y,X)となっているのだ.

画像中の座標が求まると座標を利用した画像処理ができて便利. (H,W,2_xy)の形の座標を作ってみよう.

H,W = Y,X = 5,7
 
grid = np.c_[tuple(m[:,:,np.newaxis] for m in np.mgrid[:H,:W][::-1])]
grid = np.c_[tuple(m[:,:,np.newaxis] for m in np.mgrid[:Y,:X][::-1])] # どちらでも構わない.
 
# こっちのほうが良さげ
grid = np.mgrid[:H,:W].transpose(1,2,0)[:,:,::-1]
grid = np.mgrid[:Y,:X].transpose(1,2,0)[:,:,::-1]

これをつかって画像中心からの距離を利用してグラデーションのかかった点を描画してみる

import numpy as np
from PIL import Image
 
H,W = 300,400
grid = np.c_[tuple(m[:,:,np.newaxis] for m in np.mgrid[:H,:W][::-1])]
 
window = 3
x,y = grid[:,:,0], grid[:,:,1]
x = x/W*window - (window/2)
y = y/H*window - (window/2)
v = np.e**(-(x**2+y**2))[:,:,np.newaxis] * 255
img = np.c_[v,v,v].astype(np.uint8)
 
Image.fromarray(img)

この場合,2×2行列での座標変換は

transformed = (np.array([[1,2],[3,4]]) @ grid.reshape(-1,2).T).T.reshape(grid.shape)

とやるのが良さそう.

同次座標

(N,2)のndarrayを同次座標に変えて戻す

harr = np.c_[arr,np.ones((arr.shape[0],1))]
arr = harr[:,:-1]

サンプリングを利用した画像変形

H,W,C = Y,X,_ = img.shape
 
grid = np.mgrid[:H,:W].transpose(1,2,0)[:,:,::-1]
 
smp_x = grid[:,:,0].astype(np.int64).flatten()
smp_y = grid[:,:,1].astype(np.int64).flatten()
 
out = img[smp_y,smp_x,:].reshape(H,W,C)

変形

np.r_はaxis=0でのconcatenate.
np.c_はaxis=-1でのconcatenate.(要検証)

dtypeは常に意識するのが良い.

in-place

numpyやpytorchのin-placeな関数とは 破壊的代入をおこなう関数.copy()などで防げる.

linalg

linear algebra (線形代数) パッケージ.

linalg.solve(A,B)

$AX=B$の$X$を返す.

型変換

.astype()でfloatからintへ変換すると,四捨五入ではなく小数点以下切り捨てとなる.

tips/python/numpy/start.1558336797.txt.gz · 最終更新: 2019/05/20 07:19 by yuuho