CoolFace
Apppublic

GDavila/GIFify_OpenCV

sourceHugging Facemitupdated 4y agoView on Hugging Face
4likes
app.py120 linesDownload Raw Back to root
1import streamlit as st2import cv23import numpy as np4from PIL import Image5import base646 7color_step = st.slider('color_step parameter. Inversely proportional to the number of colors that will be sampled. Choose 1 to get the max number of colors, anything above 90 to get just 2 colors, The default value 10 yields 18 colors.', value=10, min_value=1, max_value=179, step=1)8 9#duration of each frame of the gif in milliseconds 10duration_parameter = st.slider('duration_parameter aka duration of each frame of the gif in milliseconds', value=10, min_value=1, max_value=2000, step=10)11 12#Loop parameter = number of times gif loops. 0 = loops infinitely. 13loop_parameter = st.slider('Loop parameter aka number of times gif loops. 0 defaults to infinitely repeating gif, like most gifs', value=0, min_value=0, max_value=10, step=1)14 15 16if color_step == 0:17  my_hue_list = [0]18else:19  my_hue_list = list( range(0, 180, color_step) ) #Color step basically gives step range of this list, ie if color_step = 2 then it is [0,2,4,6,....,178]20 21 22st.write("Upload an image and this app will turn it into a GIF based on the slider values. Larger images will take longer to process, max image size under 2MB. Lower values of the color_step parameter will take longer to process. Refresh the page to reprocess an image under different parameters.")23user_image_object = st.file_uploader("upload your image", type=['png', 'jpg'], accept_multiple_files=False)24 25if user_image_object is not None:26  st.image(user_image_object )27  28  29  user_image_name = "input_image.png"30  31  #re-encode for streamlit interface32  #streamlit uploader encodes as a pillow img so we want to save to open in cv2 (converting directly is a pain)33  input_image = Image.open( user_image_object )34  input_image.save(user_image_name )35 36  # load image with alpha channel37  img = cv2.imread( user_image_name , cv2.IMREAD_UNCHANGED)38  39  # extract alpha channel  40  #alpha = img[:,:,3]41  42  # extract bgr channels43  bgr = img[:,:,0:3]44  45  # convert to HSV46  hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)47  #h = hsv[:,:,0]48  #s = hsv[:,:,1]49  #v = hsv[:,:,2]50  h,s,v = cv2.split(hsv)51  52  53  if color_step == 0:54    my_hue_list = [0]55  else:56    my_hue_list = list( range(0, 180, color_step) ) #Color step basically gives step range of this list, ie if color_step = 2 then it is [0,2,4,6,....,178]57  #180 at end means highest it can go is 179 (same as hue param )58  #including 0 makes original image part of the outputs/gif 59  60  #H,S,V = Hue , Saturation, Value (ie color value) parameters61  #Hue has range [0,179] , Saturation [0,255] , Value [0,255]62  63  img_array = []64  output_filename_array = []65  for i in my_hue_list:66    # modify hue channel by adding difference and modulo 180 (modulo because hue parameter only goes up to index 180, shouldn't exceed that )67    hnew = np.mod(h + i, 180).astype(np.uint8)   #<<<<<<<<<<<<<<<< where the iter comes in 68  69    # recombine channels70    hsv_new = cv2.merge([hnew,s,v])71  72    # convert back to bgr73    bgr_new = cv2.cvtColor(hsv_new, cv2.COLOR_HSV2BGR)74    75    img_array.append(bgr_new )76  77    # put alpha back into bgr_new78    #bgra = cv2.cvtColor(bgr_new, cv2.COLOR_BGR2BGRA)79    #bgra[:,:,3] = alpha80  81    # save output AS FILE LABELED BY ITERABLE 82    output_filename = 'output_bgr_new_' + str(i) +'.png'        #<<<<<<<<<<<<<<<< where the iter comes in 83    output_filename_array.append(output_filename)84    cv2.imwrite(output_filename, bgr_new)85  86  87  height, width, layers = bgr_new.shape88  size = (width,height)89  90  st.write("This algorithm creates a GIF from images by creating hue shifted aka different color images from your input images bases on the parameters you chose in the slider above. The current set of parameters yields this many images: \n   len(img_array) = ", len(img_array) , "   \n So you GIF  will be a composite of this many images changing color.")91  92  '''Show some demos: '''93  94  #Uncomment this if statement to show some sample images of the gif 95  #if len(img_array) > 7:96  #  for ii in [1, 4, 7]:97  #    st.image( img_array[ii] )98  99  #HuggingFaces Spaces can create a video vile ephemerally but doesn't actually save one that we can access. 100  #So to show the video/gif we save it as a file then open that file to show it in streamlit101  102  st.text("Generating GIF, may take a minute. You should see it appear on screen. ")103  104  #Create GIF105  img, *imgs = [Image.open(f) for f in output_filename_array]106  img.save(fp="output_gif.gif", format='GIF', append_images=imgs,107         save_all=True, duration=duration_parameter, loop=loop_parameter)108  109  110  #Show gif using this script to show gifs in streamlit https://discuss.streamlit.io/t/how-to-show-local-gif-image/3408/2111  """### gif from local file"""112  file_ = open("output_gif.gif", "rb")113  contents = file_.read()114  data_url = base64.b64encode(contents).decode("utf-8")115  file_.close()116  117  st.markdown(118      f'<img src="data:image/gif;base64,{data_url}" alt="output gif">',119      unsafe_allow_html=True,120  )