python - 图像Python3的中值滤波器
问题描述
我想实现一个径向中值滤波器。我有以下图片(尺寸=(Nx,Ny))
我想导出每个像素的半径。对于每个半径计算中值并将其放入一个新矩阵中,以代替具有相同半径的所有像素。我发现Image Smoothing Using Median Filter,但速度不够快。我创建了自己的脚本,不幸的是,它也不快。我在一些通用数据上对其进行了测试:
import cv2
from PIL import Image
from scipy import stats, ndimage, misc
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as mpimg
from scipy import stats
a = np.array([[0.,0.,0.,0.,0.],[0.,5.,1.,9.,0.],[0.,10.,2.,10.,0.],[0.,9.,1.,5.,0.],[0.,0.,0.,0.,0.]])
b = a.copy().flatten()
y,x = np.indices((a.shape))
center = [len(x)//2, len(y)//2]
r = np.hypot(x-center[0],y-center[1])
r = r.astype(np.int) # integer part of radii (bin size = 1)
set_r = set(r.flatten()) # get the list of r without duplication
max_r = max(set_r) # determine the maximum r
median_r = np.array([0.]*len(r.flatten())) # array of median I for each r
for j in set_r:
result = np.where(r.flatten() == j)
median_r[result[0]] = np.median(b[result[0]])
a_med = median_r.reshape(a.shape)
am_med = ndimage.median_filter(a, 3)
plt.figure(figsize=(16, 5))
plt.subplot(141)
plt.imshow(a, interpolation='nearest')
plt.axis('off')
plt.title('Original image', fontsize=20)
plt.subplot(142)
plt.imshow(am_med, interpolation='nearest', vmin=0, vmax=5)
plt.axis('off')
plt.title('Median filter', fontsize=20)
plt.subplot(143)
plt.imshow(a_med, interpolation='nearest')
plt.axis('off')
plt.title('Own median', fontsize=20)
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0,
right=1)
plt.show()
我想找到一种方便的方法来解决这个问题
解决方案
我认为您想用输入图像中同一半径上的像素平均值替换图像每个圆的半径周围的所有像素。
我建议将图像变形为笛卡尔坐标,计算平均值,然后变形回极坐标。
我生成了一些大小合适的测试数据,如下所示:
#!/usr/bin/env python3
import cv2
from PIL import Image
from scipy import stats, ndimage, misc
import matplotlib.image as mpimg
from scipy import stats
import numpy as np
w, h = 600, 600
a = np.zeros((h,w),np.uint8)
# Generate some arcs
for s in range(1,6):
radius = int(s*w/14)
centre = (int(w/2), int(w/2))
axes = (radius, radius)
angle = 360
startAngle = 0
endAngle = 72*s
cv2.ellipse(a, centre, axes, angle, startAngle, endAngle, 255, 2)
这给出了这个:
Image.fromarray(a.astype(np.uint8)).save('start.png')
def orig(a):
b = a.copy().flatten()
y,x = np.indices((a.shape))
center = [len(x)//2, len(y)//2]
r = np.hypot(x-center[0],y-center[1])
r = r.astype(np.int) # integer part of radii (bin size = 1)
set_r = set(r.flatten()) # get the list of r without duplication
max_r = max(set_r) # determine the maximum r
median_r = np.array([0.]*len(r.flatten())) # array of median I for each r
for j in set_r:
result = np.where(r.flatten() == j)
median_r[result[0]] = np.median(b[result[0]])
return median_r
def me(a):
h, w = a.shape
centre = (int(h/2), int(w/2))
maxRad = np.sqrt(((h/2.0)**2.0)+((w/2.0)**2.0))
pol = cv2.warpPolar(a.astype(np.float), a.shape, centre, maxRad, flags=cv2.WARP_POLAR_LINEAR+cv2.WARP_FILL_OUTLIERS)
polmed = np.median(pol,axis=0,keepdims=True)
polmed = np.broadcast_to(polmed,a.shape)
res = cv2.warpPolar(polmed, a.shape, centre, maxRad, cv2.WARP_INVERSE_MAP)
return res.astype(np.uint8)
a_med = orig(a).reshape(a.shape)
Image.fromarray(a_med.astype(np.uint8)).save('result.png')
r = me(a)
Image.fromarray(r).save('result-me.png')
结果与您的相同,即它删除所有小于 180 度的弧并填充所有超过 180 度的弧:
但我的时间要快 10 倍:
In [58]: %timeit a_med = orig(a).reshape(a.shape)
287 ms ± 17.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [59]: %timeit r = me(a)
29.9 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
如果你很难想象我会得到什么warpPolar()
,它看起来像这样。然后我用np.mean()
平均值来降低列,即axis=0
:
关键词:Python、径向平均值、径向中值、笛卡尔坐标、极坐标、矩形、warpPolar、linearPolar、OpenCV、图像、图像处理
推荐阅读
- command-line - 将 Wetty 用于 Web 应用程序的多个用户?
- c# - 超时后更新 BotFramework 中的活动
- amazon-web-services - AWS CLI:从 Cognito Identities 获取用户详细信息
- flutter - 如何使用flutter-workmanager访问Workmanager.executeTask的回调中的单例对象
- azure - 移动或重命名时能否保留 blob 版本?
- c - 关于多个单链表的问题
- c# - 使用 Pulumi 为 Azure 应用配置增加价值
- vba - 如何在通讯录中搜索电话号码?
- python - AttributeError: 'NoneType' 对象没有属性 'roles' 添加角色时出错
- uwp - 如何访问 UWP 控件数据模板内的页面数据上下文?