python - 如何使用 numpy 有效地初始化数组的一部分?
问题描述
我想弄清楚我是否可以使用 numpy 有效地将 3 维数组的区域设置为一个值。我的数组是具有 3 个颜色通道的黑色图像,我想将图像中一组像素周围的区域设置为某种颜色。
我的工作但缓慢的代码是这样的(提取的相关部分):
import skimage
import numpy as np
def clamp(n, upper, lower=0):
return max(lower, min(n, upper))
def apply_contours(image, contours, color=(128.0,128.0,128.0), radius=5):
"""Draw the pixels in the contours in a given colour and size
"""
for contour in contours:
for pixel in contour:
r1 = clamp(int(pixel[0])-radius, image.shape[0])
r2 = clamp(int(pixel[0])+radius, image.shape[0])
c1 = clamp(int(pixel[1])-radius, image.shape[1])
c2 = clamp(int(pixel[1])+radius, image.shape[1])
for y in range(r1,r2):
for x in range(c1,c2):
for c in range(3):
image[y][x][c] = color[c]
return image
input = skimage.io.imread("image.png")
contours = skimage.measure.find_contours(input, 0.5)
mask = np.zeros((input.shape[0],input.shape[1],3), dtype=np.uint8)
apply_contours(mask)
我没有太多使用 numpy,但我想到我应该可以通过用apply_contours
类似这样的东西替换嵌套循环来加快速度:
image[r1:r2][c1:c2] = np.array([color[0],color[1],color[2])
但这似乎不起作用,因为生成的图像确实显示了任何变化,而循环版本显示了我的期望。
我也试过:
image[r1:r2][c1:c2][0] = color[0]
image[r1:r2][c1:c2][1] = color[1]
image[r1:r2][c1:c2][2] = color[2]
但这给了我一个错误IndexError: index 0 is out of bounds for axis 0 with size 0
。
是否有可能用 numpy 更有效地做我想做的事情?
解决方案
我想通了,我在 numpy 的总 n00b 状态。正确的语法是:
image[r1:r2,c1:c2] = np.array([color[0],color[1],color[2])
推荐阅读
- javascript - 如何在 github 和 prisma 中使用 next-auth
- excel - 在 UserForm 中使用 Friendly_Name 显示链接
- ios - 在 swiftui 中选择路径
- python - 我想在python中将数字转换为确切的日期
- excel - Excel VBA 格式化 InputMessage 文本显示
- c - c 用 cairo 和 cups 打印更多页面
- python - vscode:在调试控制台中评估多个选定的行会导致缩进错误(使用 python 类)
- elasticsearch - 在 ElasticSearch 的另一个字段中复制一个字段的数据
- python - Numpy 沿轴卷积 2 个二维数组
- javascript - 处理 javascript fetch 中的服务器端错误