Qiita Conference 2026

【ゲスト講演】(敬称略)

及川 卓也、広木 大地、西見 公宏、みのるんなど全12名のゲストが登壇!

3
4

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.

1次元のメディアンフィルター(中央値フィルター)

3
Posted at

画像処理ではよく使われるメディアンフィルター。
OpenCVを使えば画像の2次元配列に対して
median = cv2.medianBlur(img,5)
とするだけで処理できる。

時系列データなどの1次元データにおいても外れ値がある場合,
メディアンフィルターで取り除くことができる。
1次元用のメディアンフィルターというのはnumpyにもopencvにも関数が見当たらず,
すこし工夫したのでメモ。
インデックスで各点ごとに中央値を選ぶ領域を抽出して2次元配列にしてから,
np.medianを行方向に適用している。

median.py
import numpy as np
import matplotlib.pyplot as plt

# 1次元配列に対するメディアンフィルター
# kはフィルターの大きさで奇数
def median1d(arr, k):
    w = len(arr)
    idx = np.fromfunction(lambda i, j: i + j, (k, w), dtype=np.int) - k // 2
    idx[idx < 0] = 0
    idx[idx > w - 1] = w - 1
    return np.median(arr[idx], axis=0)

# 外れ値を含む正弦波
x = np.sin(np.arange(1000) / 50)
x[np.random.randint(0, len(x), 20)] += np.random.randn(20) * 3

# フィルタリング
y = median1d(x, 5)

plt.figure(1)
plt.clf()
plt.subplot(2, 1, 1)
plt.plot(x)
plt.ylim([-3, 3])
plt.subplot(2, 1, 2)
plt.plot(y)
plt.ylim([-3, 3])

image.png

3
4
2

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

Comments

nkay
@nkay

scipy.ndimage.median_filter()を使うのはどうでしょうか。

import scipy.ndimage

y = scipy.ndimage.median_filter(x, size=5, mode='nearest')
0
a2kiti
@a2kiti

ちゃんと調べるべきでしたorz

ありがとうございます。

0

Let's comment your feelings that are more than good

Qiita Conference 2026 will be held!: 5/27(Wed) - 5/29(Fri)

Qiita Conference is Qiita's largest tech conference, dedicated to engineers in the age of AI!

Speakers

Takuya Oikawa, Tsuyoshi Ushio, Daichi Hiroki, Masahiro Nishimi, Minorun, and 12 guests in total!

View event details

Being held Article posting campaign

みんなでRubyの知見を共有しよう

2026-04-13 ~ 2026-05-10

View details
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address