moonPhase

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

moonphase.py (3254B)


      1 import urllib.request as req
      2 import os
      3 import imageio
      4 import argparse
      5 import subprocess
      6 
      7 # Argument parser
      8 parser = argparse.ArgumentParser("Download Moon Images and Create Video")
      9 parser.add_argument("-t", "--thinning", default=1, help="Frequency of images to download, e.g. every 10th image")
     10 parser.add_argument("-f", "--ffmpeg", action='store_true', help="Use ffmpeg to create video")
     11 args = parser.parse_args()
     12 
     13 
     14 def addZeros(imageNumber):
     15     """Add leading zeros to a number, up to 4 digits."""
     16     numAdd = 4 - len(str(imageNumber))
     17     return "0" * numAdd + str(imageNumber)
     18 
     19 def getImage(imageNumber, directory):
     20     """Download an image given an image to an output directory"""
     21     URL = (
     22             "https://svs.gsfc.nasa.gov"
     23             "/vis/a000000/a004600/a004604/frames/"
     24             "730x730_1x1_30p/moon.{}.jpg"
     25             ).format(imageNumber)
     26 
     27     imageName = directory + imageNumber + ".jpg"
     28     req.urlretrieve(URL, imageName)
     29     return
     30 
     31 def makeVideo(directory, startNumber, thinning, ffmpeg=False):
     32     """Create a video with the downloaded images"""
     33     
     34     # Get a list of all the files 
     35     files = [image for image in os.listdir(directory) if ".jpg" in image]
     36     
     37 
     38     # Create a video using ffmpeg command
     39     if ffmpeg:
     40         frameRate = str(len(files)/60)
     41         subprocess.run(
     42                 ["ffmpeg",
     43                 "-r", frameRate, 
     44                 "-pattern_type", "glob",
     45                 "-i", "./images/*.jpg",
     46                 "-vb", "20M", "moon.mp4"], check=True)
     47     
     48     else:
     49         # Save each image frame to a list
     50         images = []
     51         for imageNumber in range(startNumber, 8761, thinning):
     52             imageName = directory + addZeros(imageNumber) + ".jpg"
     53             images.append(imageio.imread(imageName))
     54 
     55         imageio.mimsave('moon.gif', images)
     56     return
     57 
     58 def main(startNumber=1, thinning=1, ffmpeg=False):
     59     
     60     directory = 'images/'
     61 
     62     if not os.path.exists(directory):
     63         os.makedirs(directory)
     64     
     65     for i, imageNumber in enumerate(range(startNumber, 8761, thinning)):
     66         percent = round(imageNumber/87.61)
     67         imageNumber = addZeros(imageNumber)
     68         
     69         # Skip if already downloaded
     70         if os.path.exists(directory + imageNumber + ".jpg"):
     71             print("Already downloaded " + imageNumber)  
     72             continue
     73             
     74         while True:
     75             try:
     76                 getImage(imageNumber, directory)
     77                 
     78                 # Create progress bar, we use 0.5*percentage
     79                 # for a shorter bar
     80                 bar = (
     81                         "["
     82                         + "#" * int(0.5 * percent)
     83                         + "-" * int(0.5 * (100 - percent))
     84                         + "]"
     85                 )
     86                 
     87                 # Clear terminal
     88                 print('\033c')
     89 
     90                 # Print progress
     91                 status = "Downloaded {}/{}, {}% ".format(i, 8761//thinning, percent)
     92                 print(status + bar)
     93 
     94             except Exception as e:
     95                 print(e)
     96                 continue
     97             break
     98             
     99     print("Making video...")
    100     makeVideo(directory, startNumber, thinning, ffmpeg)
    101     return
    102 
    103 
    104 main(1, int(args.thinning), args.ffmpeg)
    105 
    106