如何在Angular前端向Django视图传递图片实现图像分割
segmentImage() in Angular to Send Image Data to Your Django Backend Let's break this down step by step—you've already got the core upload/display functionality working, so we just need to wire up the segment button to your Django view and handle the response.
First: Fix Up Your Django View (views.py)
Your existing view has a few gaps (like an undefined form) and is set up to render a template, which isn't ideal for an API call from Angular. Let's adjust it to return JSON instead, since we just need the segmentation coordinates back:
from django.shortcuts import render from django import forms from django.http import JsonResponse # Import your image model here if you need to fetch stored images # from your_app.models import UploadedImage # Define a simple form to validate incoming data class SegmentForm(forms.Form): info_name = forms.CharField() # We'll send the image's PK here def segment_image(request): if request.method == 'POST': form = SegmentForm(request.POST) if form.is_valid(): image_pk = form.cleaned_data['info_name'] # Fetch your image object using the PK (adjust model name as needed) # image_obj = UploadedImage.objects.get(pk=image_pk) # Pass the image path to your processing function # x, y, w, h = script_function(image_obj.image.path) # For testing, return sample coordinates (replace with your actual script output) x, y, w, h = script_function(image_pk) return JsonResponse({'x': x, 'y': y, 'w': w, 'h': h}) # Return error if form is invalid return JsonResponse({'error': 'Invalid request data'}, status=400) # Handle GET requests (if needed) return JsonResponse({'error': 'Use POST method'}, status=405) def script_function(info): # Your image segmentation logic goes here # Example: if info is the image PK, fetch the image file and process it return 50, 50, 200, 200 # Sample return values
Don't forget to add a URL route for this view in your Django urls.py:
path('segment/', views.segment_image, name='segment_image'),
Second: Add the segmentImage() Function to Your Angular Controller (app.js)
We'll use Angular's $http service to send a POST request to your Django endpoint, passing the image's PK (since the image is already stored on your server—no need to re-upload it). Update your MainCtrl like this:
myApp.controller('MainCtrl', function($scope, Images, $http) { console.log('In main Control'); $scope.images = Images.query(); $scope.newImage = {}; // ... your existing uploadImage() and deleteImage() functions ... $scope.segmentImage = function(image) { // Send the image's PK to the backend const postData = { info_name: image.pk }; $http.post('/segment/', postData) .then(function(response) { // Success: capture the segmentation coordinates const segmentationData = response.data; console.log('Segmentation result:', segmentationData); // Store the data on the image object to use in the template image.segmentation = segmentationData; }) .catch(function(error) { console.error('Segmentation failed:', error); alert('Oops, failed to process the image. Please try again.'); }); }; });
Optional: Display the Segmentation Box on the Image
To visualize the result, add a red bounding box over your image in index.html using the returned coordinates:
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-4" ng-repeat="image in images track by image.pk"> <h3> Image {{ image.pk }} <button class="btn btn-warning" ng-click="deleteImage(image)">Delete</button> <button class="btn btn-primary" ng-click="segmentImage(image)">Segment</button> </h3> <!-- Container to position the image and segmentation box --> <div style="position: relative; display: inline-block;"> <a href="{{ image.image }}"> <img class="img-responsive" ng-src="{{ image.image }}"> </a> <!-- Red box that only shows when segmentation data exists --> <div ng-if="image.segmentation" style="position: absolute; left: {{ image.segmentation.x }}px; top: {{ image.segmentation.y }}px; width: {{ image.segmentation.w }}px; height: {{ image.segmentation.h }}px; border: 2px solid #dc3545; pointer-events: none;"> </div> </div> </div>
Key Notes
- CSRF Protection: Angular automatically handles Django's CSRF token as long as you have the CSRF cookie set (which Django does by default for authenticated users). If you're having issues, make sure your base template includes
{% csrf_token %}somewhere. - Image Processing: In your
script_function, replace the sample return values with your actual segmentation logic. If you need the image file path, use the PK to fetch the image object from your database and accessimage_obj.image.path. - Error Handling: The example includes basic error handling, but you can expand it to show user-friendly messages or retry logic as needed.
内容的提问来源于stack exchange,提问作者roadrunner009

