python 获取图像高宽值
时间: 2023-08-18 10:16:22 浏览: 164
要获取图像的高度和宽度,可以使用 OpenCV 库中的 cv2.imread() 函数读取图像,然后使用图像的 shape 属性来获取高度和宽度。它返回一个元组 (height, width, channels),其中 channels 表示图像的通道数,通常为 3(彩色图像)或 1(灰度图像)。
示例代码:
```python
import cv2
img = cv2.imread('image.jpg')
height, width, channels = img.shape
print('Image height:', height)
print('Image width:', width)
print('Number of channels:', channels)
```
这段代码读取名为 'image.jpg' 的图像,然后使用 img.shape 属性获取图像的高度、宽度和通道数,并打印这些值。
相关问题
python PIL 获取图像高宽值
要使用 Python Imaging Library (PIL) 获取图像的高度和宽度,可以使用 PIL 库中的 Image 类。首先使用 Image.open() 函数打开图像,然后使用图像的 size 属性获取其高度和宽度。它返回一个元组 (width, height)。
示例代码:
```python
from PIL import Image
img = Image.open('image.jpg')
width, height = img.size
print('Image width:', width)
print('Image height:', height)
```
这段代码打开名为 'image.jpg' 的图像,然后使用 img.size 属性获取其高度和宽度,并打印这些值。
Python 引用图像宽高
### 使用 Python 获取图像宽度和高度
在 Python 中,可以利用多个库来获取图像的宽度和高度。以下是几种常见的方式。
#### 使用 PIL 库获取图像尺寸
通过 `PIL`(即 Pillow),能够轻松打开并查询图像的信息:
```python
from PIL import Image
image_path = './example.jpg'
img = Image.open(image_path)
width, height = img.size # 返回的是(width, height)元组
print(f'Width: {width}, Height: {height}')
```
这段代码展示了如何加载一张图片,并打印其宽度和高度[^2]。
#### 使用 OpenCV 库读取图像大小
OpenCV 是另一个强大的计算机视觉库,在此也可以很方便地取得图像尺寸信息:
```python
import cv2
image_path = r'./example.png'
img = cv2.imread(image_path)
dimensions = img.shape[:2] # shape 属性给出(Height, Width[, Channels]),这里只取前两个值作为高宽
height, width = dimensions
print(f'Width: {width}, Height: {height}')
```
注意这里的路径前面加上了字母 'r' 来防止反斜杠被解释成转义字符[^4]。
这两种方法都是高效且易于实现的选择,具体选用哪一个取决于项目需求和个人偏好。
阅读全文
相关推荐














