Python(Numpy 数组)- 逐像素翻转图像

Python (Numpy Array) - Flipping an image pixel-by-pixel

我编写了一个代码来逐个像素地垂直翻转图像。但是,代码使图像沿 x = height/2.

线镜像

我尝试通过将“i”的范围从 (0, h) 设置为 (0, h//2) 来更正代码,但结果仍然相同。

Original Photo Resulted Photo

#import libraries
import numpy as np

import matplotlib.pyplot as plt
from PIL import Image

#read image (set image as m)
m = Image.open('lena.bmp')

#change image to array (set array as np_array)
np_array = np.array(m)

#define the width(w) and height(h) of the image
h, w = np_array.shape

#make the image upside down
for i in range(0,h):
    for j in range(0,w):
        np_array[i,j] = np_array[h-1-i,j]
        
#change array back to image (set processed image as pil_image)
pil_image = Image.fromarray(np_array)

#open the processed image
pil_image.show()

#save the processed image
pil_image.save('upsidedown.bmp')

上面给出的代码是在原地替换图像像素,这就是结果是镜像图像的原因。 如果你想逐像素翻转图像,只需创建一个具有相同形状的新数组,然后替换这个新数组中的像素。例如:

#import libraries
import numpy as np

import matplotlib.pyplot as plt
from PIL import Image

#read image (set image as m)
m = Image.open('A-Input-image_Q320.jpg')

#change image to array (set array as np_array)
np_array = np.array(m)
new_np_array = np.copy(np_array)

#define the width(w) and height(h) of the image
h, w = np_array.shape

#make the image upside down
for i in range(0,h):
    for j in range(0,w):
        new_np_array[i,j] = np_array[h-1-i,j]
        
#change array back to image (set processed image as pil_image)
pil_image = Image.fromarray(new_np_array)

#open the processed image
pil_image.show()

#save the processed image
pil_image.save('upsidedown.bmp')