|
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): |
|
|
|
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): |
|
|
|
image_np = np.array(image) |
|
|
|
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): |
|
|
|
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) |
|
|
|
|
|
|
|
def preprocess_image004(image): |
|
|
|
image_np = np.array(image) |
|
|
|
gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY) |
|
|
|
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): |
|
|
|
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): |
|
|
|
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) |
|
|