Python(Numpy Array)逐像素翻转图像出现沿x=height/2镜像异常
问题原因
你代码的核心问题是直接在原数组上做覆盖赋值,没有保留原始像素值:
- 当你遍历
i从0到h-1时,前半段循环已经把上半部分的像素值替换成了下半部分的对应值,等循环到下半部分i的时候,你读取的np_array[h-1-i,j]已经是被覆盖过的新值,不是原始图像的像素,所以最终只会得到沿高度中线对称的镜像效果。 - 就算你把循环范围改成
(0, h//2),你也只做了「把上半部分像素替换为下半部分像素」的操作,没有把下半部分像素替换成原始上半部分的像素,自然结果也不对。
解决方法
方法1:修改循环逻辑
最简单的改法是提前把原始数组拷贝一份,所有像素取值都从备份的原始数组里读,再写入目标数组即可:
#import libraries import numpy as np 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) # 提前备份原始数组 origin_array = np_array.copy() #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] = origin_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')
要是不想多占内存备份数组,也可以循环前半部分的时候做像素交换,不用遍历全量像素:
for i in range(0, h//2): for j in range(0, w): # 交换上下对应位置的像素 np_array[i,j], np_array[h-1-i,j] = np_array[h-1-i,j], np_array[i,j]
方法2:直接用numpy自带的翻转操作,效率更高
numpy已经封装了垂直翻转的接口,不用自己写循环,运行速度快很多:
np_array = np.flipud(np_array)
内容的提问来源于stack exchange,提问作者Melody Mak
相关产品推荐
相关产品推荐

