任务:有一一对应的图片多组如下,希望统计灰色部分原有grb平均值,彩色部分rgb平均值。
方法:由下图对各个像素分析,分为3类,并记录坐标,根据坐标统计上图的rgb平均值,结果放在一张Excel中。
import os
import time
from PIL import Image
import openpyxl
def process_images(folder1, folder2, output_excel):
start_time = time.time() #
# 创建一个新的Excel工作簿
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Image Analysis"
ws.append(["Image Name", "Category", "Average R", "Average G", "Average B"])
# 获取文件夹中的所有文件名
files1 = [f for f in os.listdir(folder1) if f.endswith('.jpg')]
files2 = [f for f in os.listdir(folder2) if f.endswith('.jpg.jpg')]
# 确保文件名对应
for file1 in files1:
file2 = file1 + ".jpg"
if file2 in files2:
img1_path = os.path.join(folder1, file1)
img2_path = os.path.join(folder2, file2)
img1 = Image.open(img1_path)
img2 = Image.open(img2_path)
if img1.size != img2.size:
print(f"Skipping {file1} and {file2} due to size mismatch.")
continue
pixels1 = img1.load()
pixels2 = img2.load()
categories = {
'black': {'count': 0, 'total_r': 0, 'total_g': 0, 'total_b': 0},
'gray': {'count': 0, 'total_r': 0, 'total_g': 0, 'total_b': 0},
'other': {'count': 0, 'total_r': 0, 'total_g': 0, 'total_b': 0}
}
for y in range(img1.height):
for x in range(img1.width):
r2, g2, b2 = pixels2[x, y]
if (r2, g2, b2) == (0, 0, 0):
category = 'black'
elif (r2, g2, b2) == (169, 169, 169):
category = 'gray'
else:
category = 'other'
r1, g1, b1 = pixels1[x, y]
categories[category]['count'] += 1
categories[category]['total_r'] += r1
categories[category]['total_g'] += g1
categories[category]['total_b'] += b1
for category, data in categories.items():
if data['count'] > 0:
avg_r = data['total_r'] / data['count']
avg_g = data['total_g'] / data['count']
avg_b = data['total_b'] / data['count']
ws.append([file1, category, avg_r, avg_g, avg_b])
else:
ws.append([file1, category, 0, 0, 0])
wb.save(output_excel)
end_time = time.time() # 结束计时
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds")
# 使用示例
folder1 = '/folder1' # 文件夹路径
folder2 = '/folder2' #
output_excel = 'output.xlsx'
process_images(folder1, folder2, output_excel)