Skip to content

Instantly share code, notes, and snippets.

@nemupm
Created October 20, 2014 11:47
Show Gist options
  • Save nemupm/72cd14572a8e00dc5382 to your computer and use it in GitHub Desktop.
Save nemupm/72cd14572a8e00dc5382 to your computer and use it in GitHub Desktop.
Median Filter
# -*- coding:utf-8 -*-
from PIL import Image
from itertools import product
class Filter:
def __init__(self, input_image):
self.input_image = input_image
self.input_pix = self.input_image.load()
self.w, self.h = self.input_image.size
def median(self):
output_image = Image.new("RGB", self.input_image.size)
output_pix = output_image.load()
# ピクセルの周辺走査用変数
W = (-1, 2)
H = (-1, 2)
# 配列の境界判定
borderX = {0: (0, 2), self.w-1: (-1, 1)}
borderY = {0: (0, 2), self.h-1: (-1, 1)}
for y, x in product(*map(xrange, (self.h, self.w))):
pixels = []
_W, _H = W, H
if not 0 < x < self.w - 1:
_W = borderX[x]
if not 0 < y < self.h - 1:
_H = borderY[y]
# x, y周辺の輝度を得る
for dx, dy in product(range(*_W), range(*_H)):
pixel = self.input_pix[x+dx, y+dy]
pixels.append(pixel)
# 輝度配列の長さ
pixlen = len(pixels)
# 色成分ごとに配列をまとめる
pixels = zip(*pixels)
# 輝度順にソートする
sorted_pixels = map(sorted, pixels)
# 中央値を得る
color = tuple(map(lambda x: x[int(pixlen/2)], sorted_pixels))
output_pix[x, y] = color
return output_image
input_img = Image.open("input.jpg")
filterInstance = Filter(input_img)
output_img = filterInstance.median()
output_img.save("output.jpg","JPEG")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment