电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

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

瀏覽:2日期:2022-06-19 09:12:44
目錄演示地址:關(guān)于程序開發(fā)環(huán)境資源和依賴包NASA TV feed 流Python第三方庫完整代碼演示地址:

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

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

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

關(guān)于程序

Spacestills會定期從feed流中下載NASA TV靜止幀并將其顯示在GUI中。該程序可以校正幀的縱橫比,并將其保存為PNG格式。它會自動下載最新的幀,并提供手動重新加載,禁用自動重新加載或更改下載頻率的選項。Spacestillsis是一個比較初級的版本,但是它可以做一些有用的事情:捕獲并保存NASA TV直播的太空事件圖像。太空愛好者經(jīng)常在社交網(wǎng)絡(luò)或論壇共享他們從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 BytesIOfrom datetime import datetime, timedeltafrom pathlib import Pathimport requestsfrom requests.exceptions import Timeoutfrom PIL import Imageimport PySimpleGUI as sgFEED_URL = ’https://science.ksc.nasa.gov/shuttle/countdown/video/chan2large.jpg’# Frame size without and with 16:9 aspect ratio correctionWIDTH = 704HEIGHT = 480HEIGHT_16_9 = 396# Minimum, default, and maximum autoreload interval in secondsMIN_DELTA = 45DELTA = MIN_DELTAMAX_DELTA = 300class 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 frameoriginal : PIL.Image Original frame with wchich the instance is initialized, cached in case of resizing to the original sizeMethods -------bytes : Return the raw bytesresize : Resize the screenshotnew_size : Calculate new aspect ratio ''' def __init__(self, image):'''Convert the image to PNG and cache the converted original.Parameters---------- image : PIL.ImageImage to store'''self.image = imageself._topng()self.original = self.image def _topng(self):'''Convert image format of frame to PNG.Returns------- StillFrameFrame 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_imagereturn self def bytes(self):'''Return raw bytes of a frame image.Returns------- bytesByte 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-tupleNew size'''size = self.image.sizeoriginal_size = self.original.sizenew_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-tupleNew sizeReturns------- StillFrameFrame 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 sizeReturns -------PIL.Image Blank image ''' image = Image.new(’RGB’, size=size, color=’blue’) return imagedef download_image(url): '''Download current NASA TV image. Parameters ----------url : str URL to download the image fromReturns -------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 imagedef refresh(window, resize=False, feed=FEED_URL): '''Display the latest still frame in window.Parameters ----------window : sg.Window Window to display the still tofeed : string Feed URLReturns -------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 stilldef 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 stillnew_size : 2-tuple New size of the stillReturns -------StillFrame Frame containing the resized image ''' resized_still = still.resize(new_size) window[’-IMAGE-’].update(data=resized_still.bytes()) return resized_stilldef save(still, path): '''Save still to a file. Parameters ----------still : StillFrame Still to savepath : string File nameReturns -------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 saveddef next_timeout(delta): '''Return the moment in time right now + delta seconds from now. Parameters ----------delta : int Time in seconds until the next timeoutReturns -------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.datetimeReturns -------bool True if the next timeout is due ''' rightnow = datetime.now() return rightnow >= next_timeoutdef 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 timeoutReturns -------int Time in seconds until the next timeoutbool 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 isvalidLAYOUT = [[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’): breakelif ((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 windowif __name__ == ’__main__’: main(LAYOUT)

以上就是用 Python 監(jiān)控 NASA TV 直播畫面的實現(xiàn)步驟的詳細(xì)內(nèi)容,更多關(guān)于Python 監(jiān)控 NASA TV 直播畫面的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 磁力抛光机_磁力研磨机_磁力去毛刺机_精密五金零件抛光设备厂家-冠古科技 | 纸箱抗压机,拉力机,脂肪测定仪,定氮仪-山东德瑞克仪器有限公司 | 铝机箱_铝外壳加工_铝外壳厂家_CNC散热器加工-惠州市铂源五金制品有限公司 | 吊篮式|移动式冷热冲击试验箱-二槽冷热冲击试验箱-广东科宝 | 活性氧化铝|无烟煤滤料|活性氧化铝厂家|锰砂滤料厂家-河南新泰净水材料有限公司 | 科普仪器菏泽市教育教学仪器总厂 | 微量水分测定仪_厂家_卡尔费休微量水分测定仪-淄博库仑 | 缠绕机|缠绕膜包装机|缠绕包装机-上海晏陵智能设备有限公司 | 高效复合碳源-多核碳源生产厂家-污水处理反硝化菌种一长隆科技库巴鲁 | 气动|电动调节阀|球阀|蝶阀-自力式调节阀-上海渠工阀门管道工程有限公司 | 明渠式紫外线杀菌器-紫外线消毒器厂家-定州市优威环保 | 低浓度恒温恒湿称量系统,强光光照培养箱-上海三腾仪器有限公司 | 自动售货机_无人售货机_专业的自动售货机运营商_免费投放售货机-广州富宏主官网 | 台湾HIWIN上银直线模组|导轨滑块|TBI滚珠丝杆丝杠-深圳汉工 | 缠膜机|缠绕包装机|无纺布包装机-济南达伦特机械设备有限公司 | 无痕胶_可移胶_无痕双面胶带_可移无痕胶厂家-东莞凯峰 | 低气压试验箱_高低温低气压试验箱_低气压实验箱 |林频试验设备品牌 | TPE塑胶原料-PPA|杜邦pom工程塑料、PPSU|PCTG材料、PC/PBT价格-悦诚塑胶 | 大型冰雕-景区冰雕展制作公司,3D创意设计源头厂家-[赛北冰雕] | 路面机械厂家| 酒水灌装机-白酒灌装机-酒精果酒酱油醋灌装设备_青州惠联灌装机械 | 我车网|我关心的汽车资讯_汽车图片_汽车生活! | 海外仓系统|国际货代系统|退货换标系统|WMS仓储系统|海豚云 | 家庭教育吧-在线家庭教育平台,专注青少年家庭教育 | 一礼通 (www.yilitong.com)-企业礼品解决方案一站式服务平台 | 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 青岛美佳乐清洁工程有限公司|青岛油烟管道清洗|酒店|企事业单位|学校工厂厨房|青岛油烟管道清洗 插针变压器-家用电器变压器-工业空调变压器-CD型电抗器-余姚市中驰电器有限公司 | 加热制冷恒温循环器-加热制冷循环油浴-杭州庚雨仪器有限公司 | 暖气片十大品牌厂家_铜铝复合暖气片厂家_暖气片什么牌子好_欣鑫达散热器 | 尚为传动-专业高精密蜗轮蜗杆,双导程蜗轮蜗杆,蜗轮蜗杆减速机,蜗杆减速机生产厂家 | 福建珂朗雅装饰材料有限公司「官方网站」 | 搜木网 - 木业全产业链交易平台,免费搜货、低价买货! | 塑胶跑道_学校塑胶跑道_塑胶球场_运动场材料厂家_中国塑胶跑道十大生产厂家_混合型塑胶跑道_透气型塑胶跑道-广东绿晨体育设施有限公司 | 杭州公司变更法人-代理记账收费价格-公司注销代办_杭州福道财务管理咨询有限公司 | 熔体泵_熔体出料泵_高温熔体泵-郑州海科熔体泵有限公司 | 垃圾处理设备_餐厨垃圾处理设备_厨余垃圾处理设备_果蔬垃圾处理设备-深圳市三盛环保科技有限公司 | 苏州工作服定做-工作服定制-工作服厂家网站-尺品服饰科技(苏州)有限公司 | 全自动五线打端沾锡机,全自动裁线剥皮双头沾锡机,全自动尼龙扎带机-东莞市海文能机械设备有限公司 | 珠光砂保温板-一体化保温板-有釉面发泡陶瓷保温板-杭州一体化建筑材料 | 传动滚筒_厂家-淄博海恒机械制造厂 | 小威小说网 - 新小威小说网 - 小威小说网小说搜索引擎 |