图像亮度是指图像的明亮程度,其计算公式为:

其中, 是图像的像素值。

本题的一个小难点是处理异常情况,主要有以下几种情况:

  1. 图像为空
  2. 图像没有列
  3. 图像的行长度不一致
  4. 图像的像素值不在0到255之间

标准代码如下

def calculate_brightness(img):
    # Check if image is empty or has no columns
    if not img or not img[0]:
        return -1

    rows, cols = len(img), len(img[0])

    for row in img:
        if len(row) != cols:
            return -1
        for pixel in row:
            if not 0 <= pixel <= 255:
                return -1

    total = sum(sum(row) for row in img)
    return round(total / (rows * cols), 2)

可以看到,本题在实现上本质只是对一个矩阵求和,然后求平均值,因此可以使用numpy库中的sum函数和mean函数来简化代码编写。

def calculate_brightness(img):
    import numpy as np
    # 检查图像是否为空或没有列
    if not img or not img[0]:
        return -1
        
    # 转换为numpy数组以便进行运算
    img_array = np.array(img)
    
    # 检查数组维度是否正确
    if len(img_array.shape) != 2:
        return -1
        
    # 检查像素值范围
    if np.any((img_array < 0) | (img_array > 255)):
        return -1
        
    # 使用numpy的mean函数计算平均值
    return round(np.mean(img_array), 2)