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 5 years have passed since last update.

Pythonでカラーフィルムを再現してみる

Last updated at Posted at 2019-12-01

作りたいもの

今回作成しようと考えているのは,カメラに取り付けるような画像全体の色調を変えるフィルムです.Numpyモジュールを使えば3簡単に原色のフィルムを作れるのですが,汎用性を高めて全部の色に対応させようと考えました.

元画像

sample.jpg

完成品

from PIL import Image
import numpy as np

def color_filter(img_source, rgb):
    #実数配列に変換
    img_source=np.array(img_source, dtype='float16')
        
    #フィルムRGBは0~255
    if max(rgb)>255 or min(rgb)<0:
        return Image.fromarray(np.unit8(img_source))
    
    #RGBフィルムを適用
    img_source[:,:,0]*=rgb[0]/255
    img_source[:,:,1]*=rgb[1]/255
    img_source[:,:,2]*=rgb[2]/255
            
    #Imageクラスに変換後出力
    img_out=Image.fromarray(np.uint8(img_source))
    return img_out

仕組み

各ピクセルのRGBの値にフィルムのRGBの255(RGB最大値)に対する割合を掛けています.
色の範囲は元の画像から真っ黒まで変更可能です.真っ黒の時のフィルムは要は壁ですね.

実行結果

フィルムカラー:RGB(100,255,100)
sample_out2.jpg
フィルムカラー:RGB(173,216,230)
sample_out2-2.jpg

失敗作

割合ではなく,フィルタの値との平均をとれば行けるかもと初めに思ったのでその結果も載せておきます.壁が再現できなかったので失敗作といたします.

from PIL import Image
import numpy as np

def color_filter2(img_source, rgb):
    img_source=np.array(img_source, dtype="float16")
        
    #フィルムRGBは0~255
    if max(rgb)>255 or min(rgb)<0:
        return Image.fromarray(np.unit8(img_source))
    
    #RGBフィルムを適用
    img_source[:,:,0]+=rgb[0]
    img_source[:,:,0]/=2.0
    img_source[:,:,1]+=rgb[1]
    img_source[:,:,1]/=2.0
    img_source[:,:,2]+=rgb[2]
    img_source[:,:,2]/=2.0
    
            
    #Imageクラスに変換後出力
    return Image.fromarray(np.uint8(img_source))

実行結果

フィルムカラー:RGB(100,255,100)
sample_out2-1.jpg
フィルムカラー:RGB(173,216,230)
sample_out2-2.jpg
壁:RGB(0,0,0)
sample_out2-3.jpg
やはり全体的に白みがかってますね.

まとめ

どちらとも需要はあると思うので,色々とお試しください.画像認識のデータ水増しにでも使用していただけると嬉しいです.
(追記)なぜかスライス記法を忘れていた時のコードを貼っていました... 現在貼っているのはより軽量化されたものです.

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?