python图像二值化并保存到指定文件夹
时间: 2023-08-01 09:09:30 浏览: 42
以下是Python中使用OpenCV库进行图像二值化并保存到指定文件夹的示例代码:
```python
import cv2
import os
# 读取图像
img = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)
# 进行二值化处理
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 创建保存文件夹
if not os.path.exists('binarized_images'):
os.makedirs('binarized_images')
# 保存二值化后的图像
cv2.imwrite('binarized_images/example_binarized.jpg', thresh)
```
上述代码中,首先使用`cv2.imread`函数读取一张灰度图像,然后使用`cv2.threshold`函数对图像进行二值化处理。接着,使用`os.makedirs`函数创建一个名为`binarized_images`的文件夹,如果该文件夹已经存在,则不进行任何操作。最后,使用`cv2.imwrite`函数将二值化后的图像保存到`binarized_images`文件夹下并命名为`example_binarized.jpg`。
相关问题
基于python用opencv实现批量处理图像二值化
可以回答这个问题。使用Python和OpenCV可以实现批量处理图像二值化。可以使用cv2.threshold()函数来实现二值化,使用os模块来批量读取和保存图像。具体实现可以参考以下代码:
```python
import cv2
import os
# 定义二值化函数
def binarize(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
return binary
# 定义批量处理函数
def batch_binarize(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.jpg') or filename.endswith('.png'):
img_path = os.path.join(input_dir, filename)
img = cv2.imread(img_path)
binary = binarize(img)
output_path = os.path.join(output_dir, filename)
cv2.imwrite(output_path, binary)
# 调用批量处理函数
batch_binarize('input_dir', 'output_dir')
```
其中,input_dir为输入图像文件夹路径,output_dir为输出图像文件夹路径。该代码会将input_dir文件夹中所有jpg和png格式的图像进行二值化处理,并保存到output_dir文件夹中。
用python语言写批处理实现图像二值化的代码
以下是使用Python实现批处理图像二值化的代码:
```python
from PIL import Image
import os
# 设置二值化阈值
threshold = 150
# 遍历指定目录下的所有图片文件
for file in os.listdir('path/to/images/folder'):
if file.endswith('.jpg') or file.endswith('.png'):
# 打开图像文件
image = Image.open(os.path.join('path/to/images/folder', file))
# 将图像转为灰度图
gray_image = image.convert('L')
# 获取图像宽度和高度
width, height = gray_image.size
# 遍历图像的每一个像素,并进行二值化处理
for x in range(width):
for y in range(height):
pixel = gray_image.getpixel((x, y))
if pixel < threshold:
gray_image.putpixel((x, y), 0)
else:
gray_image.putpixel((x, y), 255)
# 保存处理后的图像文件
gray_image.save(os.path.join('path/to/output/folder', file))
```
需要注意的是,上述代码中的`threshold`变量用于设置二值化阈值,可以根据实际情况进行调整。同时,需要将代码中的`path/to/images/folder`和`path/to/output/folder`替换为实际的图像文件夹路径和输出文件夹路径。