2021年6月20日日曜日

【OpenCV】画像サイズを変更するresize

画像処理ライブラリOpenCVで画像サイズを変更するresizeについて説明する。


OpenCVを使うには次のようにインポートが必要。
import cv2

例に用いる画像'yamagirl.jpg'(幅400x高さ266ピクセル)は以下を使用(フリー写真素材ぱくたそより)





1. 書式

cv2.resizeの書式は以下の通り。

dst = cv.resize( src, dsize[, dst[, fx[, fy[, interpolation]]]] )
引数 意味
dst サイズ変換後の画像
img 元画像
dsize 変換後の画像サイズ。(幅, 高さ)のタプルで指定
fx, fy 幅、高さの変換後の倍率
interpolation 補完方法の指定


2. dsizeを指定する場合

dsizeに(幅, 高さ)のタプルで拡大縮小後の画像サイズを設定する。幅、高さは整数で指定する。
幅400高さ266ピクセルの元の画像を幅200高さ133に縮小する場合。

import cv2

img = cv2.imread('yamagirl.jpg')
dst = cv2.resize(img, (200, 133))
cv2.imwrite('dst.jpg', dst)

実行結果



幅400高さ266ピクセルの元の画像を幅400高さ133に変換する場合。

import cv2

img = cv2.imread('yamagirl.jpg')
dst = cv2.resize(img, (400, 133))
cv2.imwrite('dst.jpg', dst)

実行結果





3. fx, fyを指定する場合

fx,fyに幅、高さの拡大縮小率を指定することで同様に画像の拡大縮小が可能。 その際、第二引数dsizeにはNoneを指定し無効にする。
幅、高さを1.5倍に拡大する場合。

import cv2

img = cv2.imread('yamagirl.jpg')
dst = cv2.resize(img, None, fx=1.5, fy=1.5)
cv2.imwrite('dst.jpg', dst)

実行結果





4. interpolation flagの指定

interpolation flagを指定することにより拡大縮小時の画素補完方法を指定できる。指定が無い場合はデフォルトのcv2.INTER_LINEARが用いられる。
縮小する場合はcv2.INTER_AREAが適しており、拡大する場合にはcv2.INTER_CUBICcv2.INTER_LINEARが適している。
cv2.INTER_AREAを指定する場合。

import cv2

img = cv2.imread('yamagirl.jpg')
dst = cv2.resize(img, (200, 133), cv2.INTER_AREA)
cv2.imwrite('dst.jpg', dst)

cv2.resizeの引数に用いることができるinterpolation flagは以下の通り。

cv.INTER_NEAREST nearest neighbor interpolation
cv.INTER_LINEAR bilinear interpolation
cv.INTER_CUBIC bicubic interpolation
cv.INTER_AREA resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.
cv.INTER_LANCZOS4 Lanczos interpolation over 8x8 neighborhood
cv.INTER_LINEAR_EXACT Bit exact bilinear interpolation


interpolation flagを用いて元画像を1/4に縮小した場合。
縮小する場合はcv2.INTER_AREAが適しているとされるが、この例では差が良くわからない(そもそも縮小時は優劣は分かりにくい)。


元画像



cv.INTER_NEAREST



cv.INTER_LINEAR



cv.INTER_CUBIC



cv.INTER_AREA



cv.INTER_LANCZOS4



cv.INTER_LINEAR_EXACT





interpolation flagを用いて元画像を4倍に拡大した場合。
拡大する場合にはcv2.INTER_CUBICcv2.INTER_LINEARが適しているとされており、確かに両者はモザイク感があまりなく拡大できており適切に補完されていると思われる。


元画像



cv.INTER_NEAREST



cv.INTER_LINEAR



cv.INTER_CUBIC



cv.INTER_AREA



cv.INTER_LANCZOS4



cv.INTER_LINEAR_EXACT





5. リファレンス

OpenCV > Geometric Image Transformations > resize()
OpenCV > Geometric Image Transformations > InterpolationFlags

使用したバージョン:Python 3.7.0 / OpenCV 4.0.0

0 件のコメント:

コメントを投稿