CoolFace
Apppublic

pixelprotest/fox-robot

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
utils.py109 linesDownload Raw Back to root
1import os2import cv23import numpy as np4# import sys5import glob6import gradio as gr7import random8# import importlib.util9import datetime10# from tensorflow.lite.python.interpreter import Interpreter11 12# import matplotlib13import matplotlib.pyplot as plt14 15### ---------------------------- image utils ---------------------------------16def parse_image_for_detection(img):17    """18    if img comes from gradio, it makes sure its a numpy array19    if img is a file path, it reads it and converts from BGR to RGB20    it also returns the width and height of the image21    """22    if isinstance(img, str):23        ## if its a file path, we read it and convert from BGR to RGB24        image = cv2.imread(img)25        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)26    else:27        ## otherwise assume its a numpy array from Gradio UI.28        ## but make sure that it actually is.29        if not isinstance(img, np.ndarray):30            img = np.array(img)31        image = img32 33    ## lets also get the width and height of the original image 34    image_height, image_width, _ = image.shape35 36    return image, image_width, image_height37 38def resize_image(np_image, width, height):39    image_resized = cv2.resize(np_image, (width, height))40    np_image = np.expand_dims(image_resized, axis=0)41    return np_image42 43def normalize_image(np_image, interpreter):44    ## check if the model expects a floating point input 45    is_model_float = (interpreter.get_input_details()[0]['dtype'] == np.float32)46 47    ## Normalize pixel values if using a floating model (i.e. if model is non-quantized)48    if is_model_float:49        input_mean = 256.0 / 2.050        input_std = 256.0 / 2.051        np_image = (np.float32(np_image) - input_mean) / input_std52    return np_image53 54def save_image(image, output_dir, output_width=1600, output_height=1200, dpi=80):55    """ 56    saves the image in the output dir, as a matplotlib figure 57    """58    ## make sure output directory exists59    os.makedirs(output_dir, exist_ok=True)60 61    ## first get the figsize in inches based on pixel output width, height62    figsize = get_figsize_from_pixels(output_width, output_height, dpi=dpi)63 64    ## now plot the image65    plt.figure(figsize=figsize)66    plt.imshow(image)67    plt.tight_layout(pad=3)68 69    ## generate an output filename with a timestamp70    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S_%f')71    output_filename = os.path.join(output_dir, f'img_{timestamp}.png')72    ## save the figure with the output filename73    plt.savefig(output_filename, dpi=dpi)74    return output_filename75### ---------------------------- image utils ---------------------------------76 77 78### ---------------------------- basic utils ---------------------------------79def get_labels(labels_filepath):80    with open(labels_filepath, 'r') as f:81        labels = [line.strip() for line in f.readlines()]82    return labels83 84def get_random_images(dirpath, image_count=10):85    """ returns a list of random image filepaths from the dirpath """86    images = glob.glob(dirpath + '/*.jpg') + \87                glob.glob(dirpath + '/*.JPG') + \88                glob.glob(dirpath + '/*.png') + \89                glob.glob(dirpath + '/*.bmp')90 91    # img_filepaths = random.sample(images, image_count)92    # return img_filepaths93    return sorted(images)94 95def get_figsize_from_pixels(width, height, dpi=80):96    """ returns the width and height in inches based on the dpi97    used for matplotlib figures98    """99    width_in = width / dpi100    height_in = height / dpi101    return (width_in, height_in)102### ---------------------------- basic utils ---------------------------------103 104 105 106 107 108 109