def detect_sign(contents):
    """To convert image string into PIL form and perform detection operation"""
    strng=contents
    if find_img_type(strng)=='jpeg':
        type1=strng[23:]#jpeg
        str2img =Image.open(io.BytesIO(base64.b64decode(type1)))
        imx=np.array(str2img)
    #     print(imx.shape)
        img = skimage.transform.resize(imx, (32, 32), mode='constant')
        img1 = np.reshape(img,[1,32,32,3])
        with graph.as_default():
            classes = model.predict_classes(img1)

        for i in dict1.keys():
            if i == str(classes):
                name = dict1[i]
                print("Image :",name)
        return name

    elif find_img_type(strng)=='png':
        type2=strng[22:]#png
        str2img =Image.open(io.BytesIO(base64.b64decode(type2)))
        imx=np.array(str2img)
        print(imx.shape)
        Im4=imx[:,:,:-1]
        img = skimage.transform.resize(Im4, (32, 32), mode='constant')
        img1 = np.reshape(img,[1,32,32,3])
        with graph.as_default():
            classes = model.predict_classes(img1)

        for i in dict1.keys():
            if i == str(classes):
                name = dict1[i]
                print("Image :",name)
        return name

    elif find_img_type(strng)=='octet-stream':
        type3=strng[37:] #ppm
        str2img =Image.open(io.BytesIO(base64.b64decode(type3)))
        imx=np.array(str2img)
        print(imx.shape)
        img = skimage.transform.resize(imx, (32, 32), mode='constant')
        img1 = np.reshape(img,[1,32,32,3])
        with graph.as_default():
            classes = model.predict_classes(img1)

        for i in dict1.keys():
            if i == str(classes):
                name = dict1[i]
                print("Image :",name)
        return name

    else:
        msg="File format not supported.Please upload image with .jpeg/.png/.ppm format only"
        return msg
def segmentation(string, content, NDVIcontent):
    global ROIRGB, ROINDVI
    if string:
        data = content.encode("utf8").split(b";base64,")[1]
        NDVIdata = NDVIcontent.encode("utf8").split(b";base64,")[1]
        img = io.BytesIO()
        imgNDVI = io.BytesIO()
        img.write(base64.b64decode(data))
        imgNDVI.write(base64.b64decode(NDVIdata))
        img.seek(0)
        imgNDVI.seek(0)
        i = np.asarray(bytearray(img.read()), dtype=np.uint8)
        i = cv2.imdecode(i, cv2.IMREAD_COLOR)
        iNDVI = np.asarray(bytearray(imgNDVI.read()), dtype=np.uint8)
        iNDVI = cv2.imdecode(iNDVI, cv2.IMREAD_COLOR)
        mask = parse_jsonstring(string, (i.shape[0],i.shape[1]))
        ret,thresh = cv2.threshold(np.array(mask, dtype=np.uint8), 0, 255, cv2.THRESH_BINARY)
        im_floodfill = thresh.copy()
        h, w = thresh.shape[:2]
        m = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(im_floodfill, m, (0,0), 255)
        im_floodfill_inv = cv2.bitwise_not(im_floodfill)
        im_out = thresh | im_floodfill_inv
        RGBimg = cv2.bitwise_and(i, i, mask=im_out)
        RGBimg = cv2.cvtColor(RGBimg, cv2.COLOR_BGR2RGB)
        target_size = (RGBimg.shape[1],(RGBimg.shape[0]))
        iNDVI = cv2.resize(iNDVI, target_size)
        NDVIimg = cv2.bitwise_and(iNDVI, iNDVI, mask=im_out)
        NDVIimg = cv2.cvtColor(NDVIimg, cv2.COLOR_BGR2RGB)

        contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
        cnts = sorted(contours, key=lambda c: cv2.contourArea(c), reverse=True)  # finds the largest selection, which is a limitation to multiple selection (will be changed in the future versions)
        (x,y,w,h) = cv2.boundingRect(cnts[0])
        ROIRGB = RGBimg[y:y+h, x:x+w]
        ROINDVI = NDVIimg[y:y+h, x:x+w]
        cv2.imwrite(static_image_route+'RGB_cropped.png', cv2.cvtColor(ROIRGB, cv2.COLOR_RGB2BGR ))
        cv2.imwrite(static_image_route+'CIR_cropped.png', cv2.cvtColor(ROINDVI, cv2.COLOR_RGB2BGR ))
        with ZipFile(static_image_route+'cropped.zip', 'w') as zipObj2:
            zipObj2.write(static_image_route+'RGB_cropped.png')
            zipObj2.write(static_image_route+'CIR_cropped.png')
            location = os.path.join(static_image_route,'cropped.zip')

    else:
        raise PreventUpdate
    return array_to_data_url(img_as_ubyte(ROIRGB)), array_to_data_url(img_as_ubyte(ROINDVI)), html.A(html.Button('Download',style={'display':'block'
                                    ,'position':'relative',
                                    'top': '45%','left': '45%',
                                    'font-size': '16px',
                                    'padding': '8px 12px',
                                    'border-radius': '4px',
                                    'text-align': 'center',
                                    'align':'center',
                                    'color':'black',
                                    'font-family':'Times New Roman',
                                    'textAlign':'center'}), href=location) #, html.Div([html.Button('Save Image', id='saveImg')])
def classify_image(file):
    rand = random.Random()
    
    with anvil.media.TempFile(file) as filename:
      img = Image.open(io.BytesIO(file.get_bytes()))
      bs = io.BytesIO()
      #img.save(bs, format="JPEG")
      # save image in upload 
      img.save('/content/cell_images/upload/myphoto.png', 'PNG')
      final_path = '/content/cell_images/upload/myphoto.png'
      prediction = "Sick" if getPrediction(CNN, final_path) == 0 else "Healthy"
      # save image for backup      
      lol = str(randint(1,1000000))
      backup_path = "/content/cell_images/backup/"+lol+".png"
      img.save(backup_path, 'JPEG')
      return(prediction)
def get_imgs():
    ann_id = np.random.choice(ids)
    img_id = coco.anns[ann_id]['image_id']
    img = coco.loadImgs(img_id)[0]
    print(img)
    url = img['coco_url']
    #flickrurl=img['flickr_url']
    #print(url)
    #print(flickrurl)
    orig_img = skimage.io.imread(url)
    plt.axis('off')
    plt.imshow(orig_img)
    plt.show()
    #print(orig_img.shape)

    response = requests.get(url)
    img_pil = Image.open(io.BytesIO(response.content)).convert('RGB')

    transform_test = transforms.Compose([
        transforms.Resize(256),  # smaller edge of image resized to 256
        transforms.RandomCrop(224),  # get 224x224 crop from random location
        transforms.RandomHorizontalFlip(
        ),  # horizontally flip image with probability=0.5
        transforms.ToTensor()
    ])

    I_transf = transform_test(img_pil)
    return orig_img, I_transf.view(1, 3, 224, 224), img
Exemple #5
0
def get_sat(coord):

    newpath = r'img/{}_{}'.format(*coord)
    if os.path.exists(newpath):
        shutil.rmtree(newpath, ignore_errors=True)
    os.makedirs(newpath)
        
    new_url = base_URL + "&center=" + quote("{}, {}".format(*coord))
    new_satellite_url = satellite_URL + "&center=" + quote("{}, {}".format(*coord))

    with urllib.request.urlopen(new_url) as url:
        f = io.BytesIO(url.read())
    img = exposure.rescale_intensity(np.array(Image.open(f)))
    skimage.io.imsave(newpath + "/mask.png",img)

    img_satellite = skimage.io.imread(new_satellite_url)
    skimage.io.imsave(newpath + "/sat.png",img_satellite)

    cmd = r'matlab -nosplash -nodesktop -r "road_segmentation {}; quit"'.format(newpath)
    os.system(cmd)

    p = Path(newpath)
    for sec_img in p.glob('*/*/*.png'):
        if sec_img.parts[-1] in ['sat.png']:
            shutil.copy(os.getcwd() + '/' + '/'.join(sec_img.parts), '{}'.format(':'.join(sec_img.parts)))
Exemple #6
0
    def infer_from_img_url(self, img_url):
        tik = time.time()
        response = requests.get(img_url, timeout=20)
        if response.status_code in [403, 404, 500]:
            return {
                'status': 2,
                'message': 'Invalid URL',
                'elapse': time.time() - tik,
                'results': None
            }

        else:
            img_content = response.content

            import io
            from PIL import Image
            img_np = np.array(Image.open(io.BytesIO(img_content)))
            img = Image.fromarray(img_np.astype(np.uint8))

            preprocess = transforms.Compose([
                transforms.Resize(227),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                transforms.Normalize([0.485, 0.456, 0.406],
                                     [0.229, 0.224, 0.225])
            ])

            img = preprocess(img)
            img.unsqueeze_(0)

            img = img.to(self.device)

            outputs = self.model.forward(img)
            outputs = F.softmax(outputs, dim=1)

            # get TOP-K output labels and corresponding probabilities
            topK_prob, topK_label = torch.topk(outputs, self.topK)
            prob = topK_prob.to("cpu").detach().numpy().tolist()

            _, predicted = torch.max(outputs.data, 1)

            tok = time.time()

            return {
                'status':
                0,
                'message':
                'success',
                'elapse':
                tok - tik,
                'results': [{
                    'name':
                    self.key_type[int(topK_label[0][i].to("cpu"))],
                    'category id':
                    int(topK_label[0][i].data.to("cpu").numpy()) + 1,
                    'prob':
                    round(prob[0][i], 4)
                } for i in range(self.topK)]
            }
Exemple #7
0
def predict_food():
    response = {}
    image = flask.request.files["image"].read()
    image = Image.open(io.BytesIO(image))
    prediction, prob = predict(image)
    response['prediction'] = prediction
    response['probability'] = prob
    return flask.jsonify(response)
def send_file(filename,mime_type=None):
    try:
        content = array_to_data_url(img_as_ubyte(ROIRGB))
        data = content.encode("utf8").split(b";base64,")[1]
        imgtowrite = io.BytesIO(base64.decodebytes(data))
        c = base64.b64encode(imgtowrite.read()).decode()
        return dict(content=c, filename=filename,mime_type=mime_type, base64=True)
    except Exception: pass
Exemple #9
0
def load_image_rwanda_zip(name):
    archive = zipfile.ZipFile("rwanda.zip", 'r')
    img_data = archive.read("rwanda/" + name)
    bytes_io = io.BytesIO(img_data)
    img = pygame.image.load(bytes_io)
    img = pygame.surfarray.array3d(img)
    archive.close()
    return img
Exemple #10
0
def get_image(location, heading, pitch, fov):
    image = download_image(location, heading, pitch, fov)
    
    # Return image data
    imagedata = io.BytesIO()
    skimage.io.imsave(imagedata, image, plugin='pil', format_str='jpeg')
    imagedata.seek(0)
    
    return imagedata
def detect_graph_types_from_iiif(paper_id, pages, learner, debug=False):
    """Pull images from iiif server
    """

    print(paper_id, pages)

    url = "http://127.0.0.1:8182/iiif/2/biorxiv:{}.full.pdf/full/560,560/0/default.png?page={}"
    images = [open_image(io.BytesIO(requests.get(url.format(paper_id, pg)).content)) for pg in range(1, pages+1)]
    
    return detect_graph_types_from_list(images, learner)
Exemple #12
0
    def preprocess(self, raw, gt_path):
        img_bytes = io.BytesIO(bytearray(raw))
        gt_bytes = open(gt_path, 'rb')

        img = np.array(Image.open(img_bytes))
        gt = np.array(Image.open(gt_bytes))
        img = img[:, :, :3] / 255.
        gt = gt[:, :, :3] / 255.

        return img, gt
Exemple #13
0
def draw_ferwar_id_on_axis(ID, ax):
    import bb_utils.visualization
    import skimage.io
    import io
    
    ID = bb_utils.ids.BeesbookID.from_ferwar(ID)
    png = bb_utils.visualization.TagArtist().draw(ID.as_bb_binary())
    png = io.BytesIO(png)
    im = skimage.io.imread(png)
    ax.imshow(im)
    ax.set_axis_off()
Exemple #14
0
async def sort_endpoint():
    image = skimage.io.imread(io.BytesIO(await request.body))
    image = await image_function(image, sort)

    assert isinstance(image, io.BytesIO)

    response = await make_response(image.getvalue())
    response.headers['Status'] = 200
    response.headers['Content-Type'] = "image/png"

    return response
Exemple #15
0
def predict_food():
    response = {"success": False}
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))
            prediction, prob = predict(image)
            response['prediction'] = prediction
            response['probability'] = prob
            response['emissions'] = new_dict[prediction]
            response["success"] = True
    return flask.jsonify(response)
Exemple #16
0
def gen_plot(fpr, tpr):
    """Create a pyplot plot and save to buffer."""
    plt.figure()
    plt.xlabel("FPR", fontsize=14)
    plt.ylabel("TPR", fontsize=14)
    plt.title("ROC Curve", fontsize=14)
    plot = plt.plot(fpr, tpr, linewidth=2)
    buf = io.BytesIO()
    plt.savefig(buf, format="jpeg")
    buf.seek(0)
    plt.close()
    return buf
def to_base64(image) -> str:

    # convert image to bytes
    with io.BytesIO() as output_bytes:
        PIL_image = Image.fromarray(skimage.img_as_ubyte(image))
        # Note JPG is not a vaild type here
        if PIL_image.mode in ("RGBA", "P"):
            PIL_image = PIL_image.convert("RGB")
        PIL_image.save(output_bytes, 'JPEG')
        bytes_data = output_bytes.getvalue()

    # encode bytes to base64 string
    base64_str = str(base64.b64encode(bytes_data), 'utf-8')
    return base64_str
Exemple #18
0
    def infer_from_img(self, img):
        import io
        from PIL import Image
        img_np = np.array(Image.open(io.BytesIO(img)))
        img = Image.fromarray(img_np.astype(np.uint8))

        preprocess = transforms.Compose([
            transforms.Resize(224),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])

        img = preprocess(img)
        img.unsqueeze_(0)

        img = img.to(self.device)

        outputs = self.model(img)
        outputs = F.softmax(outputs, dim=1)

        topK_prob, topK_label = torch.topk(outputs, self.topK)
        prob = topK_prob.to("cpu").detach().numpy().tolist()

        _, predicted = torch.max(outputs.data, 1)

        if prob[0][0] >= cfg['thresholds']['skin_disease_recognition']:
            return {
                "status":
                0,
                "message":
                "success",
                "results": [{
                    "disease":
                    self.mapping[int(topK_label[0][i].to("cpu"))],
                    "probability":
                    round(prob[0][i], 4),
                } for i in range(self.topK)]
            }
        else:
            return {
                "status":
                0,
                "message":
                "success",
                "results": [{
                    "disease": "Unknown",
                    "probability": round(prob[0][0], 4),
                }]
            }
Exemple #19
0
    def createVectorsFile(self):
        self.dataset.loadImages()

        # Create the BlockBlockService that is used to call the Blob service for the storage account
        azureBlobStorage = BlockBlobService(
            account_name=self.parameters['azureStorageBucket'],
            account_key=self.parameters['azureStorageKey'],
            endpoint_suffix=self.parameters['azureEndpointSuffix'])

        fieldNames = ["imageId", "url"]
        for v in range(self.parameters['neuralNetwork']['vectorSize']):
            fieldNames.append(f'v{v}')

        with open('db-vectors.csv', 'wt') as f:
            writer = csv.DictWriter(f, fieldnames=list(fieldNames))
            writer.writeheader()

            for imageId in range(len(LoadedDataset.rawImages)):
                rawImage = LoadedDataset.rawImages[imageId]

                buffer = io.BytesIO()
                skimage.io.imsave(buffer, rawImage)

                result = azureBlobStorage.create_blob_from_bytes(
                    'images', f"image-{imageId}.png", buffer.getvalue())

                images = self.dataset.getImageDBSet(imageId)

                # for index, image in enumerate(images):
                #     skimage.io.imsave(f"image{imageId}-{index}.png", image)

                vectors = self.model.model.predict(numpy.array(images))
                vectors = sklearn.preprocessing.normalize(vectors)

                for vector in vectors:
                    data = {
                        "imageId":
                        imageId,
                        "url":
                        f"{self.parameters['azureStorageUrl']}image-{imageId}.png"
                    }

                    for index, value in enumerate(vector):
                        data[f'v{index}'] = value

                    writer.writerow(data)

                if imageId % 100 == 0:
                    print(
                        f"Completed {imageId}/{len(LoadedDataset.rawImages)}")
def predict():
    # Initialize the data dictionary that will be returned from the view.
    data = {"success": False}

    # Ensure an image was properly uploaded to our endpoint.
    if flask.request.method == 'POST':
        print("接收到post请求")
        if flask.request.files.get("image"):
            print("接收到字节流")
            # Read the image in PIL format
            image = flask.request.files["image"].read()
            import io
            image = Image.open(io.BytesIO(image))#从字节流还原图片
            #print(image.size)
            image=numpy.array(image)
            print("正在转换图片")
            image = transform.resize(image,(256,256),mode='constant')#这里需要resize成你的模型需要的输入大小
            image[:,:,0] = (image[:,:,0]-0.485)/0.229
            image[:,:,1] = (image[:,:,1]-0.456)/0.224
            image[:,:,2] = (image[:,:,2]-0.406)/0.225
            #例如([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])就是Imagenet dataset的标准化系数(RGB三个通道对应三组系数)。数据集给出的均值和标准差系数,每个数据集都不同的,都是数据集提供方给出的
            image=image.transpose([2,0,1])#调换通道的顺序
            image = image[np.newaxis,:]#扩维
            #在这之前,整理一下你的输入数据,确保符合模型,变成 [1,w,h,c] 图片个数、宽、高、通道数
            image=torch.from_numpy(image).float()
            if torch.cuda.is_available():
                image = Variable(image.cuda())
            else:
                image = Variable(image)
            print("开始输入模型预测")
            d1,d2,d3,d4,d5,d6,d7,d8 = model(image)#根据你的模型输出结果,改成你自己的,如果你只返回图片,就用一个变量接受就好了
            
            
            #----------------------------------
            # normalization  这一段是对模型输出做后处理,如果不需要可以直接注释掉
            pred = d1[:,0,:,:]
            pred = normPRED(pred)
            #----------------------------------
            
            #--------接下来的两步是必须的
            pred = pred.squeeze()
            pred_np = pred.cpu().data.numpy()

            data['result']=pred_np.tolist()
            # Indicate that the request was a success.
            data["success"] = True
            del d2,d3,d4,d5,d6,d7,d8  #删除没用的变量,防止内存泄漏,这一步可有可无
            print("返回结果")
    # Return the data dictionary as a JSON response.
    return flask.jsonify(data)
Exemple #21
0
async def colormap_endpoint():
    color_arg = f'#{((request.args.get("color") or "7289DA").replace("0x", "#").lstrip("#")):0>6}'
    color_obj = Color(color_arg)
    rgb = color_obj.red_int8, color_obj.green_int8, color_obj.blue_int8
    image = PILImage.open(io.BytesIO(await request.body))
    transformed = await image_function(image, colormap, rgb)

    assert isinstance(transformed, io.BytesIO)

    response = await make_response(transformed.getvalue())
    response.headers['Status'] = 200
    response.headers['Content-Type'] = "image/png"

    return response
def segmentation(string, content, NDVIcontent):
    if string:
        data = content.encode("utf8").split(b";base64,")[1]
        NDVIdata = NDVIcontent.encode("utf8").split(b";base64,")[1]
        img = io.BytesIO()
        imgNDVI = io.BytesIO()
        img.write(base64.b64decode(data))
        imgNDVI.write(base64.b64decode(NDVIdata))
        img.seek(0)
        imgNDVI.seek(0)
        i = np.asarray(bytearray(img.read()), dtype=np.uint8)
        i = cv2.imdecode(i, cv2.IMREAD_COLOR)
        iNDVI = np.asarray(bytearray(imgNDVI.read()), dtype=np.uint8)
        iNDVI = cv2.imdecode(iNDVI, cv2.IMREAD_COLOR)
        mask = parse_jsonstring(string, (i.shape[0],i.shape[1]))
        ret,thresh = cv2.threshold(np.array(mask, dtype=np.uint8), 0, 255, cv2.THRESH_BINARY)
        im_floodfill = thresh.copy()
        h, w = thresh.shape[:2]
        m = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(im_floodfill, m, (0,0), 255)
        im_floodfill_inv = cv2.bitwise_not(im_floodfill)
        im_out = thresh | im_floodfill_inv
        RGBimg = cv2.bitwise_and(i, i, mask=im_out)
        RGBimg = cv2.cvtColor(RGBimg, cv2.COLOR_BGR2RGB)
        target_size = (RGBimg.shape[1],(RGBimg.shape[0]))
        iNDVI = cv2.resize(iNDVI, target_size)
        NDVIimg = cv2.bitwise_and(iNDVI, iNDVI, mask=im_out)
        NDVIimg = cv2.cvtColor(NDVIimg, cv2.COLOR_BGR2RGB)

        contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
        cnts = sorted(contours, key=lambda c: cv2.contourArea(c), reverse=True)  # finds the largest selection, which is a limitation to multiple selection (will be changed in the future versions)
        (x,y,w,h) = cv2.boundingRect(cnts[0])
        ROIRGB = RGBimg[y:y+h, x:x+w]
        ROINDVI = NDVIimg[y:y+h, x:x+w]
    else:
        raise PreventUpdate
    return array_to_data_url(img_as_ubyte(ROIRGB)), array_to_data_url(img_as_ubyte(ROINDVI)) 
Exemple #23
0
def plot_to_image(figure):
    """Converts the matplotlib plot specified by 'figure' to a PNG image and
  returns it. The supplied figure is closed and inaccessible after this call."""
    # Save the plot to a PNG in memory.
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    # Closing the figure prevents it from being displayed directly inside
    # the notebook.
    plt.close(figure)
    buf.seek(0)
    # Convert PNG buffer to TF image
    image = tf.image.decode_png(buf.getvalue(), channels=4)
    # Add the batch dimension
    image = tf.expand_dims(image, 0)
    return image
def imshow(a, format='png', jpeg_fallback=True):
    a = np.asarray(a, dtype=np.uint8)
    str_file = io.BytesIO()
    PIL.Image.fromarray(a).save(str_file, format)
    png_data = str_file.getvalue()
    try:
        disp = IPython.display.display(IPython.display.Image(png_data))
    except IOError:
        if jpeg_fallback and format != 'jpeg':
            print('Warning: image was too large to display in format "{}"; '
                  'trying jpeg instead.').format(format)
            return imshow(a, format='jpeg')
        else:
            raise
            return disp
    def render_color_images(self, poses, scene , mode, IM_SIZE = 0):

        if IM_SIZE == 0:
            IM_SIZE = self.im_size

        subfolder_save = os.path.join(self.folder_name, mode)
        scene.show()
        for i in tqdm(range(len(poses))):

            camera_extrinsics = lookAt(poses[i], np.array([0, 0, 0]))

            #trimesh.constants.log.info('Saving image %d', i)

            # rotate the camera view transform
            camera_old, _geometry = scene.graph[scene.camera.name]
            #camera_new = lookAt(poses[i], np.array([0,0,0]))
            camera_new = camera_extrinsics
            # apply the new transform
            scene.graph[scene.camera.name] = camera_new
            #camera.K = camera_intrinsics_1
            #print(np.matmul(scene.camera.K,np.matmul(camera_extrinsics,np.array([0,0,0,1]))[:3]))

            #aa, bb = scene.graph[scene.camera.name]
            #print("trimesh renders from \n", aa)
            #print("intrinsics\n" , scene.camera.K)
            #scene.show()
            # saving an image requires an opengl context, so if -nw
            # is passed don't save the image
            try:
                # increment the file name
                file_name = os.path.join(subfolder_save, os.path.join("B", 'pose_%d.png' % i))

                # save a render of the object as a png
                png = scene.save_image(resolution=[IM_SIZE * self.anti_alias, IM_SIZE * self.anti_alias], visible=True)
                #image = Image.frombytes("RGB", (IM_SIZE * self.anti_alias, IM_SIZE * self.anti_alias), png, 'raw')
                image = Image.open(io.BytesIO(png))
                # Down sample high resolution version
                if self.anti_alias > 1:
                    image.thumbnail([IM_SIZE, IM_SIZE], PIL.Image.ANTIALIAS)
                image.save(file_name, 'PNG')

                # with open(file_name, 'wb') as f:
                #     f.write(png)
                #     f.close()
                #
            except BaseException as E:
                print("unable to save image", str(E))
            time.sleep(0.05)
Exemple #26
0
def load_images_from_zip(path):
    archive = zipfile.ZipFile(path, 'r')
    name_list = archive.namelist()
    images = np.zeros((len(name_list) - 1, 400, 400, 3))
    idx = 0
    for name in name_list:
        if (name[len(name) - 1] == '/'):
            continue
        img_data = archive.read(name)
        bytes_io = io.BytesIO(img_data)
        img = pygame.image.load(bytes_io)
        img = pygame.surfarray.array3d(img)
        images[idx] = img
        idx += 1
    archive.close()
    return images
Exemple #27
0
def predict(request: Request, img_file: bytes=File(...)):
    data = {"success": False}

    if request.method == "POST":
        image = Image.open(io.BytesIO(img_file))
        image = prepare_image(image,
                              (int(os.environ.get("IMAGE_WIDTH")),
                               int(os.environ.get("IMAGE_HEIGHT")))
                              )

        # Ensure our NumPy array is C-contiguous as well, otherwise we won't be able to serialize it
        image = image.copy(order="C")

        # Generate an ID for the classification then add the classification ID + image to the queue
        k = str(uuid.uuid4())
        image = base64.b64encode(image).decode("utf-8")
        d = {"id": k, "image": image}
        db.rpush(os.environ.get("IMAGE_QUEUE"), json.dumps(d))

        # Keep looping for CLIENT_MAX_TRIES times
        num_tries = 0
        while num_tries < CLIENT_MAX_TRIES:
            num_tries += 1

            # Attempt to grab the output predictions
            output = db.get(k)

            # Check to see if our model has classified the input image
            if output is not None:
                # Add the output predictions to our data dictionary so we can return it to the client
                output = output.decode("utf-8")
                data["predictions"] = json.loads(output)

                # Delete the result from the database and break from the polling loop
                db.delete(k)
                break

            # Sleep for a small amount to give the model a chance to classify the input image
            time.sleep(float(os.environ.get("CLIENT_SLEEP")))

            # Indicate that the request was a success
            data["success"] = True
        else:
            raise HTTPException(status_code=400, detail="Request failed after {} tries".format(CLIENT_MAX_TRIES))

    # Return the data dictionary as a JSON response
    return data
Exemple #28
0
def shapes_seg_pair_as_dict(d, key, seg, remove_old=True):
    """
    Stores shapes and segmentation pair in dict d
    seg is a PIL.Image object
    if remove_old True, deletes all the old keys and values.
    """
    bytes_to_encode = io.BytesIO()
    seg.save(bytes_to_encode, format="png")
    bytes_to_encode.seek(0)

    data = base64.b64encode(bytes_to_encode.read()).decode()

    if remove_old:
        return {key: data}
    d[key] = data

    return d
Exemple #29
0
def make_image(tensor):
    """
    Convert an numpy representation image to Image protobuf.
    Copied from https://github.com/lanpa/tensorboard-pytorch/
    """
    from PIL import Image
    _, height, width, channel = tensor.shape
    image = Image.fromarray(np.squeeze(tensor))
    import io
    output = io.BytesIO()
    image.save(output, format='PNG')
    image_string = output.getvalue()
    output.close()
    return tf.Summary.Image(height=height,
                            width=width,
                            colorspace=channel,
                            encoded_image_string=image_string)
Exemple #30
0
def predict():

    global obj

    data = {"success": False}

    if flask.request.method == "POST":
        if flask.request.files.get("image"):

            # read the image in PIL format
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            x = prepare_image(image)
            pred = obj.predict(prepare_image(image))

            data["predictions"] = pred[0]

            data["success"] = True

    return flask.jsonify(data)