Image Recognition with Deep Learning Frameworks
Image recognition is at the heart of many real-world AI applications—from facial recognition to autonomous vehicles. In this post, we'll walk through building an image recognition system using Python-based deep learning frameworks like TensorFlow and PyTorch. We'll also touch on integrating it with a Java backend using REST APIs.
🚀 Tools & Frameworks
- TensorFlow / PyTorch – for deep learning model development
- Flask – for serving the model as an API
- Java (Spring Boot) – to consume the image recognition service
🧰 Step 1: Training or Using a Pretrained Model
We'll use a pretrained model like ResNet50 from TensorFlow or PyTorch's torchvision.
🧠 Using ResNet50 with TensorFlow
import tensorflow as tf
from tensorflow.keras.applications import resnet50
from tensorflow.keras.preprocessing import image
import numpy as np
model = resnet50.ResNet50(weights='imagenet')
def predict_image(img_path):
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = resnet50.preprocess_input(x)
preds = model.predict(x)
return resnet50.decode_predictions(preds, top=3)[0]
🌐 Step 2: Serving the Model via Flask
Wrap the model into a REST API using Flask:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
file = request.files['file']
file.save("input.jpg")
preds = predict_image("input.jpg")
return jsonify(preds)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
☕ Step 3: Consuming API from Java (Spring Boot)
Send an image file to the Flask service from your Spring Boot app:
@RestController
public class ImageController {
@PostMapping("/analyze")
public String analyzeImage() throws IOException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource("src/main/resources/image.jpg"));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:5000/predict", requestEntity, String.class);
return response.getBody();
}
}
📷 Try It Out
- Download any sample image (e.g., cat, car, etc.)
- Start the Flask server:
python app.py - Run your Spring Boot app
- Call the endpoint:
POST /analyze
💡 Optional: PyTorch Alternative
Here's how you can use PyTorch for the same task:
from torchvision import models, transforms
from PIL import Image
import torch
model = models.resnet50(pretrained=True)
model.eval()
def predict(img_path):
img = Image.open(img_path)
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
])
img_tensor = transform(img).unsqueeze(0)
output = model(img_tensor)
probs = torch.nn.functional.softmax(output[0], dim=0)
return probs.topk(3)
📌 Use Cases
- Retail: Product image recognition
- Security: Surveillance & facial recognition
- Healthcare: Medical image diagnosis
- Automotive: Road sign & obstacle detection
🎯 Conclusion
We’ve successfully built an image recognition pipeline using deep learning frameworks and integrated it into a Java-based system via REST APIs. This hybrid approach lets you use Python’s ML ecosystem and Java’s backend power together.
Next steps? Try adding custom models or real-time streaming input!
Comments
Post a Comment