##1.影像調整清晰、對比度調整 import cv2 import numpy as np def adjustsharpness(image, alpha=1.9):…
- User
##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)
- Assistant
您好,感谢您提供了您的图像处理代码。请问您需要什么方面的帮助呢?
- 您是否在运行代码时遇到了错误或异常?
- 您想了解代码的运行原理和流程吗?
- 您需要优化代码的某些部分,或者实现其他功能吗?
请您详细描述您的需求或遇到的问题,我会尽力为您解答和协助。