需要在25x25网格中找到五个相邻数字的最大和

2024-09-22 20:23:21 发布

您现在位置:Python中文网/ 问答频道 /正文

import numpy as np
Bees = open("BeesData.txt", "r")
Bees = Bees.read()
Bees = Bees.split( )
for i in range(0, len(Bees)): 
    Bees[i] = int(Bees[i])
Bees = np.reshape(Bees,(25,25))
def suma5x5(x,y):
    suma=0

这是BeesData文件:

https://drive.google.com/file/d/1aWcLZq2MuGENavoTnCfokXr1Nnyygz23/view?usp=sharing![enter图像描述在此](https://i.stack.imgur.com/G9u5P.png


Tags: inhttpsimportnumpytxtcomforread
2条回答

我把这当作是一种学习练习。不是真正的numpy用户

TLDR

search_area = np.arange(25).reshape(5,5)
search_kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])

results = convolve2d(search_area, search_kernel, mode='same')

max_index = np.argmax(results, axis=None)
max_location = np.unravel_index(max_index, results.shape)
print(max_location)

假设5个相邻的意思是:上、下、左、右、中,那么你可以用卷积法找到这个值

假设我们只想找到标记为1的值的每个3x3块的总和:

[[0, 1, 0],
 [1, 1, 1],
 [0, 1, 0]]

此形状可以用作卷积的内核。它将用于将3x3平方中的每个值相加,将其相应的值乘以1。e、 g代表

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

你会得到1x0 + 2x1 + 3x0 + 4x1 + 5x1 + 6x1 + 7x0 + 8x1 + 9x0 = 25

scipy有一个用于此的方法称为convolve2d

import numpy as np
from scipy.signal import convolve2d

search_area = np.arange(36).reshape(6,6)
search_kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])

results = convolve2d(search_area, search_kernel)

print(search_area)
print(results)

这将产生:

[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]
 [30 31 32 33 34 35]]
[[  0   0   1   2   3   4   5   0]
 [  0   7  10  14  18  22  20   5]
 [  6  25  35  40  45  50  43  11]
 [ 12  49  65  70  75  80  67  17]
 [ 18  73  95 100 105 110  91  23]
 [ 24  97 125 130 135 140 115  29]
 [ 30  85 118 122 126 130  98  35]
 [  0  30  31  32  33  34  35   0]]

因为我们将边作为卷积的一部分包括在内,所以您将看到结果大小现在是8x8,而不是原来的6x6。对于由于超出数组边缘而无法找到的值,该方法假定值为零

要放弃这些边,可以使用same模式,该模式使其从结果中删除这些边:

results = convolve2d(search_area, search_kernel, mode='same')

print(search_area)
print(results)
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]
 [30 31 32 33 34 35]]
[[  7  10  14  18  22  20]
 [ 25  35  40  45  50  43]
 [ 49  65  70  75  80  67]
 [ 73  95 100 105 110  91]
 [ 97 125 130 135 140 115]
 [ 85 118 122 126 130  98]]

现在要找到蜜蜂最多的位置,可以使用argmax获得最大值的索引,并使用unravel_index将其作为原始形状中的位置

max_index = np.argmax(results, axis=None)
max_location = np.unravel_index(max_index, results.shape)

print(max_location)
(4, 4)

假设最后两行代码的窗口大小为5x5:

def suma5x5(x,y):
    suma=0

尝试了一个简单的基本python+numpy操作代码

arr = np.array([[2, 3, 7, 4, 6, 2, 9],
                [6, 6, 9, 8, 7, 4, 3],
                [3, 4, 8, 3, 8, 9, 7],
                [7, 8, 3, 6, 6, 3, 4],
                [4, 2, 1, 8, 3, 4, 6],
                [3, 2, 4, 1, 9, 8, 3],
                [0, 1, 3, 9, 2, 1, 4]])
w_size = 5
res = max(sum(sum(a)) for a in (arr[row:row+w_size, col:col+w_size] for row in range(arr.shape[0]-w_size+1) for col in range(arr.shape[1]-w_size+1)))

print(res)  # 138

相关问题 更多 >