Back to Problems

Calculate Image Brightness

Task: Image Brightness Calculator

In this task, you will implement a function calculate_brightness(img) that calculates the average brightness of a grayscale image. The image is represented as a 2D matrix, where each element represents a pixel value between 0 (black) and 255 (white).

Your Task: Implement the function calculate_brightness(img) to return the average brightness rounded to two decimal places. If the image matrix is empty, has inconsistent row lengths, or contains invalid pixel values (outside the range 0-255), the function should return -1.

Example

Example:
img = [
    [100, 200],
    [50, 150]
]
print(calculate_brightness(img))
Output: 125.0

Image Brightness Calculator

Consider a grayscale image represented as a 2D matrix where each element represents a pixel value between 0 (black) and 255 (white):

\[ Image = \begin{pmatrix} p_{11} & p_{12} \\ p_{21} & p_{22} \end{pmatrix} \]

The average brightness is calculated as:

\[ Brightness = \frac{\sum_{i=1}^{m} \sum_{j=1}^{n} p_{ij}}{m \times n} \]

where:

  • \(p_{ij}\) is the pixel value at position (i,j)
  • \(m\) is the number of rows
  • \(n\) is the number of columns

Things to note:

  • All pixel values must be between 0 and 255
  • The image matrix must be well-formed (all rows same length)
  • Empty or invalid images return -1
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])

    # Check if all rows have same length and values are valid
    for row in img:
        if len(row) != cols:
            return -1
        for pixel in row:
            if not 0 <= pixel <= 255:
                return -1

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

There’s no video solution available yet 😔, but you can be the first to submit one at: GitHub link.

Your Solution

Output will be shown here.