opencv批量修改图像尺寸
时间: 2023-09-14 16:11:42 浏览: 48
你可以使用OpenCV的resize函数来批量修改图像尺寸。以下是一个示例代码,可以将指定文件夹下的所有图像缩小到一半大小并保存在另一个文件夹中:
``` python
import cv2
import os
# 原始图像文件夹和保存文件夹
input_folder = 'input_folder'
output_folder = 'output_folder'
# 获取原始图像文件夹中的所有图像文件名
img_files = os.listdir(input_folder)
# 循环遍历所有图像文件
for img_file in img_files:
# 读取图像
img = cv2.imread(os.path.join(input_folder, img_file))
# 调整图像尺寸
img_resized = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
# 保存调整后的图像到保存文件夹
cv2.imwrite(os.path.join(output_folder, img_file), img_resized)
```
在上面的代码中,我们使用os模块获取了原始图像文件夹中的所有图像文件名,并使用cv2.imread函数读取了每个图像文件。然后,我们使用cv2.resize函数将图像缩小到一半大小,并使用cv2.imwrite函数保存调整后的图像到保存文件夹中。
相关问题
opencv批量修改图片尺寸
在 OpenCV 中,可以使用 `resize` 函数来修改图片尺寸。以下是一个示例代码,可以批量修改指定目录下的所有图片尺寸:
```python
import cv2
import os
# 定义图片目录和目标尺寸
img_dir = 'path/to/images'
target_size = (640, 480)
# 遍历图片目录
for filename in os.listdir(img_dir):
# 读取图片
img_path = os.path.join(img_dir, filename)
img = cv2.imread(img_path)
# 修改尺寸
resized = cv2.resize(img, target_size)
# 保存修改后的图片
cv2.imwrite(img_path, resized)
```
在上述代码中,我们使用 `os.listdir` 函数遍历指定目录下的所有文件名。对于每个文件,我们使用 `cv2.imread` 函数读取为图片对象。然后使用 `cv2.resize` 函数修改尺寸,并将修改后的图片使用 `cv2.imwrite` 函数保存到原文件路径。最终,所有图片的尺寸都会被修改为指定的目标尺寸。
opencv批量处理图像
您好!对于批量处理图像,OpenCV提供了很多方便的函数和工具。以下是一些常见的图像处理任务及其相应的OpenCV函数示例:
1. 读取图像文件夹中的所有图像:
```python
import cv2
import os
folder_path = 'your_folder_path'
image_files = os.listdir(folder_path)
for image_file in image_files:
image_path = os.path.join(folder_path, image_file)
image = cv2.imread(image_path)
# 在这里添加您的图像处理代码
cv2.imshow('Processed Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. 调整图像大小:
```python
resized_image = cv2.resize(image, (new_width, new_height))
```
3. 转换图像为灰度图:
```python
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
```
4. 对图像进行模糊处理:
```python
blurred_image = cv2.blur(image, (kernel_size, kernel_size))
```
5. 对图像进行边缘检测:
```python
edges = cv2.Canny(image, threshold1, threshold2)
```
6. 对图像进行阈值处理:
```python
ret, thresholded_image = cv2.threshold(image, threshold_value, max_value, cv2.THRESH_BINARY)
```
7. 保存图像:
```python
save_path = 'your_save_path'
cv2.imwrite(save_path, image)
```
您可以根据需要使用这些示例,并根据自己的需求进行修改。希望对您有所帮助!如果有任何问题,请随时提问。