【问题标题】:How to avoid 'for' loop in numpy array如何避免 numpy 数组中的“for”循环
【发布时间】:2020-02-15 03:49:24
【问题描述】:

我正在研究用光学显微镜等拍摄的一些合金微观结构的灰度图像。我的目标是分析具有给定阈值(像素数)的区域的数量(%),以及数量、大小等. 这些部分。最后我使用:from skimage import measure,morphology,它找到这些段,每个段在标签矩阵中都有唯一的整数,其形状与 pic 相同。我可以做所有事情,除了在没有for 循环的情况下为原始图像上的这些片段着色..

import numpy as np
import matplotlib.pyplot as plt

grains = np.array([[1,3], [2,5], [6,2]] )

labels=np.array([[1,1,0,0,0],[1,0,0,2,0],[0,0,2,2,2],[0,0,0,2,0],[6,6,0,0,0]])

im = np.array([[223, 222, 225, 224, 227],[222, 224, 218, 220, 221],[216, 221, 219, 223, 225],[228, 226, 231, 224, 228],[226, 228, 225, 218, 225]])

image=np.stack((im, im, im), axis=2)       # greyscale sample image

color = [0, 0, 255]                        # rgb blue color

for i in grains:
    B=np.full((i[1],3), color).astype('int')
    image[labels==i[0]]=B

plt.imshow(image)
plt.show()

是否有任何有效的“numpy 方式”,它不包含“for”循环,因此会更快。

【问题讨论】:

  • 你能帮我理解grains吗?这些数字对代表什么,它们来自哪里?我还想检查一下:这段代码的输出是你想要的吗?我的意思是,问题是关于获得相同的输出但没有循环?
  • grains 中的每个项目都与一个段相关,称为 i,其中 i[0] 是其唯一的“序列”号,而 i[1] 是其面积(像素数)..
  • 啊,好吧,现在说得通了。干杯!

标签: python image numpy matplotlib scikit-image


【解决方案1】:

如果输出已经正确,那么您可以将标记为labels 的像素变为蓝色,如下所示:

import numpy as np
import matplotlib.pyplot as plt

labels = np.array([[1,1,0,0,0],
                   [1,0,0,2,0],
                   [0,0,2,2,2],
                   [0,0,0,2,0],
                   [6,6,0,0,0]])

im = np.array([[223, 222, 225, 224, 227],
               [222, 224, 218, 220, 221],
               [216, 221, 219, 223, 225],
               [228, 226, 231, 224, 228],
               [226, 228, 225, 218, 225]])

image = np.stack((im, im, im), axis=2)
image[labels >= 1] = [0, 0, 255]

plt.imshow(image)

这给出了相同的输出:

但您似乎正在尝试做其他事情——因此label = 1 看起来与label = 2 不同。如您所见,我根本没有使用grains。如果您可以解释您希望最终图像的外观,那么几乎可以肯定有一种方法可以不使用循环。

【讨论】:

  • 非常感谢!是的,这就是解决方案。我在没有谷物的情况下朝这个方向尝试,但没有成功:) 一切顺利!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多