Read-Write-Display Image
In this lesson, you will learn how to read, how to view and save. The functions cv2.imread (), cv2.imshow (), cv2.imwrite () will be used for these operations.
To read an image, the function cv2.imread () is used. The
image to be read must be in the working directory or a full visual path must be
given. The second argument is a sign that indicates how the image should be
read.
cv2.IMREAD_COLOR: Indicates that a color image will be
loaded. It is the default flag. The integer value for this flag can be assigned
to 1.
cv2.IMREAD_GRAYSCALE: Loads the image in grayscale mode.
cv2.IMREAD_UNCHANGED: Loads the image as included in the
alpha channel.
import cv2
# The code below reads the image and assigns it to the image variable.
image = cv2.imread('bird')
The function cv2.imshow () is used to display an image. The
window opens automatically in image size. The first argument is the name of the
window to open. The second argument is the image we read above. We can create
as many windows as we want with different window names.
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
The function cv2.imwrite() is used to save the image. Used as follows.
cv2.imwrite("recorded.jpg",image)
cv2.waitKey () is a keyboard binding function. The argument
it takes is the time in milliseconds. This function waits for the specified
milliseconds for any keyboard event. If the argument is passed 0, it will wait
indefinitely for a keystroke.
cv2.destroyAllWindows () destroys all created windows. If
you want to destroy the previously specified window, the function
cv2.destroyWindow () is used. Here, the full window name should be given as an
argument.
The complete code is as follows:
import cv2
# The code below reads the image and assigns it to the image variable.
image = cv2.imread('bird.jpg')
cv2.imshow("Image", image)
cv2.imwrite("recorded.jpg",image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output of the code:
Comments
Post a Comment