Loading

Python读取保存图像文件

Python处理图像数据时通常需要对图像文件进行读取、保存等操作,因此将现有的方法归纳了一下。

1. PIL

依赖包:Pillow

安装:pip install Pillow

源码:

 1 import numpy as np
 2 from PIL import Image
 3 import matplotlib.pyplot as plt
 4 
 5 image = Image.open("image.jpg")
 6 
 7 image_resize = image.resize((128, 128))
 8 image_array = np.array(image_resize)
 9 image_output = Image.fromarray(image_array)
10 image_output.save("image_output.jpg")
11 
12 plt.imshow(image_output)
13 plt.axis("off")
14 plt.show()

2. opencv

依赖包:opencv-python

安装:pip install opencv-python

源码:

 1 import cv2
 2 
 3 image = cv2.imread("image.jpg")
 4 
 5 image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 6 image_resize = cv2.resize(image, (128, 128))
 7 
 8 cv2.imwrite("image_output.jpg", image_gray)
 9 cv2.namedWindow("img_out")
10 cv2.imshow('img_out',image_gray)
11 cv2.waitKey(0)
12 cv2.destroyAllWindows()

3. imageio

依赖包:imageio

安装:pip install imageio

源码:

 1 from imageio import imread, imsave
 2 from scipy import ndimage
 3 import matplotlib.pyplot as plt
 4 
 5 image = imread("image.jpg")
 6 
 7 img_rote_20 = ndimage.rotate(image, 20)
 8 imsave("image_out.jpg", img_rote_20)
 9 
10 plt.imshow(img_rote_20)
11 plt.axis("off")
12 plt.show()

4. skimage (recommend to use)

依赖包:scikit-image

安装:pip install scikit-image

源码:

1 from skimage import io
2 import matplotlib.pyplot as plt
3 
4 image = io.imread("image.jpg")
5 
6 io.imsave("image_output.jpg", image)
7 
8 io.imshow(image)
9 plt.show()

5. matplotlib

依赖包:matplotlib

安装:pip install matplotlib

源码:

 1 import matplotlib.image as mpimg
 2 import matplotlib.pyplot as plt
 3 
 4 image = mpimg.imread("image.jpg")
 5 
 6 mpimg.imsave("image_output.jpg", image)
 7 
 8 plt.imshow(image)
 9 plt.axis("off")
10 plt.show()

7. keras (machine learning or deep learning)

依赖包:keras

安装:pip install keras

源码:

1 from keras.preprocessing import image
2 
3 img = image.load_img("image.jpg", target_size=(128, 128))
4 
5 image_array = image.img_to_array(img)
6 image_output = image.array_to_img(img)
7 
8 image_output.save("image_output.jpg")

 

上述七种方法均可以对图像文件进行读取保存处理,对日常cv预处理图像非常有帮助。

 

posted @ 2022-01-23 11:07  _yhwu  阅读(453)  评论(0编辑  收藏  举报