Advertisement
Ahmed_Negm

Untitled

May 14th, 2025
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. def classify_single_image(model, image_path):
  2.     try:
  3.         # Read and preprocess the image
  4.         image = cv2.imread(image_path)
  5.         if image is None:
  6.             return None, "Could not load image"
  7.            
  8.         # Make a copy for display
  9.         display_image = copy.deepcopy(image)
  10.        
  11.         # Preprocess the image
  12.         image = cv2.resize(image, (CONST.IMG_SIZE, CONST.IMG_SIZE))
  13.         image = image.astype('float32') / 255.0  # Normalize to [0,1] range
  14.         image = np.expand_dims(image, axis=0)  # Add batch dimension
  15.        
  16.         # Make prediction
  17.         pred = model.predict(image, verbose=0)
  18.         class_idx = np.argmax(pred, axis=1)[0]
  19.         confidence = float(pred[0][class_idx])
  20.        
  21.         # Map prediction to class name
  22.         class_names = {0: 'Cat', 1: 'Dog'}
  23.         prediction = class_names[class_idx]
  24.        
  25.         # Add text to image
  26.         font = cv2.FONT_HERSHEY_SIMPLEX
  27.         location = (20, 30)
  28.         fontScale = 0.8
  29.         fontColor = (0, 255, 0)  # Green
  30.         lineType = 2
  31.        
  32.         text = f"{prediction}: {confidence:.2%}"
  33.         cv2.putText(display_image, text, location, font, fontScale, fontColor, lineType)
  34.        
  35.         # Save the annotated image
  36.         output_path = "prediction_result.jpg"
  37.         cv2.imwrite(output_path, display_image)
  38.        
  39.         return prediction, confidence, output_path
  40.        
  41.     except Exception as e:
  42.         return None, f"Error during classification: {str(e)}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement