cv2.imwrite
时间: 2023-10-19 07:16:56 浏览: 127
cv2.imwrite() is a function in the OpenCV (cv2) library in Python that is used to write an image to a specified file. The function takes two parameters - the file path where the image will be saved and the image array itself. Here is an example usage:
```
import cv2
# Read an image
img = cv2.imread("image.jpg")
# Convert the image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Save the grayscale image to a file
cv2.imwrite("grayscale_image.jpg", gray_img)
```
In this example, we first read an image file using cv2.imread(), then convert it to grayscale using cv2.cvtColor(). Finally, we use cv2.imwrite() to save the grayscale image to a file named "grayscale_image.jpg".
相关问题
cv2.imwrite储存地址
cv2.imwrite() 函数的第一个参数是储存图像的完整文件路径,包括文件名和文件扩展名。例如:
```python
import cv2
# 读取图像
img = cv2.imread("image.jpg")
# 储存图像到指定路径
cv2.imwrite("path/to/save/image_copy.jpg", img)
```
在上面的例子中,图像将被保存为 "image_copy.jpg" 文件,并储存在指定的路径 "path/to/save/" 下。你可以根据需要自定义储存路径和文件名。确保路径存在并有写入权限,否则会引发错误。
将多张图片依次存储cv2.imwrite()代码
可以将多张图片存储在同一个文件夹内,然后使用以下代码将它们依次存储:
```
import cv2
import os
image_folder = 'path/to/folder/with/images'
output_folder = 'path/to/output/folder'
for filename in os.listdir(image_folder):
image = cv2.imread(os.path.join(image_folder, filename))
output_path = os.path.join(output_folder, filename)
cv2.imwrite(output_path, image)
```
在代码中,首先定义了一个包含图片的文件夹路径和一个存储输出图片的文件夹路径。然后使用 `os.listdir()` 函数获取图片文件夹中的所有文件名,通过 `cv2.imread()` 函数读取每个文件并将其存储到 `output_folder` 中。
阅读全文