通过链接请求下载图像(以OCR-VQA数据集为例子)

多线程下载链接请求数据

官方代码太慢了

多线程下载

import os
import json
import urllib.request as ureq
import concurrent.futures
import threading

# Set the file paths for your Google Drive
dataset_path = '/content/drive/MyDrive/ocr_vqa/dataset.json'
images_path = '/content/drive/MyDrive/ocr_vqa/images'
download = 1  # Set to 0 if images are already downloaded

# Load dataset json file
with open(dataset_path, 'r') as fp:
    data = json.load(fp)

# Initialize a counter and a lock for thread-safe counting
downloaded_count = 0
count_lock = threading.Lock()

# Function to download an image
def download_image(k):
    global downloaded_count
    imageURL = data[k]['imageURL']
    ext = os.path.splitext(imageURL)[1]
    outputFile = os.path.join(images_path, f'{k}{ext}')

    # Only download the image if it doesn't exist
    if not os.path.exists(outputFile):
        try:
            ureq.urlretrieve(imageURL, outputFile)

            with count_lock:
                downloaded_count += 1
                if downloaded_count % 100 == 0:
                    print(f'{downloaded_count} images downloaded.')
        except urllib.error.URLError as e:
            print(f'Error downloading {outputFile}: {e}')

# Download images using multiple threads
if download == 1:
    if not os.path.exists(images_path):
        os.makedirs(images_path)

    # Create a thread pool and download the images in parallel
    with concurrent.futures.ThreadPoolExecutor() as executor:
        executor.map(download_image, data.keys())

原代码下载800分钟左右,多线程50分钟左右搞定
请添加图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值