python - 将 RGBA numpy 数组转换为二进制 2d numpy 数组

标签 python image numpy python-imaging-library rgba

我已经使用 Pillow 将图像加载为 numpy 数组,生成的 numpy 数组的尺寸为 (184, 184, 4),即它是一个 184x184 像素图像,每个像素都具有 RGBA 尺寸。

出于所有实际目的,我的应用程序只需要知道像素是否为黑色,因此我只需要一个包含 0、1 的 184x184 np 数组。

我是 numpy 的新手,特别是图像处理新手,想知道是否有更快的方法来做到这一点。

我尝试了在循环中检查每个像素的简单实现,这似乎成本太高。

最佳答案

如果我理解正确的话,你有一个形状为 (184,184,4) 的数组,并且你想获得一个形状为 (184,184) 的 bool 数组,具体取决于最终维度是否等于 [0,0,0,0]

image = np.random.randint(0, 255, size=(184, 184, 4)) #Generate random image
isBlack = np.int64(np.all(image[:, :, :3] == 0, axis=2))

完成!

但是它是如何工作的呢?看起来就像魔法一样! Numpy 有点神奇。这就是我们喜欢它的原因。在这种情况下:

  • 根据每个数字是否等于 0,将 image==0 转换为 (184,184,4) bool 数组
  • 在本例中,我们使用 image[:,:,:3] 从方程中排除第四个数字
  • np.all 询问所有元素是否都等于 0。
  • axis 参数更改它所查看的轴,请记住 python 从 0 开始计数,因此第三个轴是数字 2。

关于python - 将 RGBA numpy 数组转换为二进制 2d numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40638611/

相关文章:

android - 延迟加载列表 - 这里需要一点帮助

image - React 和 Webpack : Loading and displaying images as background-image

python - 连接两个 NumPy 数组得到 "ValueError: all the input arrays must have same number of dimensions"

javascript - Flask Dynamic 依赖下拉列表

python - 有没有用 wxPython 开发过流行的桌面应用程序?

php - 使用 PHP 创建透明 png 文件

python - 从 HTTP 链接加载 .npz

python - 我怎样才能找到数据中存在弯曲/剪切的点?

python - 正则表达式 : Remove last period in string that can contain other periods (dig output)

python搜索技术: word similarity