|
import subprocess |
|
import importlib |
|
|
|
|
|
packages = ['cv2', 'numpy', 'tensorflow', 'gr'] |
|
|
|
|
|
package_mapping = {'cv2': 'opencv-python-headless'} |
|
|
|
|
|
for package in packages: |
|
try: |
|
importlib.import_module(package) |
|
except ImportError: |
|
print(f"{package} not found. Installing...") |
|
|
|
|
|
install_package = package_mapping.get(package, package) |
|
|
|
install_command = ['pip', 'install', install_package] |
|
subprocess.run(install_command, check=True) |
|
|
|
|
|
import cv2 |
|
import numpy as np |
|
import tensorflow as tf |
|
import gradio as gr |
|
|
|
|
|
def remove_background_deeplab(image): |
|
|
|
interpreter = tf.lite.Interpreter(model_path="2.tflite") |
|
interpreter.allocate_tensors() |
|
|
|
input_details = interpreter.get_input_details() |
|
output_details = interpreter.get_output_details() |
|
|
|
|
|
image_np = np.array(image.data) |
|
|
|
|
|
input_size = (257, 257) |
|
image_resized = cv2.resize(image_np, input_size) |
|
|
|
|
|
input_tensor = (image_resized / 127.5 - 1.0).astype(np.float32) |
|
|
|
|
|
interpreter.set_tensor(input_details[0]['index'], np.expand_dims(input_tensor, axis=0)) |
|
|
|
|
|
interpreter.invoke() |
|
|
|
|
|
predictions = interpreter.get_tensor(output_details[0]['index']) |
|
mask = np.argmax(predictions, axis=-1)[0] |
|
|
|
|
|
binary_mask = cv2.resize(np.where(mask == 15, 1, 0).astype(np.uint8), (image_np.shape[1], image_np.shape[0])) |
|
|
|
|
|
result = image_np * binary_mask[:, :, np.newaxis] |
|
|
|
|
|
result_image = gr.Image(result) |
|
|
|
return result_image |
|
|
|
|
|
gr.Interface( |
|
fn=remove_background_deeplab, |
|
inputs=gr.Image(label='Drop an Image or Open Camera to Classify'), |
|
outputs=gr.Image() |
|
).launch() |
|
|