Table of contents
Show image cv2.imshow plt.imshow
Read the picture of the Chinese path
cv2
Read picture cv2.imread
The image shape read by cv2.imread(img_path) is hwc, and the channel dimension is BGR type
It can be converted to an image of RGB type by cv2.cvtColor() or img[:,:,::-1]
Note: cv2.imread() can only read pictures in English path
Show image cv2.imshow plt.imshow
cv2.imshow('name',img) where name is the name of the image to be displayed, img is the image to be displayed, and can display BGR type images normally (can directly display the image read by cv2, displaying RGB images will cause color confusion)
plt.imshow(img) displays RGB type images, add plt.show() to display images
code
import cv2
import matplotlib.pyplot as plt
img_path='D:\man.png' # 更改自己图片路径
"""法一"""
img1=cv2.imread(img_path)
print(img1.shape) # h w c(其中c维度为BGR形式)
cv2.imshow('img1',img1) #展示BGR形式的图片
cv2.waitKey(0)
cv2.destroyAllWindows()
"""法二"""
img1=cv2.imread(img_path)
# BGR->RGB的两种方式
img1=cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)
# img1=img1[:,:,::-1] # 在维度通道倒序
# plt展示图片
plt.imshow(img1)
plt.show()
Read the picture of the Chinese path
cv2.imread() can only read pictures under English path, if read Chinese path, use
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
First use the fromfile in numpy to read the file, read the picture into data according to the int type, read it into a one-dimensional array, and
then decode the array through imdecode in cv to get the picture (the decoded picture is still of BGR type)
The meaning of the last parameter:
cv2.IMREAD_COLOR reads a color image, which can be abbreviated as 1
cv2.IMREAD_GRAYSCALE: Load images in grayscale mode, which can be abbreviated as 0
cv2.IMREAD_UNCHANGED: Read in the complete image, including the alpha channel (including transparency information), which can be abbreviated as -1
cv2.resize
cv2.resize(img,(w,h)) wh is the new size after resize
import cv2
img_path='D:\man.png' # 更改自己图片路径
img1=cv2.imread(img_path)
h,w,c=img1.shape
scale=0.5
img1=cv2.resize(img1,(int(scale*w),int(scale*h)))
cv2.imshow('img1',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
PIL.Image
Read image Image.open
Image.open(img_path) reads in the picture, and the shape of the read in picture is wh
For PIL type pictures, the width and height of the picture can be displayed by printing img.width img.height, and the wh of the picture can be displayed by img.size
Through img= np.array (img), the image shape is converted to hwc , where the channel is RGB type
Show image plt.imshow
Use plt to display RGB images
code
import matplotlib.pyplot as plt
import PIL.Image as Image
import numpy as np
img_path='D:\man.png'
img2=Image.open(img_path)
print(img2.size) # w h
print(img2.width) # w
print(img2.height) # h
img2=np.array(img2)
print(img2.shape) # h w c(RGB)
# plt展示RGB图片
plt.imshow(img2)
plt.show()