目的
このようなMask画像を画像に対して縮小したいというマニアックな事例の備忘録。
これを
こうする
パイプライン
マスクの中心を計算
# 重心を取得 m = cv2.moments(mask) cx = int(m['m10'] // m['m00']) cy = int(m['m01'] // m['m00']) print(cx, cy)
中心に画像をオフセット
Affine変換で画像を平行移動させる。
# 中心にmaskをシフト num_rows, num_cols = mask.shape[:2] # Create translation matrix offsetx = mask.shape[0]//2-cx offsety = mask.shape[1]//2-cy translation_matrix = np.float32([ [1,0,offsetx], [0,1,offsety] ]) # Image translation mask_translation = cv2.warpAffine(mask, translation_matrix, (num_cols,num_rows))
mask全体を縮小
# maskを半分に縮小 mask2 = cv2.resize(mask_translation, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR) mask_resized = cv2.copyMakeBorder(mask2, 200, 200, 200, 200, cv2.BORDER_CONSTANT, 0)
オフセット分を戻す
# オフセットを戻す translation_matrix = np.float32([ [1,0,-offsetx], [0,1,-offsety] ]) # Image translation mask_translation = cv2.warpAffine(mask_resized, translation_matrix, (num_cols,num_rows)) plt.imshow(mask_translation)