简体   繁体   中英

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

I have written a code to flip an image vertically pixel-by-pixel. However, the code makes the image being mirrored along the line x = height/2.

I have tried to correct the code by setting the range of "i" from (0, h) to (0, h//2) but the result is still the same.

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')

The above given code is replacing the image pixels inplace, that is why the result is a mirrored image. If you want to flip the image pixel by pixel, just create a new array with same shape and then replace pixels in this new array. For example:

#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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM