【问题标题】:Eliminating number of connected pixels smaller than some specified number threshold消除小于某个指定数量阈值的连接像素数
【发布时间】:2017-12-28 19:36:46
【问题描述】:

我有一些数据,尺寸是 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)。我该怎么做?

【问题讨论】:

  • 但是我在 excel 文件中有数据。这不是图像。
  • 你有datamasked_data,如果你想从masked_data工作,看起来masked_data.fill(255)会将它转换为常规的np.array,也许你需要转换为uint8太:np.array(data, dtype=np.uint8) - 那么它应该被图像处理功能识别为灰度图像

标签: python image matplotlib plot


【解决方案1】:

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

即使您从 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")

图示结果:

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2010-10-13
    • 1970-01-01
    • 2011-02-21
    • 2018-07-18
    相关资源
    最近更新 更多