Пытаюсь добавить модель resNet50, обученную на Python, в мой проект React Native с использованием TensorFlow.js для прогнозирования изображений, чтобы предоставить 5 похожих изображений на основе входных данных:
import streamlit as st
import os
from PIL import Image
import numpy as np
import pickle
import tensorflow
from tensorflow.keras.layers import GlobalMaxPooling2D
from tensorflow.keras.applications.resnet50 import ResNet50,preprocess_input
from sklearn.neighbors import NearestNeighbors
from numpy.linalg import norm
import cv2
feature_list = np.array(pickle.load(open('featurevector.pkl','rb')))
filenames = pickle.load(open('filenames.pkl','rb'))
model = ResNet50(weights='imagenet',include_top=False,input_shape=(224,224,3))
model.trainable = False
model = tensorflow.keras.Sequential([
model,
GlobalMaxPooling2D()
])
st.title('Man & Women Fashion Recommender System')
def save_uploaded_file(uploaded_file):
try:
with open(os.path.join('uploads',uploaded_file.name),'wb') as f:
f.write(uploaded_file.getbuffer())
return 1
except:
return 0
def extract_feature(img_path, model):
img=cv2.imread(img_path)
img=cv2.resize(img, (224,224))
img=np.array(img)
expand_img=np.expand_dims(img, axis=0)
pre_img=preprocess_input(expand_img)
result=model.predict(pre_img).flatten()
normalized=result/norm(result)
return normalized
def recommend(features,feature_list):
neighbors = NearestNeighbors(n_neighbors=6, algorithm='brute', metric='euclidean')
neighbors.fit(feature_list)
distances, indices = neighbors.kneighbors([features])
return indices
# steps
# file upload -> save
uploaded_file = st.file_uploader("Choose an image")
print(uploaded_file)
if uploaded_file is not None:
if save_uploaded_file(uploaded_file):
# display the file
display_image = Image.open(uploaded_file)
resized_img = display_image.resize((200, 200))
st.image(resized_img)
# feature extract
features = extract_feature(os.path.join("uploads",uploaded_file.name),model)
#st.text(features)
# recommendention
indices = recommend(features,feature_list)
# show
col1,col2,col3,col4,col5 = st.columns(5)
with col1:
st.image(filenames[indices[0][1]])
with col2:
st.image(filenames[indices[0][2]])
with col3:
st.image(filenames[indices[0][3]])
with col4:
st.image(filenames[indices[0][4]])
with col5:
st.image(filenames[indices[0][5]])
else:
st.header("Some error occured in file upload")
Подробнее здесь: https://stackoverflow.com/questions/781 ... sorflow-js
Как запустить модель Python в React Native, используя TensorFlow.js? ⇐ Android
Форум для тех, кто программирует под Android
1710473073
Anonymous
Пытаюсь добавить модель resNet50, обученную на Python, в мой проект React Native с использованием TensorFlow.js для прогнозирования изображений, чтобы предоставить 5 похожих изображений на основе входных данных:
import streamlit as st
import os
from PIL import Image
import numpy as np
import pickle
import tensorflow
from tensorflow.keras.layers import GlobalMaxPooling2D
from tensorflow.keras.applications.resnet50 import ResNet50,preprocess_input
from sklearn.neighbors import NearestNeighbors
from numpy.linalg import norm
import cv2
feature_list = np.array(pickle.load(open('featurevector.pkl','rb')))
filenames = pickle.load(open('filenames.pkl','rb'))
model = ResNet50(weights='imagenet',include_top=False,input_shape=(224,224,3))
model.trainable = False
model = tensorflow.keras.Sequential([
model,
GlobalMaxPooling2D()
])
st.title('Man & Women Fashion Recommender System')
def save_uploaded_file(uploaded_file):
try:
with open(os.path.join('uploads',uploaded_file.name),'wb') as f:
f.write(uploaded_file.getbuffer())
return 1
except:
return 0
def extract_feature(img_path, model):
img=cv2.imread(img_path)
img=cv2.resize(img, (224,224))
img=np.array(img)
expand_img=np.expand_dims(img, axis=0)
pre_img=preprocess_input(expand_img)
result=model.predict(pre_img).flatten()
normalized=result/norm(result)
return normalized
def recommend(features,feature_list):
neighbors = NearestNeighbors(n_neighbors=6, algorithm='brute', metric='euclidean')
neighbors.fit(feature_list)
distances, indices = neighbors.kneighbors([features])
return indices
# steps
# file upload -> save
uploaded_file = st.file_uploader("Choose an image")
print(uploaded_file)
if uploaded_file is not None:
if save_uploaded_file(uploaded_file):
# display the file
display_image = Image.open(uploaded_file)
resized_img = display_image.resize((200, 200))
st.image(resized_img)
# feature extract
features = extract_feature(os.path.join("uploads",uploaded_file.name),model)
#st.text(features)
# recommendention
indices = recommend(features,feature_list)
# show
col1,col2,col3,col4,col5 = st.columns(5)
with col1:
st.image(filenames[indices[0][1]])
with col2:
st.image(filenames[indices[0][2]])
with col3:
st.image(filenames[indices[0][3]])
with col4:
st.image(filenames[indices[0][4]])
with col5:
st.image(filenames[indices[0][5]])
else:
st.header("Some error occured in file upload")
Подробнее здесь: [url]https://stackoverflow.com/questions/78163861/how-to-run-a-python-model-in-react-native-using-tensorflow-js[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия