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 1 year has passed since last update.

【画像処理】NumpyでMedianフィルター

Posted at

NumpyでMedianフィルターを実装してみます。
Medianフィルターはある画素について、その画素と近傍画素の中央値を出力するフィルターです。ノイズ除去などに利用されます。

まず、使用する画像を読み込み、グレースケール画像に変換しておきます。

original_image = plt.imread(image_name)
if np.issubdtype(original_image.dtype, np.integer):
  original_image = original_image / np.iinfo(original_image.dtype).max
gray_image = 0.2116 * original_image[:,:,0] + 0.7152 * original_image[:,:,1] + 0.0722 * original_image[:,:,2]
plt.imshow(gray_image, cmap='gray')

GrayImage.png

ノイズを付与します。

from numpy import random

noise_image = gray_image.copy()
noise_image[random.choice([True, False], size=noise_image.shape, p=[0.05, 0.95])] = 1.0
plt.imshow(noise_image, cmap='gray')

NoiseImage.png

ノイズを付与した画像にMedianフィルターを適用します。

def median_filter(image, size=(3, 3), boundary='edge'):
  pad_image = np.pad(image, ((int(size[0] / 2),), (int(size[1] / 2),)), boundary)
  shape = (image.shape[0] - size[0] + 1, image.shape[1] - size[1] + 1) + size
  strides = image.strides * 2
  strided_image = np.lib.stride_tricks.as_strided(image, shape, strides).reshape(shape[0], shape[1], size[0] * size[1])
  return np.apply_along_axis(lambda a: np.median(a), 2, strided_image)

median_image = median_filter(noise_image)
plt.imshow(median_image, cmap='gray')

MedianImage.png


実装したコードはGoogle Colaboratoryに置いてあります。

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?