こんにちは、シニアTです。
連続した写真から、gifアニメを作る続きです。
手取りの写真は、視点や視線が、一定じゃないので、
そのままアニメにすると、ブレブレの動画になります。
ブレを補正するには、open-cvのツールが便利です。
(インストールの仕方は、初期のブログにあります)
e:\imfolderにjpgファイルを格納して、下のプログラム
をrunさせると、同じフォルダに、アニメーションgifが
出来上がります。
説明は、次回。
import numpy as np
import imageio as imio
import glob
import cv2
def detect(images):
detector = cv2.AKAZE_create()
return [detector.detectAndCompute(
cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), None) for img in images]
def stabilize(images, alp=0.1, pn=500):
def get_matches(s_ds, d_ds):
matches = bf.match(s_ds, d_ds)
matches = sorted(matches, key=lambda x: x.distance)
return matches[:int(len(matches) * alp)]
def get_M(d_kp, mchs):
s_pts = np.float32([s_kp[m.queryIdx].pt for m in mchs]).reshape(-1,1,2)
d_pts = np.float32([d_kp[m.trainIdx].pt for m in mchs]).reshape(-1,1,2)
M, _ = cv2.findHomography(d_pts, s_pts, cv2.RANSAC, pn)
return M
kpdss = detect(images)
s_kp, s_ds = kpdss[0]
bf = cv2.BFMatcher(cv2.NORM_HAMMING)
ht, wd, channels = images[0].shape
return \(これは¥マークではなくバックスラッシュが入ります)
[cv2.warpPerspective(img, get_M(d_kp, get_matches(s_ds, d_ds)), (wd, ht))
for (d_kp, d_ds) ,img in zip(kpdss, images) ]
folder = 'e:\\imfolder'
newsize=(640, 480)
cut = 50
interportation=cv2.INTER_AREA
images = [imio.imread(fname) for fname in glob.glob(folder + '\\*.jpg')]
images = stabilize(images)
tsize = (newsize[0]+2*cut, newsize[1]+ 2*cut)
images = [cv2.resize(img, tsize, interportation) for img in images]
imio.mimsave(folder + '\\movie.gif', [img[cut:-cut, cut:-cut] for img in images])
写真は、本日のお弁当。
いかにも、親父が詰めたな...って感じですね。
色彩がいまいちだからかな?