python展示图片的四种方法

在 Python 中,有多种库可用于图像展示。以下是一些常见的展示图片的方法和相关的库
Matplotlib:
使用 matplotlib.pyplot.imshow 函数展示图像。示例代码:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img_path = 'example.jpg'
img = mpimg.imread(img_path)
plt.imshow(img)
plt.axis('off')
plt.show()
Pillow(PIL):
使用 PIL.Image.show 方法展示图像。示例代码:
from PIL import Image
img_path = 'example.jpg'
img = Image.open(img_path)
img.show()
IPython 的 Display 模块:
使用 IPython.display.Image 类展示图像。示例代码:
from IPython.display import Image, display
img_path = 'example.jpg'
display(Image(filename=img_path))
OpenCV:
使用 cv2.imshow 方法展示图像。需要注意的是,cv2.imshow 通常在 Jupyter Notebook 中无法直接使用,但在独立的 Python 脚本中有效。示例代码:
import cv2
img_path = 'example.jpg'
img = cv2.imread(img_path)
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()