Spaces:
Sleeping
Sleeping
chore: display the image from the url
Browse files
app.py
CHANGED
@@ -1,9 +1,22 @@
|
|
|
|
1 |
import streamlit as st
|
2 |
import tensorflow as tf
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from . import utils
|
2 |
import streamlit as st
|
3 |
import tensorflow as tf
|
4 |
|
5 |
+
def main():
|
6 |
+
image_url = st.text_input(
|
7 |
+
label="URL of image",
|
8 |
+
value="",
|
9 |
+
placeholder="https://your-favourite-image.png"
|
10 |
+
)
|
11 |
+
|
12 |
+
# Preprocess the same image but with normlization.
|
13 |
+
img_url = "https://dl.fbaipublicfiles.com/dino/img.png"
|
14 |
+
image, preprocessed_image = utils.load_image_from_url(
|
15 |
+
image_url,
|
16 |
+
model_type="dino"
|
17 |
+
)
|
18 |
+
st.image(image, caption="Original Image")
|
19 |
+
|
20 |
+
|
21 |
+
if __name__ == "__main__":
|
22 |
+
main()
|
utils.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# import the necessary packages
|
2 |
+
import tensorflow as tf
|
3 |
+
from tensorflow.keras import layers
|
4 |
+
|
5 |
+
from PIL import Image
|
6 |
+
from io import BytesIO
|
7 |
+
import requests
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
|
11 |
+
RESOLUTION = 224
|
12 |
+
|
13 |
+
crop_layer = layers.CenterCrop(RESOLUTION, RESOLUTION)
|
14 |
+
norm_layer = layers.Normalization(
|
15 |
+
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
|
16 |
+
variance=[(0.229 * 255) ** 2, (0.224 * 255) ** 2, (0.225 * 255) ** 2],
|
17 |
+
)
|
18 |
+
rescale_layer = layers.Rescaling(scale=1./127.5, offset=-1)
|
19 |
+
|
20 |
+
|
21 |
+
def preprocess_image(image, model_type, size=RESOLUTION):
|
22 |
+
# Turn the image into a numpy array and add batch dim.
|
23 |
+
image = np.array(image)
|
24 |
+
image = tf.expand_dims(image, 0)
|
25 |
+
|
26 |
+
# If model type is vit rescale the image to [-1, 1].
|
27 |
+
if model_type == "original_vit":
|
28 |
+
image = rescale_layer(image)
|
29 |
+
|
30 |
+
# Resize the image using bicubic interpolation.
|
31 |
+
resize_size = int((256 / 224) * size)
|
32 |
+
image = tf.image.resize(
|
33 |
+
image,
|
34 |
+
(resize_size, resize_size),
|
35 |
+
method="bicubic"
|
36 |
+
)
|
37 |
+
|
38 |
+
# Crop the image.
|
39 |
+
image = crop_layer(image)
|
40 |
+
|
41 |
+
# If model type is DeiT or DINO normalize the image.
|
42 |
+
if model_type != "original_vit":
|
43 |
+
image = norm_layer(image)
|
44 |
+
|
45 |
+
return image.numpy()
|
46 |
+
|
47 |
+
|
48 |
+
def load_image_from_url(url, model_type):
|
49 |
+
# Credit: Willi Gierke
|
50 |
+
response = requests.get(url)
|
51 |
+
image = Image.open(BytesIO(response.content))
|
52 |
+
preprocessed_image = preprocess_image(image, model_type)
|
53 |
+
return image, preprocessed_image
|