最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

用Python監(jiān)控NASA TV直播畫面的實現(xiàn)步驟

 更新時間:2021年05月20日 10:40:59   作者:Python中文社區(qū)  
本文分享一個名為"Spacestills"的開源程序,它可以用于查看 NASA TV 的直播畫面(靜止幀)

演示地址:

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

這是一個具有GUI的簡單系統(tǒng),它訪問feed流并從Web下載數(shù)據(jù)。該程序僅需350行代碼,并依賴于一些開源的Python庫。

關(guān)于程序

Spacestills會定期從feed流中下載NASA TV靜止幀并將其顯示在GUI中。
該程序可以校正幀的縱橫比,并將其保存為PNG格式。它會自動下載最新的幀,并提供手動重新加載,禁用自動重新加載或更改下載頻率的選項。
Spacestillsis是一個比較初級的版本,但是它可以做一些有用的事情:捕獲并保存NASA TV直播的太空事件圖像。太空愛好者經(jīng)常在社交網(wǎng)絡或論壇共享他們從NASA TV手動獲取的屏幕截圖。Spacestills節(jié)省了使用屏幕捕獲工具的時間,并保存了可供共享的圖像文件。您可以在Replit上在線運行Spacestills。

開發(fā)環(huán)境

筆者用Replit開發(fā)了Spacestills。Replit是云上的開發(fā),部署和協(xié)作環(huán)境,它支持包括Python在內(nèi)的數(shù)十種編程語言和框架。作為Chrome操作系統(tǒng)和云計算愛好者,筆者非常喜歡Replit,因為它可以在瀏覽器中完全正常運行,無需下載或安裝任何內(nèi)容。

資源和依賴包

Spacestills依賴于一些外部資源和Python庫。

NASA TV feed 流

肯尼迪航天中心的網(wǎng)站上有一個頁面,其中包含精選的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請求

完整代碼

from io import BytesIO
from datetime import datetime, timedelta
from pathlib import Path
import requests
from requests.exceptions import Timeout
from PIL import Image
import PySimpleGUI as sg


FEED_URL = 'https://science.ksc.nasa.gov/shuttle/countdown/video/chan2large.jpg'

# Frame size without and with 16:9 aspect ratio correction
WIDTH = 704
HEIGHT = 480
HEIGHT_16_9 = 396

# Minimum, default, and maximum autoreload interval in seconds
MIN_DELTA = 45
DELTA = MIN_DELTA
MAX_DELTA = 300


class StillFrame():
    """Holds a still frame.
    
    The image is stored as a PNG PIL.Image and kept in PNG format.
    Attributes
    ----------
        image : PIL.Image
            A still frame
        original : PIL.Image
            Original frame with wchich the instance is initialized, cached in case of
            resizing to the original size
    
    Methods
    -------
        bytes : Return the raw bytes
        resize : Resize the screenshot
        new_size : Calculate new aspect ratio
    """

    def __init__(self, image):
        """Convert the image to PNG and cache the converted original.
        Parameters
        ----------
            image : PIL.Image
                Image to store
        """
        self.image = image
        self._topng()
        self.original = self.image

    def _topng(self):
        """Convert image format of frame to PNG.
        Returns
        -------
            StillFrame
                Frame with image in PNG format
        """
        if not self.image.format == 'PNG':
            png_file = BytesIO()
            self.image.save(png_file, 'png')
            png_file.seek(0)
            png_image = Image.open(png_file)
            self.image = png_image
        return self

    def bytes(self):
        """Return raw bytes of a frame image.
        
        Returns
        -------
            bytes
                Byte stream of the frame image
        """
        file = BytesIO()
        self.image.save(file, 'png')
        file.seek(0)
        return file.read()

    def new_size(self):
        """Return image size toggled between original and 16:9.
        
        Returns
        -------
            2-tuple
                New size
        """
        size = self.image.size
        original_size = self.original.size
        new_size = (WIDTH, HEIGHT_16_9) if size == original_size else (WIDTH, HEIGHT)
        return new_size

    def resize(self, new_size):
        """Resize frame image.
        
        Parameters
        ----------
            new_size : 2-tuple
                New size
        Returns
        -------
            StillFrame
                Frame with image resized
        """
        if not(self.image.size == new_size):
            self.image = self.image.resize(new_size)
        return self
    

def make_blank_image(size=(WIDTH, HEIGHT)):
    """Create a blank image with a blue background.
    
    Parameters
    ----------
        size : 2-tuple
            Image size
    
    Returns
    -------
        PIL.Image
            Blank image
    """
    image = Image.new('RGB', size=size, color='blue')
    return image


def download_image(url):
    """Download current NASA TV image.
    Parameters
    ----------
        url : str
            URL to download the image from
    
    Returns
    -------
        PIL.Image
            Downloaded image if no errors, otherwise blank image
    """
    try:
        response = requests.get(url, timeout=(0.5, 0.5))
        if response.status_code == 200:
            image = Image.open(BytesIO(response.content))
        else:
            image = make_blank_image()
    except Timeout:
        image = make_blank_image()
    return image


def refresh(window, resize=False, feed=FEED_URL):
    """Display the latest still frame in window.
    
    Parameters
    ----------
        window : sg.Window
            Window to display the still to
        feed : string
            Feed URL
    
    Returns
    -------
        StillFrame
            Refreshed screenshot
    """
    still = StillFrame(download_image(feed))
    if resize:
        still = change_aspect_ratio(window, still, new_size=(WIDTH, HEIGHT_16_9))
    else:
        window['-IMAGE-'].update(data=still.bytes())
    return still


def change_aspect_ratio(window, still, new_size=(WIDTH, HEIGHT_16_9)):
    """Change the aspect ratio of the still displayed in window.
    
    Parameters
    ----------
        window : sg.Window
            Window containing the still
        new_size : 2-tuple
            New size of the still
    
    Returns
    -------
        StillFrame
            Frame containing the resized image
    """
    resized_still = still.resize(new_size)
    window['-IMAGE-'].update(data=resized_still.bytes())
    return resized_still


def save(still, path):
    """Save still to a file.
    Parameters
    ----------
        still : StillFrame
            Still to save
        path : string
            File name
    
    Returns
    -------
        Boolean
            True if file saved with no errors
    """
    filename = Path(path)
    try:
        with open(filename, 'wb') as file:
            file.write(still.bytes())
        saved = True
    except OSError:
        saved = False
    return saved


def next_timeout(delta):
    """Return the moment in time right now + delta seconds from now.
    Parameters
    ----------
        delta : int
            Time in seconds until the next timeout
    
    Returns
    -------
        datetime.datetime
            Moment in time of the next timeout
    """
    rightnow = datetime.now()
    return rightnow + timedelta(seconds=delta)


def timeout_due(next_timeout):
    """Return True if the next timeout is due.
    Parameters
    ----------
        next_timeout : datetime.datetime
    
    Returns
    -------
        bool
            True if the next timeout is due
    """
    rightnow = datetime.now()
    return rightnow >= next_timeout


def validate_delta(value):
    """Check if value is an int within the proper range for a time delta.
    Parameters
    ----------
        value : int
            Time in seconds until the next timeout
    
    Returns
    -------
        int
            Time in seconds until the next timeout
        bool
            True if the argument is a valid time delta
    """
    isinteger = False
    try:
        isinteger = type(int(value)) is int
    except Exception:
        delta = DELTA
    delta = int(value) if isinteger else delta
    isvalid = MIN_DELTA <= delta <= MAX_DELTA
    delta = delta if isvalid else DELTA
    return delta, isinteger and isvalid


LAYOUT = [[sg.Image(key='-IMAGE-')],
          [sg.Checkbox('Correct aspect ratio', key='-RESIZE-', enable_events=True),
           sg.Button('Reload', key='-RELOAD-'),
           sg.Button('Save', key='-SAVE-'),
           sg.Exit()],
          [sg.Checkbox('Auto-reload every (seconds):', key='-AUTORELOAD-',
                       default=True),
           sg.Input(DELTA, key='-DELTA-', size=(3, 1), justification='right'),
           sg.Button('Set', key='-UPDATE_DELTA-')]]


def main(layout):
    """Run event loop."""
    window = sg.Window('Spacestills', layout, finalize=True)
    current_still = refresh(window)

    delta = DELTA
    next_reload_time = datetime.now() + timedelta(seconds=delta)

    while True:
        event, values = window.read(timeout=100)
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        elif ((event == '-RELOAD-') or
                (values['-AUTORELOAD-'] and timeout_due(next_reload_time))):
            current_still = refresh(window, values['-RESIZE-'])
            if values['-AUTORELOAD-']:
                next_reload_time = next_timeout(delta)
        elif event == '-RESIZE-':
            current_still = change_aspect_ratio(
                window, current_still, current_still.new_size())
        elif event == '-SAVE-':
            filename = sg.popup_get_file(
                'File name', file_types=[('PNG', '*.png')], save_as=True,
                title='Save image', default_extension='.png')
            if filename:
                saved = save(current_still, filename)
                if not saved:
                    sg.popup_ok('Error while saving file:', filename, title='Error')
        elif event == '-UPDATE_DELTA-':
            # The current cycle should complete at the already scheduled time. So
            # don't update next_reload_time yet because it'll be taken care of at the
            # next -AUTORELOAD- or -RELOAD- event.
            delta, valid = validate_delta(values['-DELTA-'])
            if not valid:
                window['-DELTA-'].update(str(DELTA))

    window.close()
    del window


if __name__ == '__main__':
    main(LAYOUT)

以上就是用 Python 監(jiān)控 NASA TV 直播畫面的實現(xiàn)步驟的詳細內(nèi)容,更多關(guān)于Python 監(jiān)控 NASA TV 直播畫面的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • OpenCV實現(xiàn)常見的四種圖像幾何變換

    OpenCV實現(xiàn)常見的四種圖像幾何變換

    這篇文章主要介紹了利用OpenCV實現(xiàn)的四種圖像幾何變換:縮放、翻轉(zhuǎn)、仿射變換及透視。文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編學習一下
    2022-04-04
  • keras獲得model中某一層的某一個Tensor的輸出維度教程

    keras獲得model中某一層的某一個Tensor的輸出維度教程

    今天小編就為大家分享一篇keras獲得model中某一層的某一個Tensor的輸出維度教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • 用Python實現(xiàn)服務器中只重載被修改的進程的方法

    用Python實現(xiàn)服務器中只重載被修改的進程的方法

    這篇文章主要介紹了用Python實現(xiàn)服務器中只重載被修改的進程的方法,包括用watchdog來檢測文件的變化等,實現(xiàn)起來充分體現(xiàn)了Python作為動態(tài)語言的靈活性,強烈推薦!需要的朋友可以參考下
    2015-04-04
  • python實戰(zhàn)之德州撲克第三步-比較大小

    python實戰(zhàn)之德州撲克第三步-比較大小

    這篇文章主要介紹了python實戰(zhàn)之德州撲克第三步-比較大小,穩(wěn)中有非常詳細的代碼示例,對正在學習python的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-04-04
  • Python基于socket模塊實現(xiàn)UDP通信功能示例

    Python基于socket模塊實現(xiàn)UDP通信功能示例

    這篇文章主要介紹了Python基于socket模塊實現(xiàn)UDP通信功能,結(jié)合實例形式分析了Python使用socket模塊實現(xiàn)IPV4協(xié)議下的UDP通信客戶端與服務器端相關(guān)操作技巧,需要的朋友可以參考下
    2018-04-04
  • Python中的?if?語句及使用方法

    Python中的?if?語句及使用方法

    這篇文章主要介紹了Python中的?if?語句及使用方法,包括條件測試、if?-else?語句、if?-elif-else?語句以及使用?if?語句處理列表操作,下面內(nèi)容詳細介紹組要的小伙伴可以參考一下
    2022-03-03
  • Python企業(yè)編碼生成系統(tǒng)總體系統(tǒng)設計概述

    Python企業(yè)編碼生成系統(tǒng)總體系統(tǒng)設計概述

    這篇文章主要介紹了Python企業(yè)編碼生成系統(tǒng)總體系統(tǒng)設計,簡單描述了Python企業(yè)編碼生成系統(tǒng)的功能、結(jié)構(gòu)與相關(guān)編碼實現(xiàn)技巧,需要的朋友可以參考下
    2019-07-07
  • Flask-Docs自動生成Api文檔安裝使用教程

    Flask-Docs自動生成Api文檔安裝使用教程

    這篇文章主要為大家介紹了Flask-Docs自動生成Api文檔安裝使用教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-10-10
  • 使用Python將圖片轉(zhuǎn)正方形的兩種方法實例代碼詳解

    使用Python將圖片轉(zhuǎn)正方形的兩種方法實例代碼詳解

    這篇文章主要介紹了使用Python將圖片轉(zhuǎn)正方形的兩種方法,本文通過實例代碼給大家給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-04-04
  • python_tkinter事件類型詳情

    python_tkinter事件類型詳情

    這篇文章主要介紹了python_tkinter事件詳情,文章基于python_tkinter事件相關(guān)資料分享的內(nèi)容有事件綁定函數(shù),事件對象等相關(guān)自資料,需要的小伙伴可以參考一下
    2022-03-03

最新評論

武功县| 东阳市| 阜宁县| 峡江县| 开封市| 石首市| 桦甸市| 塘沽区| 资中县| 阜南县| 镇巴县| 芦山县| 青岛市| 从江县| 正镶白旗| 福安市| 正镶白旗| 景东| 东平县| 平安县| 馆陶县| 茌平县| 宜良县| 志丹县| 古丈县| 伊吾县| 新化县| 潼南县| 台东市| 依安县| 元阳县| 金沙县| 安陆市| 阿坝县| 锡林郭勒盟| 九江县| 东阳市| 红河县| 甘南县| 远安县| 河南省|