import cv2 | |
import numpy as np | |
from PIL import Image, ImageEnhance | |
# 方案一 | |
def preprocess_image001(image): | |
# 將影像轉換為 NumPy 數組 | |
image = np.array(image) | |
# 轉為灰階影像 | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
# 調整對比度 | |
enhancer = ImageEnhance.Contrast(Image.fromarray(gray)) | |
enhanced_image = enhancer.enhance(2) | |
# 二值化 | |
_, binary = cv2.threshold(np.array(enhanced_image), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) | |
# 去雜訊 | |
denoised = cv2.fastNlMeansDenoising(binary, None, 30, 7, 21) | |
return Image.fromarray(denoised) |