如何从Numpy Array中删除/删除异常值

问题描述 投票:0回答:1

我有一个代码编写平均多个图像来检索背景,这基本上删除了图像中的移动对象。我一直试图在平均之前删除异常值,这样我才能得到背景而不是得到褪色的对象。我尝试了一些技巧,最近的一个是这样的:

#!/usr/bin/env python3

import numpy as np
from PIL import Image
from scipy import stats

# Load images
im0 = np.array(Image.open('test1/1.jpg'))
im1 = np.array(Image.open('test1/2.jpg'))
im2 = np.array(Image.open('test1/3.jpg'))

# Stack the 3 images into a 4d sequence
sequence = np.stack((im0, im1, im2), axis=3)

mean = np.mean(sequence, axis=3)
sd = np.std(sequence, axis=3)

finalSequence = [x for x in sequence if (x > mean - 2 * sd)]
finalSequence = [x for x in finalSequence if (x < mean + 2 * sd)]

# Repace each pixel by mean of the sequence
result = np.mean(finalSequence, axis=3).astype(np.uint8)

# Save to disk
Image.fromarray(result).save('result.png')

这给了我一个错误:

final_list = [x for x in sequence if (x > mean - 2 * sd)]
ValueError: operands could not be broadcast together with shapes (474,3,3) (266,474,3) 

任何帮助或解决方法这样做将不胜感激。谢谢!

python numpy image-processing computer-vision python-imaging-library
1个回答
0
投票

没有安装软件包就很难调试。您的操作不起作用,因为阵列具有不同的形状numpy shapes。您可以使用以下方式查看

print(x.shape)
print(mean.shape)
print(sd.shape)

您还可以将均值/ sd与np.ones(sequence.shape)相乘,然后比较整个数组而不是循环它们(应该更有效)

mean_vec = mean * np.ones(sequence.shape)
sd_vec = sd * np.ones(sequence.shape)
sequence > (mean_vec - 2 * sd_vec)
© www.soinside.com 2019 - 2024. All rights reserved.