Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created March 16, 2025 00:52
Show Gist options
  • Save kujirahand/4046faff40ff292ed7de48030b35161a to your computer and use it in GitHub Desktop.
Save kujirahand/4046faff40ff292ed7de48030b35161a to your computer and use it in GitHub Desktop.
ノイズ付き画像セピアフィルタ
from random import randint
from PIL import Image, ImageEnhance, ImageOps, ImageFilter, ImageDraw
from pillow_heif import register_heif_opener
import TkEasyGUI as eg
# HEICが読めるように登録
register_heif_opener()
# 画像オブジェクトにセピアフィルタを適用する
def sepia_filter(image):
# コントラストと彩度を下げる
image = ImageEnhance.Contrast(image).enhance(0.9)
image = ImageEnhance.Color(image).enhance(0.4)
# セピアフィルタを適用する
gray = ImageOps.grayscale(image)
sepia = ImageOps.colorize(gray, "#442211", "#FFCCC1")
return sepia
# ランダムにピクセルの情報を変更する
def add_noise1(image):
width, height = image.size
pixels = image.load()
for _ in range(int(width * height * 0.02)): # 画像の2%のピクセルを変更
x = randint(0, width - 1)
y = randint(0, height - 1)
r, g, b = pixels[x, y]
noise = randint(-30, 30) # ノイズの範囲
pixels[x, y] = (
max(0, min(255, r + noise)),
max(0, min(255, g + noise)),
max(0, min(255, b + noise)),
)
# ぼかし効果を加える
image = image.filter(ImageFilter.GaussianBlur(radius=4))
return image
# 黒い染みをランダムに描画する
def add_noise2(image):
width, height = image.size
layer = Image.new("RGBA", image.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(layer)
for _ in range(int(width * height * 0.00001)):
x = randint(0, width)
y = randint(0, height)
size = randint(5, 35)
draw.ellipse((x, y, x + size, y + size), fill=(0, 0, 0, randint(50, 100)))
layer = layer.filter(ImageFilter.GaussianBlur(radius=4))
image.paste(layer, (0, 0), layer)
return image
if __name__ == "__main__":
filename = eg.popup_get_file()
if filename is not None:
# ファイルから画像を読む
image = Image.open(filename)
image = sepia_filter(image)
image = add_noise1(image)
image = add_noise2(image)
# 結果を保存
image.save(filename + "-output.jpg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment