File size: 980 Bytes
e651999
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03b6d75
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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)


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)