LoginSignup
2
2

More than 3 years have passed since last update.

【日記】OpenCVで画像の透明ピクセルだけを変換する

Last updated at Posted at 2019-07-26

画像から1ピクセルずつ取り出してアルファチャンネルをチェックし、完全に透明だったらその画素を真っ白なピクセルで置き換えます。

import cv2
import numpy as np

        img = cv2.imread(image_file_path, cv2.IMREAD_UNCHANGED)
        # 画像から透明ピクセル(アルファチャンネルが0)を抜き出し、白ピクセルで置き換える
        # np.where使いたかったけど使い方がわからんかったのです
        for y in range(img.shape[0]):
            for x in range(img.shape[1]):
                if img[y, x, 3] == 0:
                    img[y, x] = [255, 255, 255, 255]

        # jpg保存をもってアルファチャンネル削除に替える
        cv2.imwrite(dst_file_path, img)

結果は下記のようになりました。

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