Task: RGB to Grayscale Conversion
In this task, you will implement a function rgb_to_grayscale(image) that converts an RGB image to a grayscale image using the luminosity method.
The input image is represented as a 3D array of shape (H, W, 3), where H is height, W is width, and 3 represents the RGB color channels. Each pixel value should be in the range [0, 255].
Your Task:
Implement the function rgb_to_grayscale(image) to:
- Convert the RGB image to grayscale using the standard luminosity coefficients for human perception of color brightness.
- Return the grayscale image as a 2D list with pixel values rounded to integers.
- Handle edge cases:
- If the input is not a valid 3D array with 3 color channels.
- If the image has empty dimensions.
- If any pixel values are outside the valid range (0-255).
For any of these edge cases, the function should return -1.
Examples
Example 1:
Input:
image = [[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 255]]]
print(rgb_to_grayscale(image))Output:
[[76, 150], [29, 255]]Explanation: Using the luminosity formula: Gray = 0.299*R + 0.587*G + 0.114*B
- Pure Red (255, 0, 0): 0.299 * 255 = 76.245 -> 76
- Pure Green (0, 255, 0): 0.587 * 255 = 149.685 -> 150
- Pure Blue (0, 0, 255): 0.114 * 255 = 29.07 -> 29
- White (255, 255, 255): 0.299*255 + 0.587*255 + 0.114*255 = 255
Starter Code
import numpy as np
def rgb_to_grayscale(image):
"""
Convert an RGB image to grayscale using luminosity method.
Args:
image: RGB image as list or numpy array of shape (H, W, 3)
with values in range [0, 255]
Returns:
Grayscale image as 2D list with integer values,
or -1 if input is invalid
"""
# Write your code here
passPython3
ReadyLines: 1Characters: 0
Ready