用 Python 监控 NASA TV 直播画面

开发 后端
本文分享一个名为"Spacestills"的开源程序,它可以用于查看 NASA TV 的直播画面(静止帧)。

 本文分享一个名为"Spacestills"的开源程序,它可以用于查看 NASA TV 的直播画面(静止帧)。

演示地址:

https://replit.com/@PaoloAmoroso/spacestills

在Replit上运行的Spacestills主窗口

这是一个具有GUI的简单系统,它访问feed流并从Web下载数据。该程序仅需350行代码,并依赖于一些开源的Python库。

关于程序

Spacestills会定期从feed流中下载NASA TV静止帧并将其显示在GUI中。

该程序可以校正帧的纵横比,并将其保存为PNG格式。它会自动下载最新的帧,并提供手动重新加载,禁用自动重新加载或更改下载频率的选项。

Spacestillsis是一个比较初级的版本,但是它可以做一些有用的事情:捕获并保存NASA TV直播的太空事件图像。太空爱好者经常在社交网络或论坛共享他们从NASA TV手动获取的屏幕截图。Spacestills节省了使用屏幕捕获工具的时间,并保存了可供共享的图像文件。您可以在Replit上在线运行Spacestills。

开发环境

笔者用Replit开发了Spacestills。Replit是云上的开发,部署和协作环境,它支持包括Python在内的数十种编程语言和框架。作为Chrome操作系统和云计算爱好者,笔者非常喜欢Replit,因为它可以在浏览器中完全正常运行,无需下载或安装任何内容。

资源和依赖包

Spacestills依赖于一些外部资源和Python库。

  •  NASA TV feed 流

肯尼迪航天中心的网站上有一个页面,其中包含精选的NASA视频流,包括NASA电视公共频道。feed流显示最新的静止帧并自动更新。

每个feed都带有三种尺寸的帧,Spacestills依赖于具有704x408像素帧的最大NASA TV feed流。最大更新频率为每45秒一次。因此,检索最新的静止帧就像从feed流的URL下载JPEG图像一样简单。

原始图像被垂直拉伸,看起来很奇怪。因此,该程序可以通过压缩图像并生成未失真的16:9版本来校正纵横比。

  •  Python

因PySimpleGUI的原因需要安装 Python 3.6 版本。

  •  第三方库

Pillow:图像处理

PySimpleGUI:GUI框架(Spacestills使用Tkinter后端)

Request:HTTP请求

完整代码 

  1. from io import BytesIO  
  2. from datetime import datetime, timedelta  
  3. from pathlib import Path  
  4. import requests  
  5. from requests.exceptions import Timeout  
  6. from PIL import Image  
  7. import PySimpleGUI as sg 
  8. FEED_URL = 'https://science.ksc.nasa.gov/shuttle/countdown/video/chan2large.jpg' 
  9. # Frame size without and with 16:9 aspect ratio correction  
  10. WIDTH = 704  
  11. HEIGHT = 480  
  12. HEIGHT_16_9 = 396 
  13. # Minimum, default, and maximum autoreload interval in seconds  
  14. MIN_DELTA = 45  
  15. DELTA = MIN_DELTA  
  16. MAX_DELTA = 300  
  17. class StillFrame():  
  18.     """Holds a still frame.  
  19.     The image is stored as a PNG PIL.Image and kept in PNG format.  
  20.     Attributes  
  21.     ----------  
  22.         image : PIL.Image  
  23.             A still frame  
  24.         original : PIL.Image  
  25.             Original frame with wchich the instance is initialized, cached in case of  
  26.             resizing to the original size  
  27.      Methods  
  28.     -------  
  29.         bytes : Return the raw bytes  
  30.         resize : Resize the screenshot  
  31.         new_size : Calculate new aspect ratio  
  32.     """ 
  33.     def __init__(self, image):  
  34.         """Convert the image to PNG and cache the converted original.  
  35.         Parameters  
  36.         ----------  
  37.             image : PIL.Image  
  38.                 Image to store  
  39.         """  
  40.         self.image = image  
  41.         self._topng()  
  42.         selfself.original = self.image  
  43.     def _topng(self):  
  44.         """Convert image format of frame to PNG.  
  45.         Returns  
  46.         -------  
  47.             StillFrame  
  48.                 Frame with image in PNG format  
  49.         """  
  50.         if not self.image.format == 'PNG':  
  51.             png_file = BytesIO()  
  52.             self.image.save(png_file, 'png')  
  53.             png_file.seek(0)  
  54.             png_image = Image.open(png_file)  
  55.             self.image = png_image  
  56.         return self 
  57.     def bytes(self):  
  58.         """Return raw bytes of a frame image.       
  59.          Returns  
  60.         -------  
  61.             bytes  
  62.                 Byte stream of the frame image  
  63.         """  
  64.         file = BytesIO()  
  65.         self.image.save(file, 'png')  
  66.         file.seek(0)  
  67.         return file.read()  
  68.     def new_size(self):  
  69.         """Return image size toggled between original and 16:9.      
  70.          Returns  
  71.         -------  
  72.             2-tuple  
  73.                 New size  
  74.         """  
  75.         size = self.image.size  
  76.         original_size = self.original.size  
  77.         new_size = (WIDTH, HEIGHT_16_9) if size == original_size else (WIDTH, HEIGHT)  
  78.         return new_size  
  79.     def resize(self, new_size):  
  80.         """Resize frame image.       
  81.          Parameters  
  82.         ----------  
  83.             new_size : 2-tuple  
  84.                 New size  
  85.         Returns  
  86.         -------  
  87.             StillFrame  
  88.                 Frame with image resized  
  89.         """  
  90.         if not(self.image.size == new_size):  
  91.             selfself.image = self.image.resize(new_size)  
  92.         return self 
  93. def make_blank_image(size=(WIDTH, HEIGHT)):  
  94.     """Create a blank image with a blue background.   
  95.      Parameters  
  96.     ----------  
  97.         size : 2-tuple  
  98.             Image size  
  99.      Returns  
  100.     -------  
  101.         PIL.Image  
  102.             Blank image  
  103.     """  
  104.     image = Image.new('RGB', sizesize=size, color='blue' 
  105.     return image  
  106. def download_image(url):  
  107.     """Download current NASA TV image.  
  108.     Parameters  
  109.     ----------  
  110.         url : str  
  111.             URL to download the image from   
  112.      Returns  
  113.     -------  
  114.         PIL.Image  
  115.             Downloaded image if no errors, otherwise blank image  
  116.     """  
  117.     try:  
  118.         response = requests.get(url, timeout=(0.5, 0.5))  
  119.         if response.status_code == 200:  
  120.             image = Image.open(BytesIO(response.content)) 
  121.         else:  
  122.             image = make_blank_image()  
  123.     except Timeout:  
  124.         image = make_blank_image()  
  125.     return image 
  126. def refresh(window, resize=Falsefeed=FEED_URL):  
  127.     """Display the latest still frame in window.    
  128.      Parameters  
  129.     ----------  
  130.         window : sg.Window  
  131.             Window to display the still to  
  132.         feed : string  
  133.             Feed URL    
  134.      Returns  
  135.     -------  
  136.         StillFrame  
  137.             Refreshed screenshot  
  138.     """  
  139.     still = StillFrame(download_image(feed))  
  140.     if resize:  
  141.         still = change_aspect_ratio(window, still, new_size=(WIDTH, HEIGHT_16_9))  
  142.     else:  
  143.         window['-IMAGE-'].update(data=still.bytes())  
  144.     return still  
  145. def change_aspect_ratio(window, still, new_size=(WIDTH, HEIGHT_16_9)):  
  146.     """Change the aspect ratio of the still displayed in window.  
  147.      Parameters  
  148.     ----------  
  149.         window : sg.Window  
  150.             Window containing the still  
  151.         new_size : 2-tuple  
  152.             New size of the still   
  153.      Returns  
  154.     -------  
  155.         StillFrame  
  156.             Frame containing the resized image  
  157.     """  
  158.     resized_still = still.resize(new_size)  
  159.     window['-IMAGE-'].update(data=resized_still.bytes())  
  160.     return resized_still  
  161. def save(still, path):  
  162.     """Save still to a file.  
  163.     Parameters  
  164.     ----------  
  165.         still : StillFrame  
  166.             Still to save  
  167.         path : string  
  168.             File name  
  169.      Returns  
  170.     -------  
  171.         Boolean  
  172.             True if file saved with no errors  
  173.     """  
  174.     filename = Path(path)  
  175.     try:  
  176.         with open(filename, 'wb') as file:  
  177.             file.write(still.bytes())  
  178.         saved = True  
  179.     except OSError:  
  180.         saved = False  
  181.     return saved  
  182. def next_timeout(delta):  
  183.     """Return the moment in time right now + delta seconds from now.  
  184.     Parameters  
  185.     ----------  
  186.         delta : int  
  187.             Time in seconds until the next timeout  
  188.      Returns  
  189.     -------  
  190.         datetime.datetime  
  191.             Moment in time of the next timeout  
  192.     """  
  193.     rightnow = datetime.now()  
  194.     return rightnow + timedelta(seconds=delta
  195. def timeout_due(next_timeout):  
  196.     """Return True if the next timeout is due.  
  197.     Parameters  
  198.     ----------  
  199.         next_timeout : datetime.datetime   
  200.      Returns  
  201.     -------  
  202.         bool  
  203.             True if the next timeout is due  
  204.     """  
  205.     rightnow = datetime.now()  
  206.     return rightnow >= next_timeout   
  207. def validate_delta(value):  
  208.     """Check if value is an int within the proper range for a time delta.  
  209.     Parameters  
  210.     ----------  
  211.         value : int  
  212.             Time in seconds until the next timeout    
  213.      Returns  
  214.     -------  
  215.         int  
  216.             Time in seconds until the next timeout  
  217.         bool  
  218.             True if the argument is a valid time delta  
  219.     """  
  220.     isinteger = False  
  221.     try:  
  222.         isinteger = type(int(value)) is int  
  223.     except Exception:  
  224.         delta = DELTA  
  225.     delta = int(value) if isinteger else delta  
  226.     isvalid = MIN_DELTA <= delta <= MAX_DELTA  
  227.     deltadelta = delta if isvalid else DELTA  
  228.     return delta, isinteger and isvalid  
  229. LAYOUT = [[sg.Image(key='-IMAGE-')],  
  230.           [sg.Checkbox('Correct aspect ratio', key='-RESIZE-'enable_events=True),  
  231.            sg.Button('Reload', key='-RELOAD-'),  
  232.            sg.Button('Save', key='-SAVE-'),  
  233.            sg.Exit()],  
  234.           [sg.Checkbox('Auto-reload every (seconds):', key='-AUTORELOAD-' 
  235.                        default=True),  
  236.            sg.Input(DELTA, key='-DELTA-'size=(3, 1), justification='right'),  
  237.            sg.Button('Set', key='-UPDATE_DELTA-')]]  
  238. def main(layout):  
  239.     """Run event loop."""  
  240.     window = sg.Window('Spacestills', layout, finalize=True 
  241.     current_still = refresh(window)  
  242.     delta = DELTA  
  243.     next_reload_time = datetime.now() + timedelta(seconds=delta 
  244.     while True:  
  245.         event, values = window.read(timeout=100 
  246.         if event in (sg.WIN_CLOSED, 'Exit'):  
  247.             break  
  248.         elif ((event == '-RELOAD-') or  
  249.                 (values['-AUTORELOAD-'] and timeout_due(next_reload_time))):  
  250.             current_still = refresh(window, values['-RESIZE-'])  
  251.             if values['-AUTORELOAD-']:  
  252.                 next_reload_time = next_timeout(delta)  
  253.         elif event == '-RESIZE-':  
  254.             current_still = change_aspect_ratio 
  255.                 window, current_still, current_still.new_size())  
  256.         elif event == '-SAVE-':  
  257.             filename = sg.popup_get_file(  
  258.                 'File name', file_types=[('PNG', '*.png')], save_as=True 
  259.                 title='Save image'default_extension='.png' 
  260.             if filename:  
  261.                 savesaved = save(current_still, filename)  
  262.                 if not saved:  
  263.                     sg.popup_ok('Error while saving file:', filename, title='Error' 
  264.         elif event == '-UPDATE_DELTA-':  
  265.             # The current cycle should complete at the already scheduled time. So  
  266.             # don't update next_reload_time yet because it'll be taken care of at the  
  267.             # next -AUTORELOAD- or -RELOAD- event.  
  268.             delta, valid = validate_delta(values['-DELTA-'])  
  269.             if not valid:  
  270.                 window['-DELTA-'].update(str(DELTA))  
  271.     window.close() 
  272.     del window  
  273. if __name__ == '__main__':  
  274.     main(LAYOUT)  

 

责任编辑:庞桂玉 来源: Python中文社区 (ID:python-china)
相关推荐

2015-06-30 17:41:31

战旗TV

2013-02-01 10:09:46

TV客

2019-11-22 23:46:38

PythonNBAsh球员

2021-06-04 10:31:41

PythonUniswap加密货币

2016-07-05 14:50:57

熊猫 领域

2016-05-12 17:41:44

2022-03-24 14:42:19

Python编程语言

2023-04-09 23:17:16

Python监控城市空气

2012-01-06 10:42:43

NASA开源

2011-09-30 13:04:17

51CTO博客一周热门监控网络

2020-12-09 11:53:24

鸿蒙开发HelloWord

2020-01-13 07:42:01

技术研发指标

2020-05-07 09:05:22

电脑Python代码

2014-01-02 15:16:42

PythonLinux服务器服务器监控

2016-05-17 20:57:43

2012-08-07 08:55:40

2012-01-10 09:30:02

UbuntuCanonical

2011-05-31 16:14:26

Android

2015-01-27 15:30:10

反监控监控探测SnoopSnitch

2017-12-20 10:33:02

直播
点赞
收藏

51CTO技术栈公众号