我需要一段python代码,要求如下:读取指定文件夹中的所有图片,将图片中的不同不规则白色图案用不同颜色填充,黑色图案不变
时间: 2024-02-05 15:12:31 浏览: 22
好的,根据您的要求,以下是一个用Python处理图片的示例代码,代码中会读取指定文件夹下的所有图片,并将其中的不同不规则白色图案用不同颜色填充,黑色图案不变:
``` python
from PIL import Image, ImageDraw, ImageChops, ImageColor
import os
# 读取指定文件夹下的所有图片
folder_path = "/path/to/folder" # 替换为您想要处理的文件夹路径
output_path = "/path/to/output" # 替换为输出的文件夹路径
if not os.path.exists(output_path):
os.makedirs(output_path)
for file_name in os.listdir(folder_path):
if file_name.endswith('.jpg') or file_name.endswith('.png'):
file_path = os.path.join(folder_path, file_name)
output_file_path = os.path.join(output_path, file_name)
with Image.open(file_path) as image:
# 将图像转换为灰度图
gray_image = image.convert('L')
# 对图像进行二值化处理,得到黑白图像
threshold = 200 # 替换为您想要的阈值
binary_image = gray_image.point(lambda x: 0 if x < threshold else 255)
# 获取白色区域的轮廓
contour = ImageChops.difference(binary_image, Image.new(binary_image.mode, binary_image.size, 255)).getdata(0)
# 将轮廓转换为一个二维数组
contour_arr = list(contour)
width, height = binary_image.size
contour_arr = [contour_arr[i:i+width] for i in range(0, len(contour_arr), width)]
# 获得白色区域的数量,每一个白色区域用不同的颜色填充
white_count = len(set(contour_arr))
colors = [ImageColor.getrgb('hsl(%d, 100%%, 50%%)' % (i * 360 / white_count)) for i in range(white_count)]
# 获得每个区域的边界框
boxes = {}
for y, row in enumerate(contour_arr):
for x, pixel in enumerate(row):
if pixel == 0:
color_index = contour_arr[y][x-1]
if color_index > 0:
if color_index not in boxes:
boxes[color_index] = [x, y, x, y]
else:
boxes[color_index][2] = max(boxes[color_index][2], x)
boxes[color_index][3] = max(boxes[color_index][3], y)
# 将每个区域填充上颜色
with Image.new(image.mode, image.size) as result_image:
draw = ImageDraw.Draw(result_image)
draw.rectangle((0, 0, width, height), fill=(0, 0, 0))
for i, color in enumerate(colors):
if i + 1 in boxes:
box = boxes[i+1]
draw.rectangle(box, fill=color)
result_image.save(output_file_path)
```
希望这段代码能够满足您的需求,如果您还有其他问题,请继续提问。