本篇介绍两种方式来打开图片.
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
@Author: zh
@Time 2023/11/27 下午1:59 .
@Email:
@Describe:
"""
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
import os
img = mpimg.imread("img/test.jpg")
plt.imshow(img)
plt.show()
这里使用matplotlib.pyplot库显示图片.
其中mpimg.imread 是可以替换成plt.imread的.两者效果一样.
原因如下:
@_copy_docstring_and_deprecators(matplotlib.image.imread)
def imread(fname, format=None):
return matplotlib.image.imread(fname, format)
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
@Author: zh
@Time 2023/11/27 下午1:59 .
@Email:
@Describe:
"""
from PIL import Image
import os
# 打开图片
img = Image.open("img/test.jpg")
img.show(title="test")
注意: img.show需要指定title参数.如果使用img.show().错误如下:
Traceback (most recent call last):
File "/home/zh/workSpace/python/Test1/venv/ImageTest.py", line 22, in <module>
img.show()
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2146, in show
_show(self, title=title, command=command)
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 3085, in _show
_showxv(image, **options)
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 3091, in _showxv
ImageShow.show(image, title, **options)
File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 47, in show
if viewer.show(image, title=title, **options):
File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 67, in show
return self.show_image(image, **options)
File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 87, in show_image
return self.show_file(self.save_image(image), **options)
File "/usr/lib/python3/dist-packages/PIL/ImageShow.py", line 168, in show_file
subprocess.Popen(args)
File "/usr/lib/python3.8/subprocess.py", line 858, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1639, in _execute_child
self.pid = _posixsubprocess.fork_exec(
TypeError: expected str, bytes or os.PathLike object, not NoneType
另外,可以获取当前脚本的目录,拼接绝对路径来设置.
具体代码如下:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
@Author: zh
@Time 2023/11/27 下午1:59 .
@Email:
@Describe:
"""
from PIL import Image
import o
# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接图片文件路径
image_path = os.path.join(current_dir, 'img/test.jpg')
print(image_path)
img = Image.open(image_path)
img.show(title="test")