Python案例怎么读取图片信息?

wen python案例 13

本文目录导读:

Python案例怎么读取图片信息?

  1. 使用PIL/Pillow库(最常用)
  2. 使用OpenCV库
  3. 使用matplotlib库
  4. 使用imageio库
  5. 获取图片文件的系统信息
  6. 完整的图片信息提取示例
  7. 安装依赖
  8. 选择建议

我来介绍几种常用的Python读取图片信息的方法:

使用PIL/Pillow库(最常用)

from PIL import Image
from PIL.ExifTags import TAGS
# 打开图片
img = Image.open('example.jpg')
# 基本图片信息
print(f"图片格式: {img.format}")
print(f"图片尺寸: {img.size}")
print(f"图片模式: {img.mode}")
print(f"图片宽度: {img.width}")
print(f"图片高度: {img.height}")
# 获取EXIF信息(拍摄参数)
exif_data = img._getexif()
if exif_data:
    print("\nEXIF信息:")
    for tag_id, value in exif_data.items():
        tag_name = TAGS.get(tag_id, tag_id)
        print(f"{tag_name}: {value}")

使用OpenCV库

import cv2
# 读取图片
img = cv2.imread('example.jpg')
# 获取图片信息
print(f"图片形状: {img.shape}")
print(f"图片高度: {img.shape[0]}")
print(f"图片宽度: {img.shape[1]}")
print(f"通道数: {img.shape[2]}")
print(f"像素总数: {img.size}")
print(f"数据类型: {img.dtype}")
# 获取像素值示例
print(f"第一个像素的BGR值: {img[0, 0]}")

使用matplotlib库

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# 读取图片
img = mpimg.imread('example.jpg')
# 获取图片信息
print(f"图片数组形状: {img.shape}")
print(f"数据类型: {img.dtype}")
print(f"像素值范围: [{img.min()}, {img.max()}]")
# 显示图片
plt.imshow(img)
plt.axis('off')
plt.show()

使用imageio库

import imageio
import numpy as np
# 读取图片
img = imageio.imread('example.jpg')
# 获取图片信息
print(f"图片形状: {img.shape}")
print(f"数据类型: {img.dtype}")
print(f"像素值范围: {img.min()} - {img.max()}")
# 获取元数据
metadata = imageio.imread('example.jpg', meta=True)
print(f"元数据: {metadata}")

获取图片文件的系统信息

import os
from datetime import datetime
def get_image_file_info(filepath):
    # 文件基本信息
    stat_info = os.stat(filepath)
    file_size = stat_info.st_size
    # 文件创建时间
    created_time = datetime.fromtimestamp(stat_info.st_ctime)
    modified_time = datetime.fromtimestamp(stat_info.st_mtime)
    return {
        '文件名': os.path.basename(filepath),
        '文件大小': f"{file_size / 1024:.2f} KB",
        '创建时间': created_time,
        '修改时间': modified_time
    }
# 使用示例
file_info = get_image_file_info('example.jpg')
for key, value in file_info.items():
    print(f"{key}: {value}")

完整的图片信息提取示例

from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import os
from datetime import datetime
def get_image_info(image_path):
    """获取图片的完整信息"""
    info = {}
    # 文件基本信息
    stat_info = os.stat(image_path)
    info['文件名'] = os.path.basename(image_path)
    info['文件大小'] = f"{stat_info.st_size / 1024:.2f} KB"
    # 图片信息
    with Image.open(image_path) as img:
        info['格式'] = img.format
        info['尺寸'] = f"{img.width} x {img.height}"
        info['模式'] = img.mode
        # 获取EXIF信息
        try:
            exif = img._getexif()
            if exif:
                for tag_id, value in exif.items():
                    tag_name = TAGS.get(tag_id, tag_id)
                    if tag_name == "GPSInfo":
                        gps_info = {}
                        for gps_tag_id, gps_value in value.items():
                            gps_tag_name = GPSTAGS.get(gps_tag_id, gps_tag_id)
                            gps_info[gps_tag_name] = gps_value
                        info['GPS信息'] = gps_info
                    else:
                        info[tag_name] = str(value)[:50]  # 截取前50个字符
        except Exception as e:
            info['EXIF'] = f"无法读取: {e}"
    return info
# 使用示例
image_info = get_image_info('example.jpg')
for key, value in image_info.items():
    print(f"{key}: {value}")

安装依赖

# 安装必要的库
pip install Pillow
pip install opencv-python
pip install matplotlib
pip install imageio

选择建议

  • 基本读取:使用PIL/Pillow,功能全面,易于使用
  • 计算机视觉:使用OpenCV,功能强大,适合图像处理
  • 数据可视化:使用matplotlib,适合显示和分析
  • 文件信息:使用os模块获取系统文件属性

这些方法可以满足大多数图片信息读取的需求,你可以根据具体场景选择合适的方法。

抱歉,评论功能暂时关闭!