如何使用文本文件中包含的url下载图像? 因为我有一堆包含图片网址的文本文件。 我设法用我的代码下载了它,但是以某种方式访问某些URL时冻结了。
这是我的代码:
import urllib.request
import cv2
import numpy as np
import os
from pathlib import Path
_directory = Path('VGG').glob('*')
def store_raw_images(file):
pathname, filename = os.path.split(file)
name = filename[:-4]
print('===Gathering '+str(name)+"===")
face_link = open(str(file))
# face_image_urls = urllib.request.urlopen(face_link).read().decode()
# print('path', pathname)
# print('filename', filename)
# print(name)
# print(extension)
if not os.path.exists('VGG/'+str(name)):
os.makedirs('VGG/'+str(name))
for i in face_link:
try:
url = i.split(" ")[1]
index = i.split(" ")[0]
print(str(pic_num)+" "+str(i))
urllib.request.urlretrieve(url, "VGG/"+str(name)+"/"+str(index)+".jpg")
img = cv2.imread("VGG/"+str(name)+"/"+str(pic_num)+".jpg")
# img = cv2.imread("image/"+str(pic_num)+".jpg",cv2.IMREAD_GRAYSCALE)
# should be larger than samples / pos pic (so we can place our image on it)
# resized_image = cv2.resize(img, (100, 100))
# cv2.imwrite("image/"+str(pic_num)+".jpg",resized_image)
cv2.imwrite("VGG/"+str(name)+"/"+str(pic_num)+".jpg",img)
pic_num += 1
if (pic_num == 631):
continue
except Exception as e:
print(str(e))
for file_name in _directory:
store_raw_images(file_name)
此文件链接网址:https://ufile.io/pug4w
答案 0 :(得分:-1)
这是适用于.csv文件的文件,请尝试替换txt而不是.csv文件。
import csv
import requests
with open('fotos.csv') as csvfile:
csvrows = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in csvrows:
filename = row[0]
url = row[1]
print(url)
result = requests.get(url, stream=True)
if result.status_code == 200:
image = result.raw.read()
open(filename,"wb").write(image)