0

I have one webapp where user post image and then opencv calculate its details like width, height and show back. I got this from webapp but when I trying to get the same with API I can't figure out how should I do this here my code:

Serializers.py

from rest_framework import serializers  
from results.models import Result
import cv2


class ImageSerializer(serializers.ModelSerializer):
class Meta:
    model = Result
    fields = ('title','pub_date','medium','compound','detail','outputval','image','uploader')

models.py:

class Result(models.Model):
   title = models.CharField(max_length=200)
   pub_date = models.DateField()
   medium = models.CharField(max_length=200)
   compound = models.CharField(max_length=200)
   detail = models.TextField()
   outputval = models.TextField(default='rsult not calculated', null=True, blank=True)
  image = models.ImageField(upload_to='images/')
  uploader = models.ForeignKey(User, on_delete=models.CASCADE) # will be changed to not delete in update

views.py:

from rest_framework import viewsets
from .serializers import ImageSerializer
from results.models import Result


class ImageViewSet(viewsets.ModelViewSet):
  queryset = Result.objects.all()
  serializer_class = ImageSerializer

opencv function:

def opencv(self,img_path):
    image = cv2.imread(img_path)
    height = image.shape[0]
    width = image.shape[1]
    channels = image.shape[2]
    values = (" the height is %s , width is %s and number of channels is %s" % (height, width, channels)) 
    return values

what i want to do take image as user input and show the output in outputval fields.

1 Answer 1

1

serializer.py

from results.models import Result
import cv2


class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Result
        fields = '__all__'

    def create(self, validated_data):
        instance = super().create(validated_data)
        instance.outputval = opencv(instance.image.path)
        instance.save()
        return instance

Something like this i think. In this way when the create function on ModelViewSet return the serializer's data you have the outputval filled.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.