五月综合激情婷婷六月,日韩欧美国产一区不卡,他扒开我内裤强吻我下面视频 ,无套内射无矿码免费看黄,天天躁,日日躁,狠狠躁

新聞動態(tài)

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

發(fā)布日期:2022-05-30 14:33 | 文章來源:腳本之家

演示地址:

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)絡(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請求

完整代碼

fromioimportBytesIO
fromdatetimeimportdatetime,timedelta
frompathlibimportPath
importrequests
fromrequests.exceptionsimportTimeout
fromPILimportImage
importPySimpleGUIassg

FEED_URL='https://science.ksc.nasa.gov/shuttle/countdown/video/chan2large.jpg'
#Framesizewithoutandwith16:9aspectratiocorrection
WIDTH=704
HEIGHT=480
HEIGHT_16_9=396
#Minimum,default,andmaximumautoreloadintervalinseconds
MIN_DELTA=45
DELTA=MIN_DELTA
MAX_DELTA=300

classStillFrame():
"""Holdsastillframe.
TheimageisstoredasaPNGPIL.ImageandkeptinPNGformat.
Attributes
----------
image:PIL.Image
Astillframe
original:PIL.Image
Originalframewithwchichtheinstanceisinitialized,cachedincaseof
resizingtotheoriginalsize
Methods
-------
bytes:Returntherawbytes
resize:Resizethescreenshot
new_size:Calculatenewaspectratio
"""
def__init__(self,image):
"""ConverttheimagetoPNGandcachetheconvertedoriginal.
Parameters
----------
image:PIL.Image
Imagetostore
"""
self.image=image
self._topng()
self.original=self.image
def_topng(self):
"""ConvertimageformatofframetoPNG.
Returns
-------
StillFrame
FramewithimageinPNGformat
"""
ifnotself.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
returnself
defbytes(self):
"""Returnrawbytesofaframeimage.
Returns
-------
bytes
Bytestreamoftheframeimage
"""
file=BytesIO()
self.image.save(file,'png')
file.seek(0)
returnfile.read()
defnew_size(self):
"""Returnimagesizetoggledbetweenoriginaland16:9.
Returns
-------
2-tuple
Newsize
"""
size=self.image.size
original_size=self.original.size
new_size=(WIDTH,HEIGHT_16_9)ifsize==original_sizeelse(WIDTH,HEIGHT)
returnnew_size
defresize(self,new_size):
"""Resizeframeimage.
Parameters
----------
new_size:2-tuple
Newsize
Returns
-------
StillFrame
Framewithimageresized
"""
ifnot(self.image.size==new_size):
self.image=self.image.resize(new_size)
returnself

defmake_blank_image(size=(WIDTH,HEIGHT)):
"""Createablankimagewithabluebackground.
Parameters
----------
size:2-tuple
Imagesize
Returns
-------
PIL.Image
Blankimage
"""
image=Image.new('RGB',size=size,color='blue')
returnimage

defdownload_image(url):
"""DownloadcurrentNASATVimage.
Parameters
----------
url:str
URLtodownloadtheimagefrom
Returns
-------
PIL.Image
Downloadedimageifnoerrors,otherwiseblankimage
"""
try:
response=requests.get(url,timeout=(0.5,0.5))
ifresponse.status_code==200:
image=Image.open(BytesIO(response.content))
else:
image=make_blank_image()
exceptTimeout:
image=make_blank_image()
returnimage

defrefresh(window,resize=False,feed=FEED_URL):
"""Displaythelateststillframeinwindow.
Parameters
----------
window:sg.Window
Windowtodisplaythestillto
feed:string
FeedURL
Returns
-------
StillFrame
Refreshedscreenshot
"""
still=StillFrame(download_image(feed))
ifresize:
still=change_aspect_ratio(window,still,new_size=(WIDTH,HEIGHT_16_9))
else:
window['-IMAGE-'].update(data=still.bytes())
returnstill

defchange_aspect_ratio(window,still,new_size=(WIDTH,HEIGHT_16_9)):
"""Changetheaspectratioofthestilldisplayedinwindow.
Parameters
----------
window:sg.Window
Windowcontainingthestill
new_size:2-tuple
Newsizeofthestill
Returns
-------
StillFrame
Framecontainingtheresizedimage
"""
resized_still=still.resize(new_size)
window['-IMAGE-'].update(data=resized_still.bytes())
returnresized_still

defsave(still,path):
"""Savestilltoafile.
Parameters
----------
still:StillFrame
Stilltosave
path:string
Filename
Returns
-------
Boolean
Trueiffilesavedwithnoerrors
"""
filename=Path(path)
try:
withopen(filename,'wb')asfile:
file.write(still.bytes())
saved=True
exceptOSError:
saved=False
returnsaved

defnext_timeout(delta):
"""Returnthemomentintimerightnow+deltasecondsfromnow.
Parameters
----------
delta:int
Timeinsecondsuntilthenexttimeout
Returns
-------
datetime.datetime
Momentintimeofthenexttimeout
"""
rightnow=datetime.now()
returnrightnow+timedelta(seconds=delta)

deftimeout_due(next_timeout):
"""ReturnTrueifthenexttimeoutisdue.
Parameters
----------
next_timeout:datetime.datetime
Returns
-------
bool
Trueifthenexttimeoutisdue
"""
rightnow=datetime.now()
returnrightnow>=next_timeout

defvalidate_delta(value):
"""Checkifvalueisanintwithintheproperrangeforatimedelta.
Parameters
----------
value:int
Timeinsecondsuntilthenexttimeout
Returns
-------
int
Timeinsecondsuntilthenexttimeout
bool
Trueiftheargumentisavalidtimedelta
"""
isinteger=False
try:
isinteger=type(int(value))isint
exceptException:
delta=DELTA
delta=int(value)ifisintegerelsedelta
isvalid=MIN_DELTA<=delta<=MAX_DELTA
delta=deltaifisvalidelseDELTA
returndelta,isintegerandisvalid

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

defmain(layout):
"""Runeventloop."""
window=sg.Window('Spacestills',layout,finalize=True)
current_still=refresh(window)
delta=DELTA
next_reload_time=datetime.now()+timedelta(seconds=delta)
whileTrue:
event,values=window.read(timeout=100)
ifeventin(sg.WIN_CLOSED,'Exit'):
break
elif((event=='-RELOAD-')or
(values['-AUTORELOAD-']andtimeout_due(next_reload_time))):
current_still=refresh(window,values['-RESIZE-'])
ifvalues['-AUTORELOAD-']:
next_reload_time=next_timeout(delta)
elifevent=='-RESIZE-':
current_still=change_aspect_ratio(
window,current_still,current_still.new_size())
elifevent=='-SAVE-':
filename=sg.popup_get_file(
'Filename',file_types=[('PNG','*.png')],save_as=True,
title='Saveimage',default_extension='.png')
iffilename:
saved=save(current_still,filename)
ifnotsaved:
sg.popup_ok('Errorwhilesavingfile:',filename,title='Error')
elifevent=='-UPDATE_DELTA-':
#Thecurrentcycleshouldcompleteatthealreadyscheduledtime.So
#don'tupdatenext_reload_timeyetbecauseit'llbetakencareofatthe
#next-AUTORELOAD-or-RELOAD-event.
delta,valid=validate_delta(values['-DELTA-'])
ifnotvalid:
window['-DELTA-'].update(str(DELTA))
window.close()
delwindow

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)文章!

美國穩(wěn)定服務(wù)器

版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實時開通

自選配置、實時開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時在線

客服
熱線

400-630-3752
7*24小時客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部