import cv2
import os
import numpy as np
import matplotlib.pyplot as plt

EDGE_COUNT = 1

image_files = [f for f in os.listdir() if f.endswith('******.jpg') or f.endswith('******.jpeg')]

if len(image_files) == 0:
    print("Error: No JPEG or JPG images found in the current folder.")
else:
    for img_path in image_files:
        print(f"Processing {img_path}...")  

        canvas_size = (30000, 30000)
        background_color = (0, 0, 0)  

        img = cv2.imread(img_path)

        if img is None:
            print(f"Error: Failed to load image from {img_path}")
            continue  

        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img_height, img_width, _ = img.shape

        canvas_size = (30000, 30000)
        canvas = np.full((canvas_size[0], canvas_size[1], 3), background_color, dtype=np.uint8)

        center_y = canvas_size[0] // 2
        center_x = canvas_size[1] // 2
        start_y = center_y - img_height // 2
        start_x = center_x - img_width // 2
        canvas[start_y:start_y + img_height, start_x:start_x + img_width] = img

        non_black_pixels = np.where(np.any(canvas != background_color, axis=-1))
        pixel_coords = np.column_stack(non_black_pixels)

        center_of_mass = np.mean(pixel_coords, axis=0).astype(int)

        theta_values = np.arange(0, 360, 0.1) 
        max_radius = min(center_of_mass[0], center_of_mass[1], canvas_size[0] - center_of_mass[0], canvas_size[1] - center_of_mass[1])

        all_colors = np.zeros((max_radius, len(theta_values), 3), dtype=np.uint8) 
        y_black_positions = []  

        for i, theta in enumerate(theta_values):
            adjusted_theta = (theta + 90) % 360

            radians = np.deg2rad(adjusted_theta)  
            unit_vector = np.array([np.cos(radians), np.sin(radians)])

            consecutive_white_count = 0

            for r in range(max_radius):
                coord = center_of_mass + (r * unit_vector).astype(int)
                if 0 <= coord[0] < canvas_size[0] and 0 <= coord[1] < canvas_size[1]:
                    all_colors[r, i] = canvas[coord[0], coord[1]]

                    if np.all(all_colors[r, i] == 255):  
                        consecutive_white_count += 1
                        if consecutive_white_count >= EDGE_COUNT: 
                            y_black_positions.append((i, r))  
                            break
                    else:
                        consecutive_white_count = 0
                else:
                    break 

        stretched_colors = np.zeros((1000, len(theta_values), 3), dtype=np.uint8)

        y_black_dict = {pos[0]: max(pos[1] - EDGE_COUNT, 0) for pos in y_black_positions}  

        for i, theta in enumerate(theta_values):
            y_black = y_black_dict.get(i, 1000) 

            for new_r in range(1000):
                original_r = int(new_r * y_black / 999)  
                stretched_colors[new_r, i] = all_colors[min(original_r, max_radius - 1), i]

        plt.figure(figsize=(10, 6))
        plt.imshow(stretched_colors, origin='lower')  
        plt.title(f'Stretched Polar Image for {img_path}')
        plt.xlabel('Angle (degrees)')
        plt.ylabel('Stretched Radius (0-1000)')
        plt.show()
