import numpy as np import cv2 from fastapi import HTTPException def preprocess_image(file): try: file.file.seek(0) image_bytes = file.file.read() nparr = np.frombuffer(image_bytes, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) if img is None: raise HTTPException(status_code=500, detail="Could not decode image.") img = cv2.resize(img, (299, 299)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img / 255.0 img = np.expand_dims(img, axis=0).astype(np.float32) return img except HTTPException: raise # Re-raise already defined HTTP errors except Exception as e: raise HTTPException( status_code=500, detail=f"Image preprocessing failed: {str(e)}" )