opencv-python输出图像宽度
时间: 2025-03-27 18:34:48 浏览: 30
### 如何使用 OpenCV-Python 将图像输出为特定宽度
为了调整图像到指定宽度并保持宽高比例,可以按照如下方式实现:
计算新的高度以维持原始图片的比例。这可以通过将目标宽度除以原图宽度再乘以其高度得出。
```python
import cv2
def resize_image_by_width(image_path, target_width):
# 读取图像
image = cv2.imread(image_path)
# 获取原始尺寸
original_height, original_width = image.shape[:2]
# 计算新的高度以保持纵横比不变
aspect_ratio = float(original_height) / float(original_width)
new_height = int(target_width * aspect_ratio)
# 调整大小后的图像
resized_image = cv2.resize(image, (target_width, new_height), interpolation=cv2.INTER_AREA)
return resized_image
# 示例调用
resized_img = resize_image_by_width('example.jpg', 800)
cv2.imshow('Resized Image', resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
上述代码定义了一个名为 `resize_image_by_width` 的函数,该函数接收两个参数:要调整大小的图像路径以及期望的目标宽度。此函数会返回一张已按给定宽度重新调整过的新图像对象[^1]。
阅读全文
相关推荐



















