I have been trying to convert my PNG image (299,299) to RGB (299,299,3) for a long time, I tried a lot of suggested methods but I haven't been successful. I'm sending an image from postman to my pycharm fastapi my images are GREYSCALE PNG x-ray images
code:
from fastapi import FastAPI, File, UploadFile
import uvicorn
import numpy as np
from io import BytesIO
from PIL import Image
import tensorflow as tf
import matplotlib.pyplot as plt
import cv2
app = FastAPI()
MODEL = tf.keras.models.load_model("../saved_models/1")
CLASS_NAMES = ["COVID", "Lung_Opacity", "Normal", "Viral Pneumonia"]
@app.get("/ping")
async def ping():
return "Hello, I am alive"
def read_file_as_image(data) -> np.ndarray:
image = np.array(Image.open(BytesIO(data)))
return image
@app.post("/predict")
async def predict(
file: UploadFile = File(...)
):
image = read_file_as_image(await file.read())
image = image.reshape(299,299,3)
image = Image.fromarray(image)
image = image.convert('RGB')
img_batch = np.expand_dims(image, 0)
predictions = MODEL.predict(img_batch)
pass
if __name__ == "__main__":
uvicorn.run(app, host='localhost', port=8000)
I'm doing this for the first time and I don't know what I'm doing wrong, please help. the error i'm getting is
cannot reshape array of size 89401 into shape (299,299,3)
CodePudding user response:
In order to get 3 channels np.dstack
:
image = np.dstack([image.reshape(299,299)]*3)
Or if you want only one channel
image.reshape(299,299)