Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def classify_single_image(model, image_path):
- try:
- # Read and preprocess the image
- image = cv2.imread(image_path)
- if image is None:
- return None, "Could not load image"
- # Make a copy for display
- display_image = copy.deepcopy(image)
- # Preprocess the image
- image = cv2.resize(image, (CONST.IMG_SIZE, CONST.IMG_SIZE))
- image = image.astype('float32') / 255.0 # Normalize to [0,1] range
- image = np.expand_dims(image, axis=0) # Add batch dimension
- # Make prediction
- pred = model.predict(image, verbose=0)
- class_idx = np.argmax(pred, axis=1)[0]
- confidence = float(pred[0][class_idx])
- # Map prediction to class name
- class_names = {0: 'Cat', 1: 'Dog'}
- prediction = class_names[class_idx]
- # Add text to image
- font = cv2.FONT_HERSHEY_SIMPLEX
- location = (20, 30)
- fontScale = 0.8
- fontColor = (0, 255, 0) # Green
- lineType = 2
- text = f"{prediction}: {confidence:.2%}"
- cv2.putText(display_image, text, location, font, fontScale, fontColor, lineType)
- # Save the annotated image
- output_path = "prediction_result.jpg"
- cv2.imwrite(output_path, display_image)
- return prediction, confidence, output_path
- except Exception as e:
- return None, f"Error during classification: {str(e)}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement