Understanding Python Range Functions

Asked 2 years ago, Updated 2 years ago, 19 views

#coding:utf-8

import Image as img
import numpy as np
import matplotlib.pyplot asplt

img=np.array(img.open("a.png"))

width=img.shape[0]
height=img.shape[1]

for i in range (height+1):
    for jin range (width+1):
        img[i][j]=img[i][width]-img[i][j]

plt.imshow(img)
plt.show()

I'm a beginner at python, but I wrote a code to flip the image from side to side.

img[i][j]=img[i][width]-img[i][j]
IndexError: index512 is out of bounds for axis0 with size512

The error appears.
By the way, the image is a color image with width=height=512.
I somehow understand what the error is saying, but how can I fix it?

python

2022-09-30 19:07

1 Answers

heightHeight and widthwidthI think I gave you the initial value in reverse.Try the following:

import numpy as np
import matplotlib.pyplot asplt

img=np.array(img.open("a.png"))
plt.imshow(img)
height=img.shape[0]
width=img.shape[1]

for i in range (height):
    for jin range (width):
        img[i][:]=img[i][::-1]

plt.imshow(img)
plt.show()

Generally speaking, if you want the array a to be reverse order, I think a[:-1] is faster.


2022-09-30 19:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.