在Python中读取图像,你可以使用多种库,例如OpenCV和PIL(Pillow)。以下是使用这两种库读取图像的基本步骤:
使用OpenCV读取图像
1. 安装OpenCV库:
pip install opencv-python
2. 读取图像:
import cv2
图像路径
dirpath = "C:/Users/wuzhengxiang/Desktop/beatgirl.jpg"
读取图像
img_cv = cv2.imread(dirpath)
输出图像的形状和类型
print("img_cv shape:", img_cv.shape)
print("img_cv type:", type(img_cv))
使用PIL(Pillow)读取图像
1. 安装Pillow库:
pip install pillow
2. 读取图像:
from PIL import Image
import numpy as np
图像路径
dirpath = "C:/Users/wuzhengxiang/Desktop/beatgirl.jpg"
读取图像
img_PIL = Image.open(dirpath)
将图像转换为numpy数组
img_PIL_array = np.array(img_PIL)
输出图像的形状和类型
print("img_PIL shape:", img_PIL_array.shape)
print("img_PIL type:", type(img_PIL_array))
以上代码展示了如何使用OpenCV和PIL库读取图像,并将图像转换为numpy数组格式,以便进行后续处理。