在Python中,你可以使用不同的库来读取图像文件,并获取其格式信息。以下是使用PIL(Python Imaging Library)和OpenCV库读取图像文件并查看其格式的示例代码:
使用PIL读取图像
from PIL import Image
读取图像文件
image = Image.open('image.jpg')
获取图像信息
print(image.size) 输出图像尺寸
print(image.format) 输出图像格式
print(image.mode) 输出图像模式
使用OpenCV读取图像
import cv2
读取图像文件
image = cv2.imread('image.jpg')
获取图像信息
print(image.shape) 输出图像尺寸,形式为(高度,宽度,通道数)
验证文件格式与后缀是否一致
import os
from PIL import Image
列出文件夹中的所有文件
dirfff = 'C:\\Users\\Administrator\\Desktop\\image_format'
all_files = os.listdir(dirfff)
for i in all_files:
获取文件的完整路径
thisff = os.path.join(dirfff, i)
尝试打开文件
try:
im = Image.open(thisff)
输出文件尺寸和格式
print(f"{thisff}: size={im.size}, format={im.format}, mode={im.mode}")
except IOError:
print(f"Error opening {thisff}")
读取特定格式的图像文件
例如,使用`read_pfm`函数读取PFM格式图像:
def read_pfm(file_path):
读取文件头部信息
with open(file_path, 'rb') as file:
header = file.read(4)
width, height = map(int, header.split())
scale = float(file.readline().strip())
读取像素数据
data = np.fromfile(file, dtype=np.float32)
data = data.reshape((height, width, 3))
返回图像数据
return data
使用函数读取PFM图像
image_data = read_pfm('path_to_your_image.pfm')
print(image_data.shape) 输出图像尺寸,形式为(高度,宽度,通道数)
以上代码展示了如何使用PIL和OpenCV读取图像文件,并获取其尺寸和格式信息。如果需要读取特定格式的图像文件,可以使用相应的函数或库。