本文主要介绍了python中读取和查看图片的6种方法,分享给大家,具体如下:
file_name1='test_imgs/spect/1.png' # 这是彩色图片
file_name2='test_imgs/mri/1.png' # 这是灰度图片
1 OpenCV
注:用cv2读取图片默认通道顺序是B、G、R
,而不是通常的RGB顺序,所以读进去的彩色图直接显示会出现变色情况,详情可以看:https://www.jb51.net/article/245048.htm
import cv2
spect= cv2.imread(file_name1) # BGR
spect= spect[:, :, ::-1] # RGB
mri= cv2.imread(file_name2) # 灰度图
print(spect.shape) # (256, 256, 3)
print(mri.shape) # (256, 256, 3) cv2读进来是三通道的图片
import matplotlib.pyplot as plt
plt.imshow(spect)
plt.show()
import matplotlib.pyplot as plt
fig=plt.figure()
f1 = fig.add_subplot(121)
f2 = fig.add_subplot(122)
f1.imshow(spect)
f2.imshow(mri)
plt.show()
2 imageio
import imageio
spect = imageio.imread(file_name1)
mri = imageio.imread(file_name2)
print(spect.shape) # (256, 256, 3)
print(mri.shape) # (256, 256)
import matplotlib.pyplot as plt
fig=plt.figure()
f1 = fig.add_subplot(121)
f2 = fig.add_subplot(122)
f1.imshow(spect)
f2.imshow(mri,cmap='gray') # 注:单通道灰度图必须加上cmap='gray'才能正确显示
plt.show()
3 PIL
from PIL import Image
import numpy as np
spect= Image.open(file_name1) # <PIL.PngImagePlugin.PngImageFile image mode=RGB size=256x256 at 0x1D9F15FFDC8>
spect.show()
4 scipy.misc
from scipy.misc import imread
spect = imread(file_name1)
mri = imread(file_name2)
import matplotlib.pyplot as plt
fig=plt.figure()
f1 = fig.add_subplot(121)
f2 = fig.add_subplot(122)
f1.imshow(spect)
f2.imshow(mri,cmap='gray') # 注:单通道灰度图必须加上cmap='gray'才能正确显示
plt.show()
5 tensorflow
from tensorflow.python.keras.preprocessing.image import load_img
spect = load_img(file_name1) # <PIL.PngImagePlugin.PngImageFile image mode=RGB size=256x256 at 0x1D9EF188048>
spect.show()
6 skimage
from skimage import io
import matplotlib.pyplot as plt
mri = io.imread(file_name2)#读取数据
plt.imshow(mri,cmap='gray') # 注:单通道灰度图必须加上cmap='gray'才能正确显示
plt.show()
到此这篇关于详解python中读取和查看图片的6种方法的文章就介绍到这了,更多相关python读取和查看图片内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!