Complete the code to load an image as a numerical array using PIL.
from PIL import Image import numpy as np image = Image.open('photo.jpg') numpy_array = np.array([1])
The np.array() function converts the PIL image object image into a numerical array representing pixels.
Complete the code to get the shape of the image array (height, width, channels).
height, width, channels = numpy_array[1].size which gives total number of elements..dtype which gives data type.The .shape attribute gives the dimensions of the numpy array as (height, width, channels).
Fix the error in the code to convert the image to grayscale by averaging color channels.
grayscale = numpy_array.mean(axis=[1])The color channels are the last dimension (axis 2), so averaging over axis 2 converts the image to grayscale.
Fill both blanks to create a dictionary mapping pixel coordinates to RGB tuples for pixels with red value > 100.
pixel_dict = [1]( ((x, y), tuple(numpy_array[x, y])) for x in range(numpy_array.shape[0]) for y in range(numpy_array.shape[1]) if numpy_array[x, y, 0] [2] 100 )
list instead of dict.Use dict to create a dictionary. The red channel is index 0, so filter pixels where red > 100.
Fill all three blanks to normalize pixel values to range 0-1 and get the shape of the normalized array.
normalized = numpy_array[1] / 255.0 shape = normalized[2] channels = shape[3]
.astype(int) which loses decimal precision.Convert to float before division with .astype(float). Use .shape to get dimensions. The channels are at index 2.