python获取图片的宽高
时间: 2024-06-19 17:01:03 浏览: 11
在Python中,你可以使用PIL(Python Imaging Library)或其更新版本Pillow库来获取图片的宽度和高度。这两个库提供了丰富的图像处理功能,包括获取图像元数据。以下是一个简单的例子:
```python
from PIL import Image
def get_image_size(image_path):
with Image.open(image_path) as img:
width, height = img.size
return width, height
# 使用方法
image_path = 'path_to_your_image.jpg'
width, height = get_image_size(image_path)
print(f"Image width: {width}, Image height: {height}")
相关问题
python 获取图片的宽高
以下是两种Python获取图片宽高的方法:
方法一:使用OpenCV库[^1]
```python
import cv2
file_path = 'C:/Users/admin/Pictures/scence/1.jpg'
img = cv2.imread(file_path)
sp = img.shape
height = sp # 图片的高度
width = sp # 图片的宽度
print("图片的宽度:", width)
print("图片的高度:", height)
```
方法二:使用Pillow库
```python
from PIL import Image
file_path = 'C:/Users/admin/Pictures/scence/1.jpg'
img = Image.open(file_path)
width, height = img.size
print("图片的宽度:", width)
print("图片的高度:", height)
```
获取图片宽高 Python cv2
可以使用OpenCV库中的cv2模块来获取图片的宽高。具体实现代码如下:
```python
import cv2
img = cv2.imread('image.jpg')
height, width, channels = img.shape
print('图片宽度为:', width)
print('图片高度为:', height)
```
其中,`img.shape`返回一个元组,包含三个值,分别是图片的高度、宽度和通道数。
相关问题:
1. 如何使用Python将两张图片拼接在一起?
2. 如何使用Python将图片转换为灰度图像?
3.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)