PIL 图像读取
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 13:13:08 2020
@author: 陨星落云
"""
#%% PIL 图像读取
from PIL import Image
import numpy as np
# 读取图像
img = Image.open('lena.jpg')
# 查看图像类型
print(type(img))
# # 显示图像
# img.show()
# 查看图像的格式
print(img.format)
# 将PIL类型的图像转换成numpy.ndarray
img1 = np.asarray(img)
print(type(img1))
输出结果:
<class 'PIL.JpegImagePlugin.JpegImageFile'>
JPEG
<class 'numpy.ndarray'>
matplotlib 图像读取
#%% matplotlib 图像读取
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
img = mpimg.imread('lena.jpg')
print(type(img))
print(img.shape)
plt.imshow(img)
plt.colorbar()
输出结果:
<class 'numpy.ndarray'>
(256, 256, 3)
skimage 图像读取
#%% skimage 图像读取
from skimage import io,img_as_float,img_as_ubyte
import numpy as np
img = io.imread('lena.jpg')
# 查看类型
print(type(img))
# print(img)
# 将uint8转变为浮点数
# 方法1:需要除以255,进行归一化
image_float1=img.astype(np.float)/255
print(image_float1)
# 方法2:自动归一化
image_float2 = img_as_float(img)
print('**'*20)
print(image_float2)
输出结果:
<class 'imageio.core.util.Array'>
opencv 图像读取
#%% opencv 图像读取
import cv2
import matplotlib.pyplot as plt
grey_img = cv2.imread('lena.jpg',0)
color_img = cv2.imread('lena.jpg',1)
# 显示图像
# 方法1
plt.subplot(121)
plt.imshow(grey_img,cmap='gray')
plt.axis('off')
plt.subplot(122)
plt.imshow(cv2.cvtColor(color_img,cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
# 方法2
cv2.namedWindow('grey_image',cv2.WINDOW_NORMAL)
cv2.imshow('grey_image', grey_img)
cv2.namedWindow('color_image',cv2.WINDOW_NORMAL)
cv2.imshow('color_image', color_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出结果:
灰度图与彩色图.png图像自动化处理
#%% 图像自动化处理
import cv2
import glob
# 批量图像jpg转png
path = 'test/*.jpg'
for file in glob.glob(path):
print(file)
img = cv2.imread(file)
cv2.imwrite(file[:-4]+'.png', img)
网友评论