Spaces:
Sleeping
Sleeping
Create image_preprocess.py
Browse files- image_preprocess.py +39 -0
image_preprocess.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import logging
|
| 4 |
+
import psutil
|
| 5 |
+
|
| 6 |
+
def log_memory(stage):
|
| 7 |
+
memory = psutil.virtual_memory()
|
| 8 |
+
logging.info(f"{stage} - Memory usage: {memory.percent}%")
|
| 9 |
+
|
| 10 |
+
def preprocess(image_path):
|
| 11 |
+
log_memory("Before loading image")
|
| 12 |
+
try:
|
| 13 |
+
# Define the size to which the image will be resized
|
| 14 |
+
image_size = 224 # Reduce to 128x128 for memory efficiency
|
| 15 |
+
|
| 16 |
+
# Load the image using OpenCV
|
| 17 |
+
image = cv2.imread(image_path)
|
| 18 |
+
|
| 19 |
+
# Handle grayscale images
|
| 20 |
+
if len(image.shape) == 2: # If grayscale
|
| 21 |
+
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
|
| 22 |
+
|
| 23 |
+
# Convert the image from BGR to RGB format
|
| 24 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 25 |
+
|
| 26 |
+
# Resize the image
|
| 27 |
+
image = cv2.resize(image, (image_size, image_size))
|
| 28 |
+
|
| 29 |
+
# Expand dimensions to match model input
|
| 30 |
+
X = np.expand_dims(image, axis=0)
|
| 31 |
+
|
| 32 |
+
# Normalize the pixel values to 0-1
|
| 33 |
+
X = X / 255.0
|
| 34 |
+
|
| 35 |
+
log_memory("After preprocessing")
|
| 36 |
+
return X
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logging.error(f"Error in preprocessing: {e}")
|
| 39 |
+
raise
|