Luke
no message
0347dd6
raw
history blame
3.65 kB
import cv2
import numpy as np
from PIL import Image, ImageEnhance
def PreprocessImg(image):
if image is None:
raise ValueError("尚未上傳圖片!")
# 方案一
pre_img_001 = preprocess_image001(image)
# 方案二
pre_img_002 = preprocess_image002(image)
# 方案三
pre_img_003 = preprocess_image003(image)
# 方案四
pre_img_004 = preprocess_image004(image)
# 方案五
pre_img_005 = preprocess_image005(image)
return pre_img_001, pre_img_002, pre_img_003, pre_img_004, pre_img_005
# 方案一
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)
# 方案二
def preprocess_image002(image):
# 將 PIL Image 轉換為 numpy array
image_np = np.array(image)
# 使用 OpenCV 進行預處理
gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY) # 灰階化
gray = cv2.bilateralFilter(gray, 11, 17, 17) # 雙邊濾波去噪
edged = cv2.Canny(gray, 30, 200) # 邊緣檢測
return Image.fromarray(edged)
# 方案三:自適應門檻和形態學變換
def preprocess_image003(image):
# 將 PIL Image 轉換為 numpy array
image_np = np.array(image)
# 轉為灰階影像
gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
# 自適應門檻處理
adaptive_thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
# 形態學變換 (開運算) 去除小噪點
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
morph = cv2.morphologyEx(adaptive_thresh, cv2.MORPH_OPEN, kernel)
return Image.fromarray(morph)
# 方案四:CLAHE(限制對比度自適應直方圖均衡)
def preprocess_image004(image):
# 將 PIL Image 轉換為 numpy array
image_np = np.array(image)
# 轉為灰階影像
gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
# 應用 CLAHE
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
clahe_image = clahe.apply(gray)
# 二值化
_, binary = cv2.threshold(clahe_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return Image.fromarray(binary)
# 方案五:直方圖均衡化和高斯模糊
def preprocess_image005(image):
# 將 PIL Image 轉換為 numpy array
image_np = np.array(image)
# 轉為灰階影像
gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
# 直方圖均衡化
equalized = cv2.equalizeHist(gray)
# 高斯模糊
blurred = cv2.GaussianBlur(equalized, (5, 5), 0)
# 二值化
_, binary = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return Image.fromarray(binary)
# 方案六:自適應去噪與銳化
def preprocess_image006(image):
# 將 PIL Image 轉換為 numpy array
image_np = np.array(image)
# 轉為灰階影像
gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
# 自適應去噪
denoised = cv2.fastNlMeansDenoising(gray, None, 30, 7, 21)
# 銳化
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
sharpened = cv2.filter2D(denoised, -1, kernel)
# 二值化
_, binary = cv2.threshold(sharpened, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return Image.fromarray(binary)