消除小于某个指定数量阈值的连接像素数

问题描述 投票:0回答:1

我有一些数据,尺寸是249X250。我使用以下代码绘制数据:

import numpy as np

import pandas as pd

import matplotlib.pyplot as pl

data = pd.read_excel("sample_data.xlsx")

x = np.arange(data.shape[0])

y = np.arange(data.shape[1])

mask_data = np.ma.masked_outside(data,0,233)


pl.contourf(y,x,mask_data)

pl.colorbar()

情节是这样的:

现在我想删除绘图右侧的较小补丁,并希望仅保留最大的补丁。为此,我的逻辑是移除连接像素数小于某个指定阈值的连接像素(为此目的,它为200)。我怎样才能做到这一点?

python image matplotlib plot
1个回答
2
投票

基本上您要做的是识别图像中的所有对象。这可以通过ndimage.measurements.labelscipy.来完成。实质上,它在图像中搜索连续的像素组并为它们分配标签。然后,您可以遍历这些标记的扇区并计算对象的大小(以像素为单位)并在此基础上进行过滤。

即使您从Excel中提取数据 - 您实际拥有的是您正在绘制的249x250像素“图像”。 Excel中的每个单元格实际上都是包含值的“像素”。为了将这一点推向家庭,您可以完全使用matplotlib中的图像显示功能(例如plt.imshow

import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

xn = 250
yn = 249

# fake data to illustrate that images are just matrices of values
X = np.stack([np.arange(xn)] * yn)
Y = np.stack([np.arange(yn)] * xn).transpose()
Z = np.sin(3*np.pi * X/xn) * np.cos(4*np.pi * Y/yn) * np.sin(np.pi * X/xn)
Z[Z <.5] = 0

fig,axes = plt.subplots(1,2)
axes[0].contourf(Z)
axes[0].set_title("Before Removing Features")

# now identify the objects and remove those above a threshold
Zlabeled,Nlabels = ndimage.measurements.label(Z)
label_size = [(Zlabeled == label).sum() for label in range(Nlabels + 1)]
for label,size in enumerate(label_size): print("label %s is %s pixels in size" % (label,size))

# now remove the labels
for label,size in enumerate(label_size):
    if size < 1800:
        Z[Zlabeled == label] = 0

axes[1].contourf(Z)
axes[1].set_title("After Removing Features")

插图结果:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.