<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
Python 是一種多用途語言,廣泛用於指令碼編寫。我們可以編寫 Python 指令碼來自動化日常事務。假設我們要下載具有多個搜尋查詢的谷歌圖片。我們可以自動化該過程,而不是手動進行。
如何安裝所需的模組:
pip install google_images_download
讓我們看看如何編寫 Python 指令碼以使用 Python google_images_download 模組下載 Google 影象。
# importing google_images_download module from google_images_download import google_images_download # creating object response = google_images_download.googleimagesdownload() search_queries = [ 'The smartphone also features an in display fingerprint sensor.', 'The pop up selfie camera is placed aligning with the rear cameras.', '''In terms of storage Vivo V15 Pro could offer up to 6GB of RAM and 128GB of onboard storage.''', 'The smartphone could be fuelled by a 3 700mAh battery.', ] def downloadimages(query): # keywords is the search query # format is the image file format # limit is the number of images to be downloaded # print urs is to print the image file url # size is the image size which can # be specified manually ("large, medium, icon") # aspect ratio denotes the height width ratio # of images to download. ("tall, square, wide, panoramic") arguments = {"keywords": query, "format": "jpg", "limit":4, "print_urls":True, "size": "medium", "aspect_ratio":"panoramic"} try: response.download(arguments) # Handling File NotFound Error except FileNotFoundError: arguments = {"keywords": query, "format": "jpg", "limit":4, "print_urls":True, "size": "medium"} # Providing arguments for the searched query try: # Downloading the photos based # on the given arguments response.download(arguments) except: pass # Driver Code for query in search_queries: downloadimages(query) print()
輸出
注意:由於下載錯誤,部分圖片無法開啟。
import re import requests from bs4 import BeautifulSoup from urllib.parse import urlparse import os f = open("images_flowers.txt", "w") res=[] def download_google(url): #url = 'https://www.google.com/search?q=flowers&sxsrf=ALeKk00uvzQYZFJo03cukIcMS-pcmmbuRQ:1589501547816&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjEm4LZyrTpAhWjhHIEHewPD1MQ_AUoAXoECBAQAw&biw=1440&bih=740' page = requests.get(url).text soup = BeautifulSoup(page, 'html.parser') for raw_img in soup.find_all('img'): link = raw_img.get('src') res.append(link) if link: f.write(link +"n") download_google('https://www.google.com/search?q=flowers&sxsrf=ALeKk00uvzQYZFJo03cukIcMS-pcmmbuRQ:1589501547816&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjEm4LZyrTpAhWjhHIEHewPD1MQ_AUoAXoECBAQAw&biw=1440&bih=740') f.close()
感謝 Adrian Rosebrock 編寫此程式碼並將其公開。
# USAGE # python download_images.py --urls urls.txt --output images/santa # import the necessary packages from imutils import paths import argparse import requests import cv2 import os # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-u", "--urls", required=True, help="path to file containing image URLs") ap.add_argument("-o", "--output", required=True, help="path to output directory of images") args = vars(ap.parse_args()) # grab the list of URLs from the input file, then initialize the # total number of images downloaded thus far rows = open(args["urls"]).read().strip().split("n") total = 0 # loop the URLs for url in rows: try: # try to download the image r = requests.get(url, timeout=60) # save the image to disk p = os.path.sep.join([args["output"], "{}.jpg".format( str(total).zfill(8))]) f = open(p, "wb") f.write(r.content) f.close() # update the counter print("[INFO] downloaded: {}".format(p)) total += 1 # handle if any exceptions are thrown during the download process except: print("[INFO] error downloading {}...skipping".format(p)) # loop over the image paths we just downloaded for imagePath in paths.list_images(args["output"]): # initialize if the image should be deleted or not delete = False # try to load the image try: image = cv2.imread(imagePath) # if the image is `None` then we could not properly load it # from disk, so delete it if image is None: print("None") delete = True # if OpenCV cannot load the image then the image is likely # corrupt so we should delete it except: print("Except") delete = True # check to see if the image should be deleted if delete: print("[INFO] deleting {}".format(imagePath)) os.remove(imagePath)
如何安裝所需的模組:
pip install pytube3
import cv2 from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import pandas as pd import warnings from pytube import YouTube warnings.filterwarnings('ignore') video = YouTube('https://www.youtube.com/watch?v=GTkU4qj6v7g') # print(video.streams.all()) print(video.streams.filter(file_extension = "mp4").all()) # [<Stream: itag="18" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.42001E" acodec="mp4a.40.2" progressive="True" type="video">, # <Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2" progressive="True" type="video">, # <Stream: itag="137" mime_type="video/mp4" res="1080p" fps="30fps" vcodec="avc1.64001f" progressive="False" type="video">, # <Stream: itag="136" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.4d401e" progressive="False" type="video">, # <Stream: itag="135" mime_type="video/mp4" res="480p" fps="30fps" vcodec="avc1.4d4015" progressive="False" type="video">, # <Stream: itag="134" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.4d400d" progressive="False" type="video">, # <Stream: itag="133" mime_type="video/mp4" res="240p" fps="30fps" vcodec="avc1.4d400c" progressive="False" type="video">, # <Stream: itag="160" mime_type="video/mp4" res="144p" fps="30fps" vcodec="avc1.4d400b" progressive="False" type="video">, # <Stream: itag="140" mime_type="audio/mp4" abr="128kbps" acodec="mp4a.40.2" progressive="False" type="audio">] # 為要下載的視訊的解析度使用適當的 itag。如果您需要高解析度視訊下載, # 請在以下步驟中選擇最高解析度的 itag 進行下載 print(video.streams.get_by_itag(137).download()) # '/Users/sapnasharma/Documents/github/video_clips/Akshay Kumars Fitness Mantras for a Fit India GOQii Play Exclusive.mp4' video_path = video.title print(video_path) # "Akshay Kumar's Fitness Mantras for a Fit India | GOQii Play Exclusive" # 視訊標題在名稱之間新增了一個管道,因此實際名稱已損壞。我稍後會修復這個錯誤, # 現在我們可以直接貼上視訊的名字來達到我們的目的。 video_path = "Akshay Kumars Fitness Mantras for a Fit India GOQii Play Exclusive.mp4" # Video Capture Using OpenCV cap = cv2.VideoCapture(video_path) frame_cnt = int(cap.get(cv2.cv2.CAP_PROP_FRAME_COUNT)) fps = cap.get(cv2.CAP_PROP_FPS) print('Frames in video: ', frame_cnt) print(f"Frames per sec: {fps}") # Frames in video: 34249 # Frames per sec: 25.0 # (1)要獲取整個視訊的幀,請使用下面的程式碼塊。 # Use this for accessing the entire video index = 1 for x in range(frame_cnt): ret, frame = cap.read() if not ret: break # Get frame timestamp frame_timestamp = cap.get(cv2.CAP_PROP_POS_MSEC) # fetch frame every sec if frame_timestamp >= (index * 1000.0): # change the value from 1000 to anyother value if not needed per second index = index + 2 # decides the freq. of frames to be saved print(f"++ {index}") cv2.imwrite(f"images/cv_{index}.png", frame) if cv2.waitKey(20) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() # (2)要獲取特定持續時間之間的幀,請使用以下程式碼塊。 # Use this in case frames are to be fetched within a certain time frame # frame_timestamp will be calculated as fps*time*1000 and set the starting index accordingly index = 1560 for x in range(frame_cnt): ret, frame = cap.read() if not ret: break # Get frame timestamp frame_timestamp = cap.get(cv2.CAP_PROP_POS_MSEC) if frame_timestamp >= 1560000.0 and frame_timestamp <= 1800000.0 : # fetch frame every sec if frame_timestamp >= (index * 1000.0): index = index + 4 # decides the freq. of frames to be saved print(f"++ {index}") cv2.imwrite(f"images/cv_{index}.png", frame) if cv2.waitKey(20) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
以上就是Python獲取網路圖片和視訊的範例程式碼的詳細內容,更多關於Python獲取圖片 視訊的資料請關注it145.com其它相關文章!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45