from PIL import Image
import numpy as np

def expand_center_line(image_path, output_path="expanded_center_line.png", expanded_height=300):
    """
    在一张灰色底的图片文件中找到水平亮线的中心位置，
    从原图中提取该中心线位置的一行像素，
    并将其复制展宽为一个指定高度的图片

    """
    try:
        # 打开图像并转换为灰度图
        img_gray = Image.open(image_path).convert("L")
        width, height = img_gray.size
        np_img_gray = np.array(img_gray)

        # 寻找亮线的垂直范围
        bright_rows = []
        for y in range(height):
            # 检查该行是否存在明显比背景亮的像素
            if np.any(np_img_gray[y, :] > np.mean(np_img_gray) + 20): 
                bright_rows.append(y)

        if not bright_rows:
            print("未找到明显的水平亮线。")
            return

        # 找到亮线的最高和最低边缘
        min_bright_row = min(bright_rows)
        max_bright_row = max(bright_rows)

        # 计算亮线的中心位置 (垂直方向)
        center_y = (min_bright_row + max_bright_row) // 2

        # 打开原图提取像素
        img_color = Image.open(image_path).convert("RGB")
        pixels = img_color.load()

        # 创建一个新的空图像
        expanded_img = Image.new("RGB", (width, expanded_height))
        expanded_pixels = expanded_img.load()

        # 将中心线像素复制到新图像的每一行
        for y_new in range(expanded_height):
            for x in range(width):
                expanded_pixels[x, y_new] = pixels[x, center_y]

        # 保存展宽后的图像
        expanded_img.save(output_path)
        print(f"已将中心线像素提取并展宽为 {expanded_height} 像素高度的图片，保存到 '{output_path}'。")

    except FileNotFoundError:
        print(f"错误：找不到文件 '{image_path}'。")
    except Exception as e:
        print(f"发生错误：{e}")

if __name__ == "__main__":
    # 替换为你的图片文件路径
    input_image_path = "dubhe-rotated.png"
    expand_center_line(input_image_path, expanded_height=300)
