
python如何得到图像的长宽
用户关注问题
怎样使用Python获取图片的尺寸信息?
我想知道在Python中有没有简单的方法来获得一张图片的宽度和高度?
使用Pillow库读取图片尺寸
可以使用Python的Pillow库(PIL)来获取图像尺寸。加载图片文件后,可以通过image.size属性获得宽度和高度,例如:
from PIL import Image
img = Image.open('example.jpg')
width, height = img.size
print('宽度:', width, '高度:', height)
Python有没有其他库可以获取图像的长宽?
除了PIL外,有没有其他Python库能够方便地读取图片的宽度和高度?
使用OpenCV库获取图片尺寸
OpenCV是一个流行的计算机视觉库,也可以用来获取图像尺寸。用cv2.imread读取图像后,返回的是一个多维数组,可以通过shape属性获得高和宽,例如:
import cv2
img = cv2.imread('example.jpg')
height, width = img.shape[:2]
print('宽度:', width, '高度:', height)
如何获取网络图片的长宽信息?
如果图片是网络上的,我该如何使用Python获得它的尺寸?
先下载图片后读取尺寸
使用requests库先下载网络图片,然后通过Pillow等库读取尺寸。例如:
import requests
from io import BytesIO
from PIL import Image
url = 'http://example.com/image.jpg'
response = requests.get(url)
img = Image.open(BytesIO(response.content))
width, height = img.size
print('宽度:', width, '高度:', height)