在python中使用opencv获取图片的尺寸
时间: 2023-03-31 16:02:55 浏览: 287
可以使用cv2模块中的函数cv2.imread()读取图片,然后使用shape属性获取图片的尺寸,例如:
import cv2
img = cv2.imread('image.jpg')
height, width, channels = img.shape
print('图片尺寸为:{}x{}'.format(width, height))
相关问题
python如何使用opencv获取图片中最长的轮廓,代码示例
您好,以下是使用OpenCV获取图片中最长轮廓的Python代码示例:
```
import cv2
# 读取图片
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用Canny算子进行边缘检测
edges = cv2.Canny(gray, 50, 150)
# 轮廓检测
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 找到最长的轮廓
max_contour = max(contours, key=cv2.contourArea)
# 绘制最长的轮廓
cv2.drawContours(img, [max_contour], -1, (0, 255, 0), 2)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
希望能对您有所帮助。如果您有其他问题,欢迎继续提问。
opencv获取图片尺寸
### 如何使用 OpenCV 获取图片尺寸
在 Python 中,可以利用 `cv2` 库来读取并获取图像的尺寸。通过调用 `shape` 属性能够轻松获得图像的高度、宽度以及通道数。
当一幅彩色图像是以 NumPy 数组形式存储时,数组形状会返回三个值组成的元组 `(height, width, channels)` 。对于灰度图像,则只会有两个值 `(height, width)` [^1]。
下面是一个简单的例子展示如何实现这一点:
```python
import cv2
image_path = 'lena.jpg' # 假设这是要处理的图像文件路径
img = cv2.imread(image_path)
if img is not None:
dimensions = img.shape
height, width, channels = dimensions[:3]
print(f"Image Dimension : {dimensions}")
print(f"Image Height : {height}")
print(f"Image Width : {width}")
print(f"Number of Channels : {channels}")
else:
print("Could not read the image.")
```
这段代码首先尝试加载指定路径下的图像;如果成功加载,则打印出该图像的具体维度信息——高度、宽度和颜色通道数量。需要注意的是,在某些情况下(比如路径错误或存在中文字符),可能会导致无法正确读取图像文件[^2]。
阅读全文
相关推荐
















