optimise tis "# FastAPI endpoint for processing images @app.post('/processimage',…
- User
optimise tis "# FastAPI endpoint for processing images @app.post('/process_image', response_class=HTMLResponse, status_code=200) async def process_image(request: Request, file: UploadFile = File(...)): try: image_contents = await file.read() image = Image.open(io.BytesIO(image_contents)) image_array = np.array(image) visualised_origine, instances = await run_prediction('model_final_lines', image_array)
coderesults = [] async def process_contour(contour_idx, contour, i): x, y, w, h = cv2.boundingRect(contour) area = w * h # Add a condition based on width and height if w < 1500 and h < 80: return mask = np.zeros_like(image_array, dtype=np.uint8) cv2.drawContours(mask, [contour], contourIdx=-1, color=(255,) * mask.shape[2], thickness=cv2.FILLED) masked_image = cv2.bitwise_and(image_array, mask) cropped_image = masked_image[y:y + h, x:x + w] # Run prediction for the letter asynchronously letter_prediction, _ = await run_prediction('model_letter', cropped_image) # Encode the letter prediction prediction_letters = encode_image_to_base64(letter_prediction) # Encode the cropped image encoded_image_64 = encode_image_to_base64(cropped_image) # add the test character : test = classify_character(cropped_image, model5) # add loop to crop the character results.append({'original': encoded_image_64, 'letter_prediction': prediction_letters, 'contour_idx': contour_idx, 'instance_idx': i, 'area': area, 'test': test}) for i, instance_idx in enumerate(range(len(instances))): if instances.pred_classes[instance_idx] != 0: continue polygon = instances.pred_masks[instance_idx].cpu().numpy().astype(np.uint8) contours, _ = cv2.findContours(polygon, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: continue print(f"Processing Contours for Instance {i}") await asyncio.gather(*[process_contour(contour_idx, contour, i) for contour_idx, contour in enumerate(contours)]) print("Image Processing Completed") return templates.TemplateResponse( "result_template.html", { "request": request, "code": 200, "encoded_image": encode_image_to_base64(image_array), "encoded_predicted": encode_image_to_base64(visualised_origine), "message": "Success", "results": results } ) except Exception as e: logging.error(f"Error processing image: {e}") return templates.TemplateResponse( "result_template.html", { "request": request, "code": 500, "message": f"Error: {e}", } ) # a more meaningful response can be used - Assistant
- User
add async " for i, instance_idx in enumerate(instances):
- Assistant