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