Create a python program that takes in an image from the user and puts the image into matrices of red, green, and blue. Then use the equation Y = 0.2126R + 0.7125G + 0.0722B to convert the image to grayscale and output the grayscale image. You must only use the libraries numpy, matplotlib.pyplot, and math. You may not use pillow, openCV, sciPy, etc.
Python code:
# Import necessary libraries
import numpy as np
import matplotlib
import matplotlib.pyplot as pyplot
# Colored image input
img = matplotlib.image.imread("img.jpg")
# Print the RGB matrix
print("The matrix for the colored image is:")
print(np.array(img))
# Display the colored image
print("The colored image is: ")
pyplot.imshow(img)
pyplot.show()
# Define the RGB weights according to the equation (Y = 0.2126R + 0.7125G + 0.0722B)
rgb_weights = [0.2126, 0.7125, 0.0722]
# Convert into grayscale and display
print("The grayscale image is: ")
grayscale_image = np.dot(img[...,:3], rgb_weights)
pyplot.imshow(grayscale_image, cmap=pyplot.get_cmap("gray"))
pyplot.show()
Output:
The matrix for the colored image is:
[[[ 78 106 48]
[ 78 106 47]
[ 78 106 47]
...
[152 180 96]
[152 180 96]
[152 180 96]]
[[ 78 106 48]
[ 78 106 47]
[ 78 106 47]
...
[152 180 96]
[152 180 96]
[152 180 96]]
[[ 78 106 48]
[ 78 106 47]
[ 78 106 47]
...
[153 181 97]
[153 181 97]
[153 181 97]]
...
[[ 93 123 61]
[ 93 123 61]
[ 93 123 61]
...
[160 188 104]
[160 188 104]
[160 188 104]]
[[ 93 123 61]
[ 93 123 61]
[ 93 123 61]
...
[160 188 104]
[160 188 104]
[160 188 104]]
[[ 93 123 61]
[ 93 123 61]
[ 93 123 61]
...
[160 188 104]
[160 188 104]
[160 188 104]]]
Get Answers For Free
Most questions answered within 1 hours.