使用opencv工具包完成一幅彩色图片的读取显示和保存
时间: 2024-09-07 07:05:51 浏览: 55
OpenCV 是一个广泛使用的计算机视觉库,它支持 Python,非常适合图像处理和计算机视觉应用。要使用 OpenCV 读取、显示和保存彩色图片,你可以按照以下步骤操作:
首先,确保你已经安装了 opencv-python 库。如果没有,可以通过 pip 安装:
```bash
pip install opencv-python
```
然后,你可以用以下 Python 代码完成这些功能:
```python
import cv2
# 读取图片
image_path = 'path_to_your_image.jpg' # 替换为你的图片路径
img = cv2.imread(image_path)
# 检查图片是否成功读取
if img is not None:
# 显示图片(BGR色彩空间)
cv2.imshow('Image', img)
# 添加等待时间,让用户看到图片,0表示一直显示直到关闭
cv2.waitKey(0)
# 键盘按下任意键后继续
cv2.destroyAllWindows()
# 保存图片
output_path = 'output_image.jpg' # 输出图片的新路径
cv2.imwrite(output_path, img)
else:
print("Failed to read the image.")
```
在这个例子中:
- `cv2.imread()` 函数用于从指定路径读取图片,返回的是一个 BGR 彩色通道组成的 numpy 数组。
- `cv2.imshow()` 将数组转换成图像显示在窗口上。
- `cv2.waitKey(0)` 让程序暂停等待用户按键,0 表示无限等待。
- `cv2.destroyAllWindows()` 关闭所有显示的图像窗口。
- `cv2.imwrite()` 用于保存图片。
阅读全文
相关推荐


















