python - Numpy:有效地将满足条件的所有像素设置为黑色
问题描述
我需要将满足某些条件的所有像素更改为黑色。我的快速解决方案是迭代每个像素。我的应用程序对性能很敏感,并且比要求的要慢。它循环的图像尺寸非常小,从大约 25x25 到 50x50 不等。
我已经提供了一个我正在做的例子。如果图像加载或宽度/高度部分有任何错误,我们深表歉意。
image = cv2.imread("image.png")
width, height = image.shape
for x in range(width):
for y in range(height):
blue = image[x, y, 0]
green = image[x, y, 1]
red = image[x, y, 2]
if (abs(green - blue) > 20 and green > 30) or abs(red - green) < 40:
output[x, y] = [0, 0, 0]
解决方案
使用矢量化操作和掩码 -
import numpy as np
# Convert to int datatype, as we want to avoid overflow later on
image_int = image.astype(int)
# Split up the channels
B,G,R = image_int.transpose(2,0,1)
# Or image_int[...,0],image_int[...,1],image_int[...,2]
# Use numpy.abs and 2D sliced data to get 2D mask
mask = mask = ((np.abs(G - B) > 20) & (G>30)) | (np.abs(R - G) < 40)
# Use the mask to assign zeros into o/p with boolean-indexing
output[mask] = [0,0,0]
推荐阅读
- nativescript - Spawn 发布到 Apple Store 失败的问题
- android - 如何在一封电子邮件中发送附件+邮件正文
- excel - VBA / Excel:如何允许用户使用下拉选项添加新行
- java - Hibernate & JPA“mappedBy”与关系和级联的所有者
- android - 标题在底部导航视图中对齐
- matlab - 无法遍历结构 matlab 的字段
- reactjs - 从类名中反应设置显示名的类装饰器
- mysql - Grails id 映射自动增量 - MySQL
- ios - 有没有办法将“NSDate.timeIntervalSinceReferenceDate”转换为像 Firebase 这样的字符串?
- elasticsearch - 通过在弹性搜索中将 url 作为文档的输入来搜索单词