【问题标题】:Python - Find First and Last white pixels coordinatesPython - 查找第一个和最后一个白色像素坐标
【发布时间】:2018-08-19 04:04:58
【问题描述】:

我在 python 编码一个遍历图像中所有像素的循环方面需要帮助。我需要找到所有白色像素并保存检测到的第一个像素和最后一个像素的坐标。该图像是一个阈值图像(只有白色和黑色像素)。我做了一个嵌套循环,但我不知道如何进行评估。

【问题讨论】:

  • 您可能不需要循环,但您能显示您正在使用的数组类型吗?例如,一个具有随机“白色”和“黑色”像素的 5x5 阵列,其格式与您正在使用的真实像素相同?你想要的输出呢?

标签: python loops numpy image-processing iteration


【解决方案1】:

如果您愿意,可以使用嵌套循环来实现,但这会很慢而且很笨重。我建议使用 numpy 内置的优化方法

假设您的图像是一个二维numpy 数组,黑色值为0,白色值为255,如下所示:

image = np.random.choice([0,255], size=(10,10), p=[0.8, 0.2])

>>> image
array([[  0,   0, 255,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0, 255,   0],
       [  0,   0,   0, 255,   0,   0,   0,   0,   0,   0],
       [  0, 255,   0, 255, 255,   0,   0,   0, 255, 255],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [255,   0,   0,   0, 255,   0,   0,   0,   0,   0],
       [  0, 255, 255,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [255, 255,   0,   0, 255, 255, 255, 255,   0, 255]])

您可以像这样找到白色值(值等于 255)的第一个和最后一个坐标:

white_pixels = np.array(np.where(image == 255))
first_white_pixel = white_pixels[:,0]
last_white_pixel = white_pixels[:,-1]

导致:

>>> first_white_pixel
array([0, 2])
>>> last_white_pixel
array([9, 9])

或者,作为一个班轮:

first_white_pixel, last_white_pixel = np.array(np.where(image == 255))[:,[0,-1]].T

【讨论】:

  • 谢谢!!这是完美的,正是我需要的,甚至更好,因为经过优化。
  • 很高兴它有帮助!
猜你喜欢
  • 2012-06-11
  • 2023-03-09
  • 2019-08-12
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多