How do you create a model using opencv in django?

Viewed 115

Anybody know who to integrate django and opencv(cv2) together. My goal is to create an model that can store the user and a picture of them. I first tried just using UserPicture.objects.create(user=request.user, picture=image) but that wouldn't work because the function was not taking request as a parameter. Should I create an APIView somehow? Anyways, here is the code I am using for the opencv class:

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0, cv2.CAP_DSHOW)

    def __del__(self):
        self.video.release()
    
    def create_facial_boundary(self, image, cascadeClassifier, color, emotion):
        grayScaled = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
        face = cascadeClassifier.detectMultiScale(grayScaled, 1.1, 10)
        coords = []
        for (x, y, w, h) in face:
            cv2.rectangle(image, (x, y), (x + w, y + h), color)
            roi_gray = grayScaled[y : y+h, x: x+w]
            cv2.putText(image, emotion, (x, y-4), cv2.FONT_HERSHEY_PLAIN, 2, (255, 255, 255))
            coords = [x, y, w, h]
        self.update_time()
        return coords, image

    def detect_face(self, image, cascadeClassifier):
      color = {"green" : (0, 145, 25)}
      coords, image = self.create_facial_boundary(image, cascadeClassifier, color["green"], "ExText")
      image = cv2.flip(image, 1)
      return image

    def update_time(self):
        time.sleep(5)

    def get_user_face(self):
        success, frame  = self.video.read()
        # img_file = "User-Face.jpg"
        frame = self.detect_face(frame, cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'))
        new_frame = cv2.flip(frame, 1)
        _, image = cv2.imencode(".jpg", new_frame)
        return image
    
    def get_user_emotion():
        pass

    def get_frame(self):
        success, frame = self.video.read()
        image_flip = cv2.flip(frame, 1)
        ret, jpeg = cv2.imencode('.jpg', image_flip)
        return jpeg.tobytes()
    
    

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

def get_image(camera):
    image = camera.get_user_face()
    return image

        
def video_feed(request):
    while True:
        return StreamingHttpResponse(gen(VideoCamera()),
                    content_type='multipart/x-mixed-replace; boundary=frame')
1 Answers

First, the way you are opening the image is not recommended, use from PIL import Image to open it (ithis is the recommended way when using opencv and requests together).
Second, check if you are really receiving the image in your request.

Related