I am working on reactjs with python api and openCV which after uploading photo returns result with green rectangle around the face. So working on it, on clicking upload photo it returns 422(unprocessable entity). I have three main part Upload.js for frontend uploading part, main.py image api and face_detector.py for opencv part.
Upload.js
import React, { useState } from 'react'
import './Upload.css'
import axios from 'axios';
const Upload = () => {
const [file, setFile] = useState();
const handleChange = (event) => {
setFile(URL.createObjectURL(event.target.files[0]))
}
const submitForm = () => {
const formData = new FormData();
formData.append('file', file);
axios
.post('http://127.0.0.1:8000/images', formData, {
headers: {
accept: 'multipart/form-data',
}
})
.then(() => {
alert('file upload succcess');
})
.catch(() => alert("File Upload Error"))
return formData
}
return (
<>
<input className='img_choose' type="file" onChange={handleChange} />
<img src={file} className='prev_img' alt='img' />
<button className='btn_upload' onClick={submitForm}>Upload</button>
</>
);
}
export default Upload
main.py
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import Response
from random import randint
from starlette.requests import Request
import uuid
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
db = []
origins = [
"http://localhost:3000",
"http://127.0.0.1:8000/"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/main")
def main():
return{"message":"Welcome"}
@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):
file.filename = f"{uuid.uuid4()}.jpg"
contents = await file.read() # <-- Important!
db.append(contents)
return {"filename": file.filename}
@app.get("/images/")
async def read_random_file():
# get a random file from the image db
random_index = randint(0, len(db) - 1)
response = Response(content=db[random_index])
return response
Face_detector.py
import cv2
import urllib.request
import numpy as np
url = [
"http://127.0.0.1:8000/images/"
]
def url_to_image(url):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# return the image
return image
for url in url:
trained_face_data = cv2.CascadeClassifier(
'haarcascade_frontalface_default.xml')
x = y = w = h = int
image = url_to_image(url)
face_coordinates = trained_face_data.detectMultiScale(image,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
for (x, y, w, h) in face_coordinates:
cv2.rectangle(image, (x, y), (x w, y h), (0, 255, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)
CodePudding user response:
This is where you are doing it wrong.
setFile(URL.createObjectURL(event.target.files[0]))
You are attaching the file URL in the formData instead of the file.
use this instead
setFile(event.target.files[0])