Spaces:
Build error
Build error
File size: 3,847 Bytes
c8bfd94 | 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | import cv2
from pathlib import Path
import numpy as np
from matplotlib import pyplot as plt
def Advanced_gray(image_path):
# Define the image you want to preprocess
IMG_NAME = image_path # π Change to your image name
SOURCE_IMG_PATH = Path("./") / IMG_NAME
DEST_IMG_PATH = Path("test") / IMG_NAME
# Ensure output directory exists
DEST_IMG_PATH.parent.mkdir(parents=True, exist_ok=True)
# Load in grayscale
img = cv2.imread(str(SOURCE_IMG_PATH), cv2.IMREAD_GRAYSCALE)
if img is None:
print(f"β Failed to load image: {SOURCE_IMG_PATH}")
return None
else:
print(f"β
Loaded image: {SOURCE_IMG_PATH.name}")
# Apply Gaussian blur to remove noise
img = cv2.GaussianBlur(img, (5, 5), 0)
# Apply adaptive thresholding
img = cv2.adaptiveThreshold(
img, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
11, 2
)
# Save the processed image
cv2.imwrite(str(DEST_IMG_PATH), img)
print(f"β
Processed image saved to: {DEST_IMG_PATH}")
return img
# Sharpening function
def sharpen_image(image):
kernel = np.array([[0, -1, 0],
[-1, 5,-1],
[0, -1, 0]])
sharpened = cv2.filter2D(image, -1, kernel)
return sharpened
def enhance_contrast(image):
lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
cl = clahe.apply(l)
limg = cv2.merge((cl, a, b))
enhanced_img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
return enhanced_img
def modify_image(image_path):
x = Advanced_gray(image_path)
if x is None:
return None
y = sharpen_image(x)
# Convert grayscale to BGR before enhancing contrast
y_bgr = cv2.cvtColor(y, cv2.COLOR_GRAY2BGR)
z = enhance_contrast(y_bgr)
output_path = Path("test") / Path(image_path).name
cv2.imwrite(str(output_path), z)
return z
def batch_process_images(image_dir, limit=10):
image_dir_path = Path(image_dir)
output_dir = Path("test")
output_dir.mkdir(parents=True, exist_ok=True)
images_processed = 0
processed_images = []
for img_path in image_dir_path.glob("*.jpg"):
if images_processed >= limit:
break
print(f"Processing image: {img_path.name}")
processed_img = modify_image(str(img_path))
if processed_img is not None:
print(f"Saved processed image to: {output_dir / img_path.name}")
processed_images.append(processed_img)
images_processed += 1
else:
print(f"Failed to process image: {img_path.name}")
# Plot all processed images in a single plot
if processed_images:
cols = 5
rows = (len(processed_images) + cols - 1) // cols
plt.figure(figsize=(15, 3 * rows))
for i, img in enumerate(processed_images):
plt.subplot(rows, cols, i + 1)
if len(img.shape) == 2: # grayscale
plt.imshow(img, cmap='gray')
else:
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.tight_layout()
plt.show()
# if __name__ == "__main__":
# # Process a single image
# image_path = "data/10.jpg"
# processed_img = modify_image(image_path)
# if processed_img is not None:
# plt.figure(figsize=(6,6))
# if len(processed_img.shape) == 2:
# plt.imshow(processed_img, cmap='gray')
# else:
# plt.imshow(cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB))
# plt.axis('off')
# plt.show()
|