0
1

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.

カラー画像を白黒や5色のみで描画する

Last updated at Posted at 2023-05-07

環境

実行環境:Google Colaboratory
言語:Python3

経緯

アート画像を作成する前段階として、この処理が必要であったため作成した。

カラー画像を5色のみで再度描画する

Before①

ex.png

After①

output.jpg

Before②

ダウンロード.jpeg

After②

ダウンロード (1).jpg

コード

from google.colab import files
import io
import cv2
import numpy as np
from IPython.display import Image

import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont

# 画像のアップロード
uploaded = files.upload()

# アップロードされた画像の読み込み
uploaded_file_name = next(iter(uploaded))
img = cv2.imread(uploaded_file_name)

# 画像の高さと幅を取得
height, width, _ = img.shape

# RGBの平均値を算出し、画像を5色に分割する
img_colors = np.zeros((height, width, 3), np.uint8)

for i in range(height):
    for j in range(width):
        # RGBを抽出
        b,g,r = img[i][j]

# 赤の定義は、R成分がG成分とB成分よりも大きく、かつ、R-Gが30以上であり、R-Bが30以上であること。他も同様
        if r > g and r > b and (r - g) > 30 and (r - b) > 30:
            img_colors[i][j] = [0, 0, 255]  # 赤
        elif g > r and g > b and (g - r) > 30 and (g - b) > 30:
            img_colors[i][j] = [0, 255, 0]  # 緑
        elif b > r and b > g and (b - r) > 30 and (b -g) > 30:
            img_colors[i][j] = [255, 0, 0]  # 青
        elif r > 180 and g > 180 and b > 180:
            img_colors[i][j] = [255, 255, 255]  # 白
        else:
            img_colors[i][j] = [0, 0, 0]  # 黒
            
# 出力
cv2.imwrite('output.jpg', img_colors)

# 出力画像の表示
display(Image(filename='output.jpg'))

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?