In [1]:
import pandas as pd
import numpy as np
import cv2
Basic Operations on an Image¶
Reading an Image¶
For this operation, we have to and use the method imread().
The method imread() is used to convert an image file into a numpy array.
imread() has flags parameter which is by default 1,
where flags = 0 represents a grayscale image and
flags = 1 represents an RGB image.
In [2]:
img = cv2.imread(r"C:\Users\hp\Downloads\dogimage.jpeg")
In [3]:
img.shape # This gives the dimensions of the image
Out[3]:
(148, 192, 3)
In [10]:
img.dtype # This shows the datatype of the image
Out[10]:
dtype('uint8')
In [11]:
# Total no. of features in this image canbe calculated by multiplying the dimensions
148 * 192 * 3
Out[11]:
85248
Converting the dog image into grayscale using flags parameter¶
In [5]:
gray_img = cv2.imread(r"C:\Users\hp\Downloads\dogimage.jpeg", flags = 0)
In [8]:
gray_img.shape
Out[8]:
(148, 192)
In [9]:
gray_img.dtype
Out[9]:
dtype('uint8')
In [12]:
148 * 192
Out[12]:
28416
Writing an Image¶
For this operation, we have to and use the method imwrite().
The method imwrite() is used to convert a numpy array into an image.
Creating a grayscale image of the dog image¶
In [13]:
# Saving the image to disk
success = cv2.imwrite('dog_grayscale.jpg', gray_img)
if success:
print("Image successfully saved!")
else:
print("Failed to save the image.")
Image successfully saved!
Showing an Image¶
For this operation, we have to and use the method imshow().
The method imshow() is used to display an array in the form of an image by creating a popup window.
Displaying the created grayscale image of a dog using imshow()¶
In [18]:
cv2.imshow("Grayscale image of a dog", gray_img)
cv2.waitKey(10000) # waitKey() is used to add delay in milliseconds. The image will be display for that amount of time and closes.
cv2.destroyAllWindows() # destroyAllWindows() is used to clear the closed image from RAM