LoginSignup
1
2

More than 5 years have passed since last update.

[python]opencvで画像を背景白の正方形にする

Posted at

用意するもの

  • 白地の画像

コード

python
import cv2
import os
import numpy as np

# 背景画像を読み込む
back_img = cv2.imread("背景画像のパス")

img = cv2.imread("正方形にしたい画像のパス")
tmp = img[:, :]
height, width = img.shape[:2]
if(height > width):
    size = height
    limit = width
else:
    size = width
    limit = height

start = int((size - limit) / 2)
fin = int((size + limit) / 2)
new_img = cv2.resize(back_img, (size, size))

if(size == height):
    new_img[:, start:fin] = tmp
else:
    new_img[start:fin, :] = tmp

# 保存する
cv2.imwrite("保存ディレクトリ" + file, new_img)

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