Files
ctf/2025/hack.lu/rev/FLAN/analyze_pixels.py
2025-10-19 20:35:43 +02:00

71 lines
2.9 KiB
Python

import cv2
import numpy as np
def measure_stripe_width(image_path):
# 1. Load the image in grayscale
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
print(f"Error: Could not load image from {image_path}")
return
# 2. Check if the image has already been binarized, otherwise apply thresholding
# For clean black/white images, we can assume a simple global threshold is sufficient
# We invert the colors so that the features we are interested in (stripes) are white (255)
_, binary_img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)
# Optional: Display the binary image to verify
# cv2.imshow('Binary Image', binary_img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# 3. Analyze a horizontal line (a row) to find the stripe widths
# We'll take a row from the middle of the image for robustness
row_index = binary_img.shape[0] // 2
row = binary_img[row_index, :]
# 4. Find the horizontal positions where the color changes (edges)
# We look for where the pixel value changes from one column to the next
# A change happens where the difference is non-zero
edges = np.where(np.abs(np.diff(row)) > 0)[0] + 1
# Add the image boundaries as 'edges' for the first and last stripe measurement
edges = np.insert(edges, 0, 0)
edges = np.append(edges, img.shape[1])
# 5. Calculate the width of each stripe
stripe_widths = np.diff(edges)
# 6. Separate widths for black and white stripes
# Stripes start at column 0. If the first pixel (row[0]) is black (0),
# then the widths are [Black, White, Black, White, ...]
# If the first pixel is white (255), then the widths are [White, Black, White, Black, ...]
is_first_stripe_white = row[0] == 255
if is_first_stripe_white:
white_widths = stripe_widths[::2] # First, third, fifth, etc.
black_widths = stripe_widths[1::2] # Second, fourth, sixth, etc.
else:
black_widths = stripe_widths[::2] # First, third, fifth, etc.
white_widths = stripe_widths[1::2] # Second, fourth, sixth, etc.
# 7. Calculate and print the average widths
avg_white_width = np.mean(white_widths) if white_widths.size > 0 else 0
avg_black_width = np.mean(black_widths) if black_widths.size > 0 else 0
print(f"Total stripes detected (alternating colors): {len(stripe_widths)}")
print(f"Average White Stripe Width: {avg_white_width:.2f} pixels")
print(f"Average Black Stripe Width: {avg_black_width:.2f} pixels")
print(f"All Stripe Widths (alternating): {stripe_widths}")
for s in stripe_widths:
print(s)
measure_stripe_width("images/images-001.png")
# Example usage: Replace 'path/to/your/image.png' with the actual path
# The image should be a clear pattern of vertical black and white stripes.
# measure_stripe_width('path/to/your/image.png')
# You'll need an image to test this.