LoginSignup
1
1

More than 1 year has passed since last update.

[Python]画像の余白を白埋めして正方形にする方法

Last updated at Posted at 2022-02-08

はじめに

画像を正方形にリサイズしたいとき,画像のアスペクト比を維持しようとするとどうしても上下左右のいずれかに足りない画素が生まれてしまいます.
そんなときにその余白を適当な画素で埋めて正方形の画像をつくるプログラムをOpenCVとPillowで記述しました.
余白を作る際には対象の画像が上下左右いずれにおいても中心になるようにしています.
一応リサイズするプログラムも載せていますが白埋めだけなら要らないです.

※正方形以外の画像の余白埋めには対応していません.

実際の画像変換例

変換例.jpg

コード

リサイズする

def resize (image, size):
    h, w = image.shape[:2]
    aspect = w / h
    nh = nw = size
    if 1 >= aspect:
        nw = round(nh * aspect)
    else:
        nh = round(nw / aspect)

    resized = cv2.resize(image, dsize=(nw, nh))

    return resized

白埋めする

def shiroume (image, size):
    resized = resize(image, size)

    h, w = resized.shape[:2]
    x = y = 0
    if h < w:
        y = (size - h) // 2
    else:
        x = (size - w) // 2

    resized = Image.fromarray(resized) #一旦PIL形式に変換
    canvas = Image.new(resized.mode, (size, size), (255, 255, 255)) # 黒埋めなら(0,0,0)にする
    canvas.paste(resized, (x, y))

    dst = np.array(canvas) #numpy(OpenCV)形式に戻す

    return dst

main()

import numpy as np
import cv2
from PIL import Image

image = cv2.imread('./hoge.jpg')
ume_image = shiroume(image, 600) #リサイズしたいサイズを指定
cv2.imwrite('./hogehoge.jpg', ume_image)

参考サイト

1
1
0

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
1
1