##1.影像調整清晰、對比度調整
import cv2
import numpy as np

def adjust_sharpness(image, alpha=1.9):
    """調整圖像的清晰度"""
    # 創建一個高斯模糊的圖像
    blurred = cv2.GaussianBlur(image, (0, 0), 3)
    # 將原始圖像和模糊圖像進行線性混合
    sharpened = cv2.addWeighted(image, alpha, blurred, 1 - alpha, 0)
    return sharpened

def adjust_contrast(image, beta=90):
    """調整圖像的對比度"""
    # 將圖像轉換為浮點數格式
    image = image.astype(np.float32)
    # 調整對比度
    image = image * (1 + beta / 100.0)
    # 將圖像轉換回8位無符號整數格式
    image = np.clip(image, 0, 255).astype(np.uint8)
    return image

def adjust_brightness(image, gamma=1.0):
    """調整圖像的亮度"""
    inv_gamma = 1.0 / gamma
    table = np.array([((i / 255.0) ** inv_gamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
    return cv2.LUT(image, table)

def apply_blur(image, ksize=5):
    """應用模糊"""
    return cv2.GaussianBlur(image, (ksize, ksize), 0)

# 讀取圖像
image_path = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\2024.jpg"
image = cv2.imread(image_path)

# 檢查圖像是否成功加載
if image is None:
    raise ValueError(f"無法加載圖像: {image_path}")

# 調整清晰度
sharpened_image = adjust_sharpness(image, alpha=3)  # alpha值可調

# 調整對比度
contrast_image = adjust_contrast(sharpened_image, beta=20)  # beta值可調

# 調整亮度
brightness_adjusted_image = adjust_brightness(contrast_image, gamma=1.0)  # gamma值可調

# 應用模糊
blurred_image = apply_blur(brightness_adjusted_image, ksize=1)  # ksize值可調

# 保存結果
output_path = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-chane.png"
cv2.imwrite(output_path, blurred_image)

print(f"圖像已保存到 {output_path}")

# 顯示結果

cv2.waitKey(0)
cv2.destroyAllWindows()


##2.轉變黑白二值圖

from PIL import Image

def convert_to_binary(image_path: str, output_path: str, threshold: int = 128):
    # Open the image file
    img = Image.open(image_path)
    
    # Convert the image to grayscale
    grayscale_image = img.convert('L')  # 'L' mode is for grayscale
    
    # Apply the threshold to create a binary image
    binary_image = grayscale_image.point(lambda p: 255 if p > threshold else 0, mode='1')
    
    # Save the binary (black and white) image
    binary_image.save(output_path)

# Example usage:
# Convert an image named 'input_image.jpg' to a binary image and save it as 'output_image_binary.jpg'
convert_to_binary(r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-chane.png", r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-whileback.png", threshold=100)





##3.黑白圖手動細微調整
import cv2
import numpy as np

# 加載圖像
image_path = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-whileback.png"
original_image = cv2.imread(image_path)

# 檢查圖像是否成功加載
if original_image is None:
    raise ValueError(f"無法加載圖像: {image_path}")

# 初始化變量
drawing = False  # 是否正在繪圖
ix, iy = -1, -1  # 初始位置
brush_size = 5  # 初始筆大小
color = (0, 0, 0)  # 初始顏色為黑色
scale = 0.7  # 設置縮放比例為 133%
image = cv2.resize(original_image, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)
undo_stack = []  # 用於存儲圖像狀態的堆棧

# 繪圖回調函數
def draw(event, x, y, flags, param):
    global ix, iy, drawing, brush_size, color, image

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
        undo_stack.append(image.copy())  # 保存當前圖像狀態

    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            cv2.circle(image, (x, y), brush_size, color, -1)

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.circle(image, (x, y), brush_size, color, -1)

# 創建窗口並設置回調函數
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw)

# 顯示圖像並允許用戶調整筆大小
while True:
    cv2.imshow('image', image)
    key = cv2.waitKey(1) & 0xFF

    if key == ord('+'):
        brush_size += 1
    elif key == ord('-'):
        brush_size = max(1, brush_size - 1)
    elif key == ord('b'):
        color = (0, 0, 0)  # 黑色
    elif key == ord('w'):
        color = (255, 255, 255)  # 白色
    elif key == ord('s'):
        # 保存圖像
        cv2.imwrite(image_path, cv2.resize(image, (original_image.shape[1], original_image.shape[0]), interpolation=cv2.INTER_LINEAR))
        print(f"圖像已保存到 {image_path}")
    elif key == ord('u'):
        # 返回上一步
        if undo_stack:
            image = undo_stack.pop()
        else:
            print("沒有更多的返回步驟")
    elif key == 27:  # 按下 'ESC' 鍵退出
        break

cv2.destroyAllWindows()


##4.消除噪點
import cv2
import numpy as np

# 1. 读取图像
image_path = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-whileback.png"
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# 检查图像是否成功加载
if image is None:
    raise ValueError(f"无法加载图像: {image_path}")

# 2. 应用形态学操作来消除噪音斑点
# 创建一个核（kernel）
kernel = np.ones((3, 3), np.uint8)

# 进行开运算（先腐蚀后膨胀）去除小斑点
opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, iterations=0)

# 进行闭运算（先膨胀后腐蚀）填充小孔洞
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations=2)

# 3. 保存并显示结果
output_path = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-over.png"
cv2.imwrite(output_path, closing)

# 显示结果
cv2.imshow('Cleaned Image', closing)
cv2.waitKey(0)
cv2.destroyAllWindows()


##5.使用canny繪製成線圖
import cv2

# 1. 读取图像
image_path = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-over.png"
image = cv2.imread(image_path)

# 2. 转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 3. 使用高斯滤波器平滑图像，减少噪声
blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 1.4)

# 4. 使用 Canny 边缘检测
edges = cv2.Canny(blurred_image, threshold1=150, threshold2=200)

# 5. 保存并显示结果
output_path = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\west\cropped\20\2024-overload.png"
cv2.imwrite(output_path, edges)

# 显示结果
cv2.imshow('Canny Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()


###幫我把每個步驟合成並寫成軟體 ，只要執行就能在視覺化的軟體使用