内部循环逻辑是错误的,但特别是这一行:
image[c:c+3], image[-c-3: -c] = image[-c-3: -c], image[c:c+3]
您正在image
就地更改变量,但您似乎忘记了行变量r
。所以现在,你正在改变行。你的负面切片有点不对劲。因为c=0
,你会得到image[-3:0]
,这不是一个有效的切片,它会返回[]
。
image
但是从您的代码来看,您并不是要就地更改,而是要创建new_image
. 你应该做的是在末尾插入切片new_row
:
def horizontal_flip(image):
rows = len(image)
cols = len(image[0])
new_image = []
for r in range(rows):
new_row = []
for c in range(0,cols,3):
new_row = image[r][c:c+3] + new_row
new_image.append(new_row)
return new_image
顺便说一句,您也可以image
就地更改,但要小心。当您传递 alist
时,您应该在更改之前复制它,以便原件保持不变。这是那个版本:
def horizontal_flip(image):
cols = len(image[0])/3
#make a copy so that original image is not altered
image = [row[:] for row in image]
for row in image:
for c in range(int(cols/2)): # int() is not needed for Python 2.x, since integer division yields integer
# This also takes care of odd n cases, middle chunk is not changed.
row[3*c:3*c+3], row[3*(cols-c-1):3*(cols-c-1)+3] = row[3*(cols-c-1):3*(cols-c-1)+3], row[3*c:3*c+3]
return image
这也可以通过单行的列表理解来完成,但它的可读性会降低。如果你愿意,你可以这样做:
from itertools import chain
flipped_image = [list(chain(*[row[3*i:3*i+3] for i in range(len(image[0])/3-1,-1,-1)])) for row in image]