将2d数组划分为大小为n的正方形,并在Python中计算每个正方形的平均值

2024-06-25 06:18:54 发布

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

我很抱歉这个简单的问题。我头上有个小疙瘩。 我有一个python的2d数组。我想把这个数组分解成大小为n的正方形,然后计算每个正方形的平均值。 到目前为止,我混乱的伪代码大致如下所示:

def mean(pic, n):
    """
    n: size of the square
    """
    npixels_r = pic.height // n
    npixels_c = pic.width // n
    new_pic = picture(npixels_c, npixels_r)
    # fill the new image
    # define the indexes for each qaudrant
    for s in range(0,w,n):
        for z in range(0,h,n):
            vals = []
            # for each pixel in the quadrant
            for i in range(s,s+n):
                for j in range(z, z*n):
                    # get color at each pixel
                    val = pic[i][j]
                    vals.append(val)
            m = mean(vals)
            new_pic.setValue(m)

但它不起作用。在第一个嵌套for循环中,我想在正方形上迭代,在第二个嵌套for循环中,我想在旧_图像中的每个像素上迭代,然后计算平均值。 这显然不是一个好主意,但目前我想不出任何解决方案:/


Tags: theinnewforrangeval数组mean
1条回答
网友
1楼 · 发布于 2024-06-25 06:18:54

你会踢自己:把for j in range(z, z*n)改成for j in range(z, z+n)

我会用image kernel来解决这个问题。您将使用每个像素值1/n^2创建一个nxn内核,并将其应用于图像。您提出的解决方案本质上是相同的,但不太具有普遍性(如果您想进行边缘查找而不是平均化怎么办?)

相关问题 更多 >