import os
import pickle
from PIL import Image
import math
def extract_black_pixels_in_fans(image_paths, angle, num_fans, threshold=10):
results = {}
for path in image_paths:
img = Image.open(path).convert('RGB')
width, height = img.size
center = (width // 2, height // 2)
radius = min(width, height) // 2
center_x, center_y = center
if center_x > width or center_y > height:
raise ValueError("Center point is out of the image bounds.")
fan_width = angle / num_fans
black_fan_pixel_counts = [0] * num_fans
for i in range(num_fans):
start_angle = (i * fan_width) - angle / 2
end_angle = ((i + 1) * fan_width) - angle / 2
for r in range(radius):
for theta in [math.radians(a) for a in range(int(start_angle), int(end_angle))]:
x = int(center_x + r * math.cos(theta))
y = int(center_y + r * math.sin(theta))
if 0 <= x < width and 0 <= y < height:
pixel = img.getpixel((x, y))
if max(pixel) <= threshold:
black_fan_pixel_counts[i] += 1
results[path] = black_fan_pixel_counts
return results
def process_directory(directory, angle, num_fans, threshold=10):
image_paths = [os.path.join(directory, f) for f in os.listdir(directory) if f.lower().endswith(('.jpg', '.jpeg'))]
return extract_black_pixels_in_fans(image_paths, angle, num_fans, threshold)
def save_results_to_pickle(results, filename):
with open(filename, 'wb') as f:
pickle.dump(results, f)
def main(root_directory):
for root, dirs, files in os.walk(root_directory):
if dirs: # 只處理含有子目錄的目錄
for directory in dirs:
full_directory_path = os.path.join(root, directory)
results = process_directory(full_directory_path, angle=360, num_fans=36)
pickle_filename = os.path.splitext(os.path.basename(full_directory_path))[0] + '.pickle'
save_results_to_pickle(results, pickle_filename)
print(f"Processed directory '{full_directory_path}' and saved results to '{pickle_filename}'.")
if __name__ == "__main__":
main("ROOT_DIRECTORY_PATH") # 替換為你的根目錄路徑