【发布时间】:2021-12-09 18:37:54
【问题描述】:
我想在图像上应用 Arnold 猫图。我从Wikipedia 管理此代码,但是当我将600 的迭代次数增加600 图像和83 迭代时它变得很慢,它花了time=567.8921346664429 秒。可以对此代码进行任何改进。我猜循环的东西让这段代码很慢,O(n^2) 每次迭代。
from PIL.Image import open as load_pic, new as new_pic
def main(path, iterations, keep_all=False, name="arnold_cat-{name}-{index}.png"):
"""
Params
path:str
path to photograph
iterations:int
number of iterations to compute
name:str
formattable string to use as template for file names
"""
title = os.path.splitext(os.path.split(path)[1])[0]
counter = 0
while counter < iterations:
with load_pic(path) as image:
dim = width, height = image.size
with new_pic(image.mode, dim) as canvas:
for x in range(width):
for y in range(height):
nx = (2 * x + y) % width
ny = (x + y) % height
canvas.putpixel((nx, height-ny-1), image.getpixel((x, height-y-1)))
if counter > 0 and not keep_all:
os.remove(path)
counter += 1
print(counter, end="\r")
path = name.format(name=title, index=counter)
canvas.save(path)
return canvas
我为我的用例修改代码,如下所示:
def cat_map(image_matrix,MAX):
dim = width, height = image_matrix.shape
transformed_matrix = np.zeros((width,height))
# Apply Arnold cat map on image_matrix
index = []
counter = 0
iterations = MAX
# collect initial index of the image_matrix
for i in range(len(image_matrix)):
for j in range(len(image_matrix[0])):
index.append([i,j])
forward_index = []
while counter < iterations:
for coordinate in index:
x = coordinate[0]
y = coordinate[1]
new_x = (2 * x + y) % width
new_y = (x + y) % height
transformed_matrix[new_x][new_y] = image_matrix[x][y]
forward_index.append([new_x,new_y])
index = forward_index
# apply recursive transformation on image_matrix
image_matrix = transformed_matrix
# only store the last index matrix
if counter != iterations - 1:
forward_index = []
# re-initialize transformation matrix
transformed_matrix = np.zeros((width,height))
counter += 1
return transformed_matrix,forward_index
我还需要最后一次迭代的index_array。我很欣赏@dankal444 的矢量化思想,但是如何存储索引数组?
【问题讨论】:
标签: python numpy performance iteration