可实现计算多张的加和平均数
from PIL import Image
import os
def calculate_pixel_percentages(image_path):
# 打开图像
image = Image.open(image_path)
# 转换为灰度图像
image = image.convert('L')
# 获取图像的宽度和高度
width, height = image.size
# 初始化计数器
crack_pixel_count = 0
non_crack_pixel_count = 0
# 遍历图像的每个像素
for y in range(height):
for x in range(width):
pixel_value = image.getpixel((x, y))
# 假设裂缝像素的值为255(白色),非裂缝像素的值为0(黑色)
if pixel_value == 255:
crack_pixel_count += 1
else:
non_crack_pixel_count += 1
# 计算百分比
total_pixels = width * height
crack_percentage = (crack_pixel_count / total_pixels) * 100
non_crack_percentage = (non_crack_pixel_count / total_pixels) * 100
# 返回结果
return crack_percentage, non_crack_percentage
def calculate_multiple_images(image_directory):
# 获取目录下的所有图像文件
image_files = [f for f in os.listdir(image_directory) if os.path.isfile(os.path.join(image_directory, f))]
# 初始化总和计数器
total_crack_pixels = 0
total_non_crack_pixels = 0
# 遍历每个图像文件
for image_file in image_files:
image_path = os.path.join(image_directory, image_file)
crack_pixels, non_crack_pixels = calculate_pixel_percentages(image_path)
# 更新总和计数器
total_crack_pixels += crack_pixels
total_non_crack_pixels += non_crack_pixels
# 打印结果
print("Image: ", image_file)
print("Crack pixels: ", crack_pixels)
print("Non-crack pixels: ", non_crack_pixels)
print()
# 计算平均数
total_images = len(image_files)
average_crack_pixels = total_crack_pixels / total_images
average_non_crack_pixels = total_non_crack_pixels / total_images
# 打印总和和平均数结果
print("Total crack pixels: ", total_crack_pixels)
print("Total non-crack pixels: ", total_non_crack_pixels)
print("Average crack pixels: ", average_crack_pixels)
print("Average non-crack pixels: ", average_non_crack_pixels)
# 替换为你的图像文件夹路径
image_directory = " "
calculate_multiple_images(image_directory)