Skip to main content
 首页 » 编程设计

python之从 numpy 数组中删除连续的数字

2024年12月31日8powertoolsteam

我是 python 的新手,但我对我正在尝试做的这个项目真的很困惑。我有一张图片显示 here .我想要做的是找到图像中像素范围从 0 到 255 的所有正方形的平均值。下面的代码显示了我用来计算图片值的方法。出现的问题是像素/正方形的大小不一样,有些比另一个大。例如,在一个实例中,当查看初始图片的一部分时 here ,正方形都相等,因此数组都相等。然而在this图片,我们可以看到右边的方 block 比左边的小。

我正在考虑从原始数组创建一个子数组,其中忽略任何重复的值。例如如下所示:

1 1 1 2 2 1 2 
1 1 1 2 2 1 2 
1 1 1 2 2 1 2 
1 1 1 2 2 1 2 
3 3 3 4 4 1 2 
3 3 3 4 4 1 2 
5 5 5 6 6 1 2 
7 7 7 8 8 1 2 
7 7 7 8 8 1 2 
 
to  
 
1 2 1 2 
3 4 1 2 
5 6 1 2 
7 8 1 2 

我尝试使用以下方法:

1. unique_rows = np.unique(data, axis=0) 
2. unique_columns = np.unique(unique_rows, axis=1) 

将所有不重复的行从原始数组中显示到一个新数组中,然后使用第二个代码从新数组中获取所有不重复的列。不幸的是,这样做是为了摆脱所有重复的值。我想要的只是摆脱重复的连续值。

我真的不知道该怎么做请帮忙!

代码:

from PIL import Image 
import numpy as np 
 
img = Image.open('greyscale.png').convert('L')  # convert image to 8-bit grayscale 
WIDTH, HEIGHT = img.size 
 
data = list(img.getdata()) # convert image data to a list of integers 
# convert that to 2D list (list of lists of integers) 
data = np.array ([data[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)]) 
 
#unique_rows = np.unique(data, axis=0) 
#unique_columns = np.unique(unique_rows, axis=1) 
 
# At this point the image's pixels are all in memory and can be accessed 
# individually using data[row][col]. 
 
# For example: 
#print data 
for row in data: 
    print(' '.join('{:3}'.format(value) for value in row)) 
 
print np.mean(data) 

请您参考如下方法:

我检查了此解决方案是否适用于您的整个图像而不是那个小样本,它确实有效。
我将为那个小数组举一个例子:

import numpy as np 
 
x = np.array([[1, 1, 1, 2, 2, 1, 2], 
              [1, 1, 1, 2, 2, 1, 2], 
              [1, 1, 1, 2, 2, 1, 2], 
              [1, 1, 1, 2, 2, 1, 2], 
              [3, 3, 3, 4, 4, 1, 2], 
              [3, 3, 3, 4, 4, 1, 2], 
              [5, 5, 5, 6, 6, 1, 2], 
              [7, 7, 7, 8, 8, 1, 2], 
              [7, 7, 7, 8, 8, 1, 2]]) 
 
rows_mask = np.insert(np.diff(x[:, 0]).astype(np.bool), 0, True) 
columns_mask = np.insert(np.diff(x[0]).astype(np.bool), 0, True) 
 
print(x[np.ix_(rows_mask, columns_mask)]) 

给出:

[[1 2 1 2] 
 [3 4 1 2] 
 [5 6 1 2] 
 [7 8 1 2]] 

从这里您可以计算平均值。


关于获取 rows_mask 和 columns_mask 你可以在这里阅读:Remove following duplicates in a numpy array .
另外,请注意没有 np.ix_仅返回对角线元素:Boolean array indexing