
本文将介绍如何利用NumPy高效地随机化图像像素,重点在于避免使用较慢的 np.random.shuffle 方法,并提供更优的替代方案。
直接使用 np.random.shuffle 对大型数组进行随机化可能效率较低。一种更高效的方法是生成一个随机排列的索引数组,然后使用这些索引来重新排列原始数组。以下是一个示例函数:
import numpy as np
import time
def randomize_image(img):
# convert image from (m,n,3) to (N,3)
# Note "-1" means "whatever size is necessary"
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)
img1 = randomize_image(img)
start_time = time.perf_counter()
randomize_image(img)
end_time = time.perf_counter()
print('Time random shuffle: ', end_time - start_time)
img2 = randomize_image2(img)
start_time = time.perf_counter()
randomize_image2(img)
end_time = time.perf_counter()
print('Time random permutation: ', end_time - start_time)在这个例子中,randomize_image2 函数首先将图像重塑为一个二维数组,其中每一行代表一个像素。然后,它使用 np.random.permutation 生成一个随机排列的索引数组 i。最后,它使用这个索引数组来重新排列像素,并将结果重塑回原始图像的形状。
对于更大的图像,使用 NumPy 的 Generator 可能会带来额外的性能提升。NumPy Generator 提供了一种更现代、更灵活的方式来生成随机数。
# include this outside of the function
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
# 示例使用
m, n = 1000, 1000
img = np.arange(m*n*3).reshape(m, n, 3)
img3 = randomize_image3(img)
start_time = time.perf_counter()
randomize_image3(img)
end_time = time.perf_counter()
print('Time random permutation with Generator: ', end_time - start_time)在这个例子中,我们首先创建了一个 NumPy Generator 对象 rng。然后,在 randomize_image3 函数中,我们使用 rng.permutation 代替 np.random.permutation 来生成随机排列的索引数组。
通过使用 np.random.permutation 和 NumPy Generator,可以显著提升图像像素随机化的速度。这些方法在处理大型图像时尤其有效。根据图像的大小和您的具体需求,选择最合适的方案可以帮助您优化性能。避免直接使用 np.random.shuffle,并考虑使用索引重排的方式来实现更快的随机化。
以上就是快速将图像像素随机化的NumPy方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号