Stomach_Cancer_Pytorch/utils/convert_to_freq.py

121 lines
4.0 KiB
Python

import cv2
import numpy as np
import os
import glob
import sys
# Add project root to sys.path to allow importing from utils and other modules
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir) # d:\Programing\stomach_cancer\Pytorch
if project_root not in sys.path:
sys.path.append(project_root)
from utils.Stomach_Config import Save_Result_File_Config, Loading_Config
import utils.Stomach_Config as SC
def apply_lpf(fft_shift, radius):
rows, cols = fft_shift.shape
crow, ccol = rows // 2, cols // 2
# Create a mask
mask = np.zeros((rows, cols), np.uint8)
center = [crow, ccol]
x, y = np.ogrid[:rows, :cols]
mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= radius*radius
mask[mask_area] = 1
# Apply mask
fshift_filtered = fft_shift * mask
return fshift_filtered
def process_image(img_path, save_path):
# Read image
img = cv2.imread(img_path)
if img is None:
print(f"Failed to read {img_path}")
return
# Process each channel independently
# Split channels: B, G, R
channels = cv2.split(img)
filtered_channels = []
# Define cutoff frequency
cutoff_freq = 15
for channel in channels:
# FFT
f = np.fft.fft2(channel)
fshift = np.fft.fftshift(f)
# Apply LPF
fshift_filtered = apply_lpf(fshift, cutoff_freq)
# Inverse FFT
f_ishift = np.fft.ifftshift(fshift_filtered)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)
# Clip and convert to uint8
img_back = np.clip(img_back, 0, 255).astype(np.uint8)
filtered_channels.append(img_back)
# Merge channels back
result_img = cv2.merge(filtered_channels)
# Save
os.makedirs(os.path.dirname(save_path), exist_ok=True)
cv2.imwrite(save_path, result_img)
def resolve_path(base_path, relative_path):
# relative_path starts with ../Dataset, which is relative to Pytorch folder (project_root)
# So we join project_root and relative_path
return os.path.abspath(os.path.join(base_path, relative_path))
def main():
print(f"Project Root: {project_root}")
# Map input source keys to output destination keys in config
# Loading_Config has "Train_Data_Root" and "Test_Data_Root"
# Save_Result_File_Config has "Training_Image_LPF_Image" and "Testing_Image_LPF_Image"
task_map = [
(Loading_Config["Train_Data_Root"], Save_Result_File_Config["Training_Image_LPF_Image"]),
(Loading_Config["Test_Data_Root"], Save_Result_File_Config["Testing_Image_LPF_Image"])
]
count = 0
for src_rel, dst_rel in task_map:
# Resolve paths
src_dir = resolve_path(project_root, src_rel)
dst_dir = resolve_path(project_root, dst_rel)
print(f"Processing from {src_dir} to {dst_dir}")
if not os.path.exists(src_dir):
print(f"Source path not found: {src_dir}")
continue
# Walk through directory
for root, dirs, files in os.walk(src_dir):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
src_path = os.path.join(root, file)
# Construct relative path from src_dir to preserve structure (Category/Filename)
# rel_path will be like "Normal_Crop/A123.jpg"
rel_path = os.path.relpath(src_path, src_dir)
# Construct destination path
dest_path = os.path.join(dst_dir, rel_path)
process_image(src_path, dest_path)
count += 1
if count % 100 == 0:
print(f"Processed {count} images...")
print(f"Processing complete. Total {count} images processed.")
if __name__ == "__main__":
main()