15 Mar Set a Grayscale filter with OpenCV
Convert an image to grayscale to give it a classic black-and-white look. Use the cv2.IMREAD_GRAYSCALE parameter value of the imread() function.
Let us now see the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Read and display an image with OpenCV and give it a grayscale filter import cv2 # Load an image # The cv2.IMREAD_GRAYSCALE here gives grayscale to the image image = cv2.imread(r'C:\Users\hp\Downloads\Astronaut.png', cv2.IMREAD_GRAYSCALE) # Display the image cv2.imshow("Grayscale Filter", image) # Wait for a key press and close the window cv2.waitKey(0) cv2.destroyAllWindows() |
The following is the output:
Explanation:
This Python script employs the OpenCV library to load an image, apply a grayscale filter, and display it:
- It begins by importing the OpenCV library:
- The script then reads the image file from the specified file path, using the
cv2.IMREAD_GRAYSCALE
flag in thecv2.imread()
function to convert the image into grayscale during the loading process. - The grayscale image is assigned to the variable
image
. - The
cv2.imshow()
function is then used to display the grayscale image in a window titled “Grayscale Filter.” - To keep the window open for viewing, the
cv2.waitKey(0)
function waits indefinitely for a key press. - Once a key is pressed, the script closes the display window using the
cv2.destroyAllWindows()
function. - This allows users to view the grayscale-filtered version of the image conveniently and interactively.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
- Generative AI Tutorial
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- Copilot Tutorial
- Gemini Tutorial
- ChatGPT Tutorial
No Comments