Лучший метод распознавания лиц Django с помощью захвата камеры клиента

Добрый день, подскажите, как лучше всего захватывать кадры с камеры пользователя, чтобы использовать функцию распознавания лиц, которая есть у меня в Django views.

Сейчас я пытаюсь открыть камеру для пользователя в Интернете и оттуда удалить рамки, но это не работает правильно, так как выдает ошибку "TypeError: Object of type bytes is not JSON serializable", а также я хотел, чтобы у пользователя была рамка вокруг лица, говорящая о том, что изображение снимается.

Я отправлю ниже то, что у меня есть в представлениях и в моем js

Я ценю любую помощь или предложенное мнение

@csrf_exempt
def process_frame_faceRecognition(request):
    print("Processando frame...")
    if request.method == 'POST':
        frame_data = request.POST.get('frame_data')
        print(frame_data)
        frame_data = frame_data.split(',')[1]  # Remover o prefixo 'data:image/png;base64,'
        frame_data_decoded = base64.b64decode(frame_data)
        frame_data = np.frombuffer(frame_data_decoded, dtype=np.uint8)
        frame = cv2.imdecode(frame_data, flags=1)
        
        # Agora você pode passar o frame para a função compare_faces()
        face_recognition = FaceRecognition()
        result = face_recognition.run_recognition(frame)

        # Verifique o tipo de resultado antes de retorná-lo
        if isinstance(result, HttpResponseRedirect):
            return JsonResponse({'message': 'redirecionamento', 'url': result.url})
        else:
            # Coleta os valores do generator em uma lista
            result_list = list(result)
            # Codifica a imagem como base64
            _, buffer = cv2.imencode('.png', frame)
            frame_base64 = base64.b64encode(buffer).decode('utf-8')
            print("hello world 2")
            return JsonResponse({'message': result_list, 'image': frame_base64})
    else:
        return JsonResponse({'message': 'Método não permitido'}, status=405)

HTMLJS

// Função para iniciar a câmera quando a página é carregada
window.onload = function() {
    startCamera();
};

// Função para iniciar a câmera
function startCamera() {
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');

    // Acessa a webcam do usuário
    navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
            video.srcObject = stream;
            video.play();
        })
        .catch(error => {
            console.error('Error accessing webcam:', error);
        });

    // Função para capturar e processar o quadro da câmera
    function captureFrame() {
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const imageData = canvas.toDataURL('image/jpeg'); // Obtém os dados do frame como uma imagem codificada em base64
        sendFrameToServer(imageData);
    }

    // Envia o frame capturado para o servidor
    function sendFrameToServer(frameData) {
        fetch('/process_frame_faceRecognition/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': getCookie('csrftoken') // Adicione o token CSRF
            },
            body: 'frame_data=' + encodeURIComponent(frameData) // Envia os dados do frame como POST data
        })
        .then(data => {
            if (data.message === 'redirecionamento') {
                window.location.href = data.url;
            }
        })
        .catch(error => {
            console.error('Error sending frame to server:', error);
        });
    }

    function processResponse(response) {
    // Verifica se a resposta possui a chave 'image'
        if ('image' in response) {
            // Obtém a imagem codificada em base64 da resposta
            var imageData = response.image;
            // Cria um elemento de imagem
            var img = document.createElement('img');
            // Define o atributo 'src' com os dados da imagem codificada
            img.src = 'data:image/png;base64,' + imageData;
            // Adiciona a imagem ao corpo do documento (ou a qualquer outro elemento desejado)
            document.body.appendChild(img);
        }
    }
Вернуться на верх