- Load, display and save the image.
- Access Image properties.
- Access and Modify Pixel Values.
- Resize The Image
OpenCV (Open Source Computer Vision Library) is a computer vision and machine learning software library used most widely for image manipulation and processing.
Load, Display and Save the Image:
Load An Image:
import cv2img = cv2.imread('lena.png')
import cv2image_path = r'D:\Binary Study\Pictures\lena.png'img = image.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
Display The Image:
cv2.imshow('image',img)cv2.waitKey(0)cv2.destroyAllWindows()
Save The Image:
To save the image use imwrite() . Let's save the image.cv2.imwrite('lena_new.png', img)
This python code will save the image 'img' as named "lena_new" in the same file where you are running this python code. Don't forget to give image type, as here .png.
Accessing Image Properties:
Image properties are shape of image (which includes number of rows, number of columns and number of color channels), size of image (which is total number of pixels in the image),data type of image etc.
Accessing Shape of an Image:
To access shape of image use img.shape. This returns a tuple of number of rows, columns, and channels( if color image).
print(img.shape)
(794, 600, 3)
Here number of rows, columns and color channels are 794, 600, and 3 respectively.
Note: If image is gray-scale then it will return only number of rows and columns. So you can use this to check an image if it is colored or not.
Accessing Size of The Image:
Total number pixels in an image is accessed by img.size:
print(img.size)
1429200
Note: If shape is (794, 600, 3) then size = 794*600*3 = 1429200
Accessing Image data type:
Use img.dtype to obtain data type of an image:
print(img.dtype)
dtype('uint8')
What is Type of An Image:
All Images are numpy ndarray. You can access what is the type of an image using type(image_name).
print(type(img))
numpy.ndarray
Accessing And Modifying Pixel Values:
print(img[250,250])
output:
[143 149 190]
img[250, 250] = [150,149,100]print(img[250,250])
output:[150 149 100]
img[0:50, 0:100] = 0
How To Resize An Image:
import cv2impot matplotlib.pyplot as plt# read the original imageimg = cv2.imread('lena.png')# get the shape of original imageprint(img.shape)# display the original imageplt.imshow(img)# here plt.imshow() is used for only to display the scale
import cv2impot matplotlib.pyplot as plt# Now resize the imageimg_r = cv2.resize(img, (400,500))# get the shape of resized imageprint(img_r)# display the resized imageplt.imshow(img_r)# here plt.imshow() is used for only to display the scale. You should use cv2.imshow()
(500, 400, 3)
I read your blog now share great information here.Image Converter Tool
ReplyDelete