0
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 1 year has passed since last update.

セグメンテーションで分けられた部分ごとに透過png画像を生成する

Last updated at Posted at 2022-12-14

1.きっかけ

前の記事の続き

元画像の例

RGB画像

21.jpg

セグメンテーション画像

semantic-segmentation-deep-learning-review-500x375.png

2.実装

from PIL import Image
import numpy as np
# 画像ファイルを読み込む
img = Image.open("hoge_segmentation.png")
img_rgb = Image.open("hoge_rgb.jpg")

# パレットモードかどうか判定する
if img.mode != "P":
    print("画像がパレットモードではありません")
    exit()

# パレットを読み込み出力用画像を生成
palette = img.getpalette()
img_output = Image.new("RGBA", size=img.size)


# 色を取得
w, h = img.size
colors = set()
for y in range(h):
    for x in range(w):
        colors.add(img.getpixel((x,y)))
print(colors)


# outputに色ごとに出力
pixels = img_rgb.load()
for color in colors:
    for y in range(h):
        for x in range(w):
            color_pixel = img.getpixel((x, y))
            if color_pixel != color:
                r ,g, b = pixels[x,y]
                img_output.putpixel((x,y),(r, g, b, 0))
            if color_pixel == color:
                r, g, b = pixels[x,y]
                img_output.putpixel((x,y),(r, g, b, 255))

# 画像の保存
      img_output.save(f"output_sample_{color}.png")

出力結果

sample_1.png
sample_2.png
sample_3.png
sample_0.png

0
0
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
0
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?