内部ループロジックが間違っているが、特に、この行:
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
を作成する必要があります。ちなみに
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
を変更、しかし、注意してくださいすることができます:あなたがやるべきことはnew_row
の最後にスライスを挿入しています。 list
を渡しているときは、変更前に元の内容に変更しないでコピーしてください。ここではそのバージョンは以下のとおりです。
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]
'は動作していないようです'というのはむしろあいまいです。あなたは、あなたが見ている問題のある行動を記述することができれば、答えを得ることができます。 – retracile
numpyスライス: 'my_arr [...、:: - 1]' – JBernardo