
图像处理中,随机化像素顺序是一种常见的操作。原始代码中使用np.random.shuffle函数来实现,但效率较低。为了提升性能,开发者尝试使用生成器(generator)配合np.random.permutation,但遇到了类型转换的问题。本文将深入探讨如何利用np.random.permutation更高效地随机化图像像素,并解决将生成器转换为NumPy数组的难题。
直接使用np.random.shuffle对大型数组进行原地洗牌效率较低。一个更高效的方法是生成一个随机排列的索引数组,然后使用该索引数组重新排列原始数组。
以下是改进后的代码示例:
import numpy as np
import time
def randomize_image(img):
# convert image from (m,n,3) to (N,3)
rndImg = np.reshape(img, (-1, img.shape[2]))
np.random.shuffle(rndImg)
rndImg = np.reshape(rndImg, img.shape)
return rndImg
def randomize_image2(img):
# convert image from (m,n,3) to (N,3)
rndImg = np.reshape(img, (-1, img.shape[2]))
i = np.random.permutation(len(rndImg))
rndImg = rndImg[i, :]
rndImg = np.reshape(rndImg, img.shape)
return rndImg
# 示例用法
m, n = 1000, 1000
img = np.arange(m*n*3).reshape(m, n, 3)
start_time = time.perf_counter()
img1 = randomize_image(img)
end_time = time.perf_counter()
print('Time random shuffle: ', end_time - start_time)
start_time = time.perf_counter()
img2 = randomize_image2(img)
end_time = time.perf_counter()
print('Time random permutation: ', end_time - start_time)在这个例子中,randomize_image2 函数使用了 np.random.permutation 生成一个随机索引数组 i。然后,它使用这个索引数组来重新排列 rndImg 数组的行,从而实现像素的随机化。
从 NumPy 1.17 版本开始,NumPy 引入了新的随机数生成器 (Generator) API,它提供了更好的性能和更多的控制选项。可以利用它来进一步优化像素随机化。
import numpy as np
# 在函数外部初始化 Generator
rng = np.random.default_rng()
def randomize_image3(img):
# convert image from (m,n,3) to (N,3)
rndImg = np.reshape(img, (-1, img.shape[2]))
i = rng.permutation(len(rndImg))
rndImg = rndImg[i, :]
rndImg = np.reshape(rndImg, img.shape)
return rndImg在这个例子中,rng.permutation 代替了 np.random.permutation。 注意: rng = np.random.default_rng() 应该在函数外部初始化,避免每次调用函数时都重新初始化,从而提高效率。
原始代码中尝试使用 yield 创建生成器,但这并不是解决问题的正确方向。生成器主要用于迭代产生值,而此处的目标是直接获得随机化后的NumPy数组。因此,不需要将函数改为生成器。
通过以上方法,可以显著提升图像像素随机化的效率,并更好地理解NumPy中随机数生成的相关工具。根据图像大小和具体应用场景,选择最合适的优化策略。
以上就是快速将Generator转换为NumPy数组并优化图像像素随机化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号