5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python3】opencvで画像の品質を出来るだけ落とさず縮小する【初心者向け】

Last updated at Posted at 2021-08-02

cv2.resizeをデフォルト設定で行うと、画像の品質が劣化する。

cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]]) → dst

画像の縮小には interpolation=INTER_AREA、拡大には INTER_CUBIC(処理遅め)、またはINTER_LINER(速くて見た目もよい)を使用すると良いようだ。

[optional] flag that takes one of the following methods. INTER_NEAREST – a nearest-neighbor interpolation INTER_LINEAR – a bilinear interpolation (used by default).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. INTER_CUBIC – a bicubic interpolation over 4×4 pixel neighborhood INTER_LANCZOS4 – a Lanczos interpolation over 8×8 pixel neighborhood.

イラストだと劣化がわかりにくいため、文章のファイルを使用する。
試しに「吾輩は猫である」の冒頭をスクショ。画像として保存。

オリジナル画像(shape=(1590, 2621, 3))

neko.png

コード

from PIL import Image
import cv2

img = cv2.imread("./neko.png")
height, width = img.shape[:2]
resized_img = cv2.resize(img, (width//3, height//3))
resized_img2 = cv2.resize(img, (width//3, height//3), interpolation = cv2.INTER_AREA)

Image.fromarray(resized_img).save("./tmp.png")
Image.fromarray(resized_img2).save("./tmp2.png")

1/3に縮小 interpolation=INTER_LINEAR(デフォルト設定)の場合

tmp.png

1/3に縮小 interpolation=INTER_AREA)の場合

tmp2.png

こうしてみると、縮小の方法ひとつで画像の品質が大きく変わることがよくわかる。

5
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?