如何使用包含在文本文件中的URL下载图像?因为我有一堆文本文件包含图像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
这对于工作,请尝试更换替代的.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)