pillow读取图片
from PIL import Image
import numpy as np
img_path = './Training/meningioma/M546.jpg'
# 读取图片
image = Image.open(img_path)
width, height = image.size
print("图片的宽度为={},高度为={}".format(width,height))
print("图片的mode为{}".format(image.mode))
print("图片的format为{}".format(image.format))
pixel = image.load()
img_arr = np.array(image)
print("图片数组大小为{}".format(img_arr.shape))
print("图片像素值最大为{}".format(np.max(img_arr)))
print("图片像素值最大为{}".format(np.min(img_arr)))
#显示图片
image.show()
#
matplotlib读取图片
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img_path = './Training/meningioma/M546.jpg'
# 打开PNG图片文件
png_image = mpimg.imread(img_path)
plt.imshow(png_image)
CV2读取图片
import cv2
import numpy as np
img_path = './Training/meningioma/M546.jpg'
# 读取图片
img = cv2.imread(img_path)
print(img.shape)
# mac显示图片有问题,会卡死,图片无法关闭,
注意点
如果在jupyter中,最好使用matplotlib就可以
因为如果使用PIL库,图片是以窗口的形式展示的
而cv2的结果是不显示,所以最好使用matploblib可以在jupyter中显示图片
我又发现了一个问题,就是原始的jpg图片和在程序中显示的维度是反过来的,比如下面的例子
原始图片
pillow读取图片
from PIL import Image
import numpy as np
img_path = './pixel_test.jpg'
# 读取图片
image = Image.open(img_path)
width, height = image.size
print("图片的宽度为={},高度为={}".format(width,height))
print("图片的mode为{}".format(image.mode))
print("图片的format为{}".format(image.format))
pixel = image.load()
img_arr = np.array(image)
print("图片数组大小为{}".format(img_arr.shape))
print("图片像素值最大为{}".format(np.max(img_arr)))
print("图片像素值最大为{}".format(np.min(img_arr)))
#显示图片
image.show()
#
可以看到,图片的数组大小是(1946,2921,3),而原始的图片的大小是2921*1946,这个有点奇怪的哈,反正记住是倒过来的就行了
matplotlib显示图片
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img_path = './pixel_test.jpg'
# 打开PNG图片文件
png_image = mpimg.imread(img_path)
plt.imshow(png_image)
print(png_image.shape)
结果如下
cv2显示图片
import cv2
import numpy as np
img_path = './pixel_test.jpg'
# 读取图片
img = cv2.imread(img_path)
print(img.shape)
# mac显示图片有问题,会卡死,图片无法关闭,
所以无论你使用哪种方法读取,这个图片的大小就是会翻转过来的,为什么会造成这种差异呢?因为图片默认的坐标轴和我们印象中的坐标轴是不一样的,图片处理的坐标轴是从左上角开始的,而不是数学中的左下角开始的,这个需要注意的,可以看下面的测试例子
测试
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img_path = './pixel_test.jpg'
# 打开PNG图片文件
png_image = mpimg.imread(img_path)
img_arr = np.array(png_image)
img_arr[0:100,100:200,:]=[255,0,0]
plt.imshow(img_arr)
#print(png_image.shape)
但是这里注意一个问题,直接使用imread()
读取的png_image
是不能赋值的,需要要注意哈
但是这个数据经过复制后就可以进行赋值了,原因在于连个数据的flags是不一样的
load_image函数
from PIL import Image
import numpy as np
def load_image(filename, verbose=True,show=True):
img = Image.open(filename)
if show:
img.show()
img = np.array(img)
if img.ndim == 3 and img.shape[-1] == 4:
img = img[..., :3] # remove alpha channel
if verbose:
print(f'Image loaded from {filename}')
return img
img = load_image("../RN49-1/he.jpg")
print(img.shape)