LoginSignup
4

More than 1 year has passed since last update.

posted at

updated at

Organization

[Python+OpenCV]画像の透過部分を白塗する

はじめに

画像の透過部分を白塗するプログラムのサンプルです。
ネットで調べてみると、for文でピクセルを走査したり、RGBを取得した後にαチャンネルを結合する方法が散見されました。
そのような複雑な処理をすることなく数行で実装できたので、自分用のメモも兼ねて記事に残しておきます。

環境

  • Python 3.7.7
  • opencv_python 4.4.0.42
  • numpy 1.18.1

実行例

以下の透過済み画像を黒塗りします(白塗りだと変化がわからないため)。
output.png

ソースコード

# -*- coding:utf-8 -*-
import cv2
import numpy as np

# 入力画像を読み込み(-1指定でαチャンネルも読み取る)
img = cv2.imread("kangaru.png", -1)
# αチャンネルが0となるインデックスを取得
# ex) ([0, 1, 3, 3, ...],[2, 4, 55, 66, ...])
# columnとrowがそれぞれ格納されたタプル(長さ2)となっている
index = np.where(img[:, :, 3] == 0)
# 白塗りする
img[index] = [255, 255, 255, 255]
# 出力
cv2.imwrite("output.png", img)

おわりに

αチャンネルの取得も、透過部分の白塗りも簡単に実装できましたね。

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
What you can do with signing up
4