我正试着在蟒蛇枕头上堆些图像。我想要做的是获取大量的图像(例如10),然后对每个像素,取中值,如:http://petapixel.com/2013/05/29/a-look-at-reducing-noise-in-photographs-using-median-blending/。
现在,我可以用令人难以置信的蛮力方式(使用get像素和put像素),但它需要很长的时间。
以下是我到目前为止所拥有的:
import os
from PIL import Image
files = os.listdir("./")
new_im = Image.new('RGB', (4000,3000))
ims={}
for i in range(10,100):
ims[i]={}
im=Image.open("./"+files[i])
for x in range(400):
ims[i][x]={}
for y in range(300):
ims[i][x][y]=im.getpixel((x,y))
for x in range(400):
for y in range(300):
these1=[]
these2=[]
these3=[]
for i in ims:
these1.append(ims[i][x][y][0])
these2.append(ims[i][x][y][1])
these3.append(ims[i][x][y][2])
these1.sort()
these2.sort()
these3.sort()
new_im.putpixel((x,y),(these1[len(these1)/2],these2[len(these2)/2],these3[len(these3)/2]))
new_im.show()发布于 2016-01-06 03:15:26
你可以用数组来向量化很多这样的循环。例如,np.array(im)将返回一个像素数组,其形状为(400,300,3)。所以把所有的东西都存储在一个数组中。
image_stacks = np.zeros(shape=(10, 400, 300, 3), dtype=np.uint8)
for i in xrange(image_stacks.shape[0]):
# open image file and store in variable `im`, then
image_stacks[i] = np.array(im)现在您可以用您喜欢的方式计算中值,但是numpy也有一个方法。
image_median = np.median(image_stacks, axis=0).astype(np.uint8)
image = Image.fromarray(image_median)这里需要注意的两件事是,np.median()将返回一个浮点类型数组,我们希望将其转换为无符号的int8。另一件事是,如果元素数目是偶数,则中位数是两个中间值的平均值,结果可能是奇数除以2,例如13.5。但是,当它转换为整数时,它将被舍入。这种微小的精度损失不应影响您的结果。
https://stackoverflow.com/questions/34624325
复制相似问题