coisini9293's picture
Upload 1809 files
b2f66f0 verified
Raw History Blame Contribute Delete
25.4 kB
"""
数据集下载脚本
从国内网站爬取并下载各类别行人图片
包含图片损坏检查、大小统一处理等功能
"""
import os
import requests
import json
import time
import random
from pathlib import Path
from tqdm import tqdm
from urllib.parse import quote
import re
from PIL import Image
import shutil
import hashlib
class ImageDownloader:
"""图片下载器,从国内网站收集数据集"""
def __init__(self, output_dir="data/train", max_images_per_category=500, target_size=(224, 224)):
"""
初始化下载器
Args:
output_dir: 输出目录路径
max_images_per_category: 每个类别最大下载数量
target_size: 目标图片尺寸(宽,高)
"""
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.max_images_per_category = max_images_per_category
self.target_size = target_size
# 定义搜索关键词(中文,适合国内网站)
self.keywords = {
'normal': ['普通行人', '成年人过马路', '行人过街', '正常行人'],
'elderly': ['老人过马路', '老年人过街', '老人行走', '老年行人'],
'wheelchair': ['轮椅过马路', '残疾人过街', '轮椅使用者', '残疾人过马路'],
'stroller': ['推婴儿车过马路', '婴儿车过街', '推婴儿车', '带小孩过马路']
}
# User-Agent,模拟浏览器
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
# 会话对象,保持连接
self.session = requests.Session()
self.session.headers.update(self.headers)
# 存储已下载图片的hash值(用于去重)
self.image_hashes = set()
def calculate_image_hash(self, image_path):
"""
计算图片的hash值(用于去重)
Args:
image_path: 图片路径
Returns:
str: 图片hash值,如果失败返回None
"""
try:
img = Image.open(image_path)
# 转换为RGB并调整到固定尺寸,然后计算hash
img = img.convert('RGB')
img_resized = img.resize((256, 256), Image.Resampling.LANCZOS)
# 计算hash值
hash_md5 = hashlib.md5()
hash_md5.update(img_resized.tobytes())
return hash_md5.hexdigest()
except Exception as e:
return None
def is_duplicate_image(self, image_path):
"""
检查图片是否重复
Args:
image_path: 图片路径
Returns:
bool: 是否重复
"""
img_hash = self.calculate_image_hash(image_path)
if img_hash is None:
return True # 无法计算hash,视为无效
if img_hash in self.image_hashes:
return True # 重复
self.image_hashes.add(img_hash)
return False
def load_existing_hashes(self, category_dir):
"""
加载已有图片的hash值
Args:
category_dir: 类别目录路径
"""
category_dir = Path(category_dir)
if not category_dir.exists():
return
image_files = list(category_dir.glob("*.png")) + \
list(category_dir.glob("*.jpg")) + \
list(category_dir.glob("*.jpeg"))
for img_path in image_files:
img_hash = self.calculate_image_hash(img_path)
if img_hash:
self.image_hashes.add(img_hash)
def check_image_valid(self, image_path, min_size=(200, 200)):
"""
检查图片是否损坏且尺寸符合要求
Args:
image_path: 图片路径
min_size: 最小尺寸(宽,高)
Returns:
bool: 图片是否有效
"""
try:
img = Image.open(image_path)
img.verify() # 验证图片完整性
# 重新打开图片(verify后需要重新打开才能使用)
img = Image.open(image_path)
img.load() # 加载图片数据
# 检查图片尺寸是否合理(排除小图标)
width, height = img.size
if width < min_size[0] or height < min_size[1]:
return False
# 检查宽高比是否合理(排除极端细长的图标)
aspect_ratio = max(width, height) / min(width, height)
if aspect_ratio > 5: # 宽高比超过5:1可能是图标
return False
return True
except Exception as e:
return False
def clean_corrupted_images(self, category_dir):
"""
清理损坏的图片、小图标和重复图片
Args:
category_dir: 类别目录路径
Returns:
int: 删除的图片数量
"""
category_dir = Path(category_dir)
if not category_dir.exists():
return 0
deleted_count = 0
seen_hashes = set()
image_files = list(category_dir.glob("*.jpg")) + \
list(category_dir.glob("*.png")) + \
list(category_dir.glob("*.jpeg")) + \
list(category_dir.glob("*.gif"))
for img_path in image_files:
should_delete = False
# 检查是否损坏或尺寸不符合要求
if not self.check_image_valid(img_path, min_size=(200, 200)):
should_delete = True
else:
# 检查是否重复
img_hash = self.calculate_image_hash(img_path)
if img_hash is None:
should_delete = True
elif img_hash in seen_hashes:
should_delete = True # 重复图片
else:
seen_hashes.add(img_hash)
if should_delete:
try:
img_path.unlink()
deleted_count += 1
except Exception as e:
pass
return deleted_count
def resize_image(self, image_path, target_size):
"""
调整图片大小(拉伸方法)并统一转换为PNG格式
Args:
image_path: 图片路径
target_size: 目标尺寸(宽,高)
"""
try:
img = Image.open(image_path)
# 转换为RGB(处理RGBA等格式)
if img.mode != 'RGB':
img = img.convert('RGB')
# 拉伸到目标尺寸
img_resized = img.resize(target_size, Image.Resampling.LANCZOS)
# 统一保存为PNG格式
png_path = image_path.with_suffix('.png')
img_resized.save(png_path, format='PNG', optimize=True)
# 如果原文件不是PNG,删除原文件
if image_path != png_path:
try:
image_path.unlink()
except:
pass
return True
except Exception as e:
return False
def batch_resize_images(self, category_dir):
"""
批量调整图片大小
Args:
category_dir: 类别目录路径
Returns:
int: 成功处理的图片数量
"""
category_dir = Path(category_dir)
if not category_dir.exists():
return 0
image_files = list(category_dir.glob("*.jpg")) + \
list(category_dir.glob("*.png")) + \
list(category_dir.glob("*.jpeg"))
success_count = 0
for img_path in tqdm(image_files, desc=f"调整 {category_dir.name} 图片大小"):
if self.resize_image(img_path, self.target_size):
success_count += 1
return success_count
def split_train_test(self, train_ratio=0.8):
"""
划分训练集和测试集
Args:
train_ratio: 训练集比例(默认0.8,即80%训练,20%测试)
"""
import random
import shutil
train_dir = self.output_dir
test_dir = train_dir.parent / "test"
test_dir.mkdir(exist_ok=True)
for category in self.keywords.keys():
train_category_dir = train_dir / category
test_category_dir = test_dir / category
if not train_category_dir.exists():
continue
# 获取所有图片文件
image_files = list(train_category_dir.glob("*.png"))
if len(image_files) == 0:
continue
# 随机打乱
random.shuffle(image_files)
# 计算划分点
split_point = int(len(image_files) * train_ratio)
train_files = image_files[:split_point]
test_files = image_files[split_point:]
# 创建测试集目录
test_category_dir.mkdir(exist_ok=True)
# 移动文件到测试集
moved_count = 0
for img_file in test_files:
try:
dest_file = test_category_dir / img_file.name
shutil.move(str(img_file), str(dest_file))
moved_count += 1
except Exception as e:
print(f" 移动文件失败 {img_file}: {e}")
print(f" {category}: 训练集 {len(train_files)} 张, 测试集 {moved_count} 张")
def download_image(self, url, save_path):
"""
下载单张图片,转换为PNG格式,并检查是否损坏和重复
Args:
url: 图片URL
save_path: 保存路径(会自动转换为.png)
Returns:
bool: 是否下载成功且图片有效且不重复
"""
try:
# 清理URL
url = url.strip()
if not url:
return False
# 设置更长的超时时间
response = self.session.get(url, timeout=15, stream=True, allow_redirects=True)
response.raise_for_status()
# 检查内容类型
content_type = response.headers.get('content-type', '').lower()
if 'image' not in content_type and not url.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp')):
return False
# 临时保存文件(保持原格式)
temp_path = save_path.with_suffix('.tmp')
with open(temp_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
# 验证文件大小(至少2KB,避免下载到错误页面)
if not temp_path.exists() or temp_path.stat().st_size < 2048:
if temp_path.exists():
temp_path.unlink()
return False
# 检查图片是否损坏且尺寸符合要求(排除小图标)
if not self.check_image_valid(temp_path, min_size=(200, 200)):
if temp_path.exists():
temp_path.unlink()
return False
# 转换为PNG格式
try:
img = Image.open(temp_path)
# 转换为RGB(处理RGBA等格式)
if img.mode != 'RGB':
img = img.convert('RGB')
# 保存为PNG格式
png_path = save_path.with_suffix('.png')
img.save(png_path, format='PNG', optimize=True)
# 删除临时文件
if temp_path.exists():
temp_path.unlink()
# 检查是否重复
if self.is_duplicate_image(png_path):
# 重复图片,删除
if png_path.exists():
png_path.unlink()
return False
return True
except Exception as e:
if temp_path.exists():
temp_path.unlink()
if save_path.with_suffix('.png').exists():
save_path.with_suffix('.png').unlink()
return False
except Exception as e:
if save_path.exists():
try:
save_path.unlink()
except:
pass
if save_path.with_suffix('.png').exists():
try:
save_path.with_suffix('.png').unlink()
except:
pass
return False
def download_from_baidu(self, keyword, category, max_images=500):
"""
从百度图片搜索下载图片
Args:
keyword: 搜索关键词
category: 图片类别
max_images: 最大下载数量
"""
category_dir = self.output_dir / category
category_dir.mkdir(exist_ok=True)
# 先清理损坏的图片和重复图片
print(f" 清理损坏和重复的图片...")
deleted = self.clean_corrupted_images(category_dir)
if deleted > 0:
print(f" 已删除 {deleted} 张图片(损坏或重复)")
# 加载已有图片的hash值(用于去重)
self.load_existing_hashes(category_dir)
# 检查已有图片数量(只统计PNG格式)
existing_images = len(list(category_dir.glob("*.png")))
print(f" 当前已有 {existing_images} 张有效图片(已去重)")
print(f" 已记录 {len(self.image_hashes)} 个图片hash值")
if existing_images >= max_images:
print(f"类别 {category} 已有 {existing_images} 张图片,跳过下载")
return existing_images
print(f"\n从百度图片搜索: {keyword} (类别: {category})")
print(f"目标下载数量: {max_images - existing_images} 张")
downloaded = existing_images
max_pages = 10 # 最多搜索10页
for page in range(max_pages):
if downloaded >= max_images:
break
try:
# 百度图片搜索URL
search_url = "https://image.baidu.com/search/index"
params = {
'tn': 'baiduimage',
'word': keyword,
'pn': page * 30, # 每页30张
'ie': 'utf-8',
'oe': 'utf-8',
'gsm': '1e',
}
response = self.session.get(search_url, params=params, timeout=15)
response.raise_for_status()
# 从HTML中提取图片URL
html = response.text
# 多种模式提取图片URL
image_urls = []
# 模式1: objURL字段(原图,优先使用)
pattern1 = r'"objURL":"([^"]+)"'
urls1 = re.findall(pattern1, html)
image_urls.extend(urls1)
# 模式2: 直接搜索图片URL模式(作为备选)
pattern2 = r'https?://[^\s"<>]+\.(?:jpg|jpeg|png|gif|webp)'
urls2 = re.findall(pattern2, html, re.IGNORECASE)
image_urls.extend(urls2)
# 去重
image_urls = list(set(image_urls))
# 过滤掉小图标、logo、缩略图等
exclude_keywords = [
'icon', 'logo', 'avatar', 'thumb', 'thumbnail',
'small', 'mini', 'tiny', 'btn', 'button',
'baidu.com/img/', '/icon/', '/logo/', '/thumb/',
'favicon', 'sprite', 'emoji', 'smiley'
]
# 过滤URL
filtered_urls = []
for url in image_urls:
url_lower = url.lower()
# 必须是图片格式
if not any(ext in url_lower for ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp']):
continue
# 排除包含关键词的URL
if any(keyword in url_lower for keyword in exclude_keywords):
continue
# 排除尺寸参数(可能是缩略图)
if any(param in url_lower for param in ['_thumb', '_small', '_mini', 'thumb_', 'small_']):
continue
# 排除百度自己的图片
if 'baidu.com/img/' in url_lower or 'baidu.com/static/' in url_lower:
continue
filtered_urls.append(url)
image_urls = filtered_urls
if not image_urls:
print(f" 第 {page + 1} 页未找到图片,尝试下一页...")
time.sleep(random.uniform(2, 4))
continue
print(f" 第 {page + 1} 页找到 {len(image_urls)} 个图片URL")
# 下载图片
success_count = 0
for idx, img_url in enumerate(image_urls):
if downloaded >= max_images:
break
# 清理和解码URL
img_url = img_url.replace('\\u002F', '/').replace('\\/', '/')
img_url = img_url.replace('\\"', '"')
# 跳过无效URL
if not img_url.startswith('http'):
continue
# 生成文件名(统一使用PNG格式)
filename = f"{category}_{downloaded + 1:04d}.png"
save_path = category_dir / filename
# 跳过已存在的文件
if save_path.exists():
continue
# 下载图片(会自动检查是否损坏)
if self.download_image(img_url, save_path):
downloaded += 1
success_count += 1
if downloaded % 20 == 0:
print(f" 已下载 {downloaded}/{max_images} 张有效图片...")
# 延迟,避免请求过快
time.sleep(random.uniform(0.5, 1.2))
if success_count == 0:
print(f" 第 {page + 1} 页下载失败,可能遇到反爬虫,等待后继续...")
time.sleep(5)
continue
# 页面间延迟
time.sleep(random.uniform(2, 4))
except Exception as e:
print(f" 下载第 {page + 1} 页时出错: {e}")
time.sleep(5) # 出错后等待更长时间
continue
print(f"类别 {category} 完成,共下载 {downloaded} 张有效图片")
return downloaded
def download_all(self):
"""
下载所有类别的图片
"""
print("=" * 60)
print("智能人行横道系统 - 数据集下载工具")
print("=" * 60)
print(f"目标目录: {self.output_dir}")
print(f"每个类别最大下载数量: {self.max_images_per_category}")
print(f"目标图片尺寸: {self.target_size}")
print("=" * 60)
# 第一步:清理所有损坏的图片并统计
print("\n第一步:清理损坏的图片...")
total_deleted = 0
for category in self.keywords.keys():
category_dir = self.output_dir / category
if category_dir.exists():
deleted = self.clean_corrupted_images(category_dir)
total_deleted += deleted
if deleted > 0:
print(f" {category}: 删除 {deleted} 张损坏图片")
if total_deleted > 0:
print(f"\n共删除 {total_deleted} 张损坏图片")
else:
print("未发现损坏图片")
# 第二步:统计当前图片数量(只统计PNG格式)
print("\n第二步:统计当前图片数量...")
category_counts = {}
for category in self.keywords.keys():
category_dir = self.output_dir / category
if category_dir.exists():
count = len(list(category_dir.glob("*.png"))) # 只统计PNG格式
category_counts[category] = count
print(f" {category}: {count} 张PNG图片")
else:
category_counts[category] = 0
print(f" {category}: 0 张")
# 第三步:下载图片补全到目标数量
print("\n第三步:下载图片补全到目标数量...")
total_downloaded = 0
for category, keywords in self.keywords.items():
print(f"\n处理类别: {category}")
print(f"搜索关键词: {', '.join(keywords)}")
# 使用第一个关键词进行搜索
keyword = keywords[0]
downloaded = self.download_from_baidu(keyword, category, self.max_images_per_category)
total_downloaded += downloaded
# 第四步:统一调整所有图片大小
print("\n" + "=" * 60)
print("第四步:统一调整所有图片大小...")
print("=" * 60)
for category in self.keywords.keys():
category_dir = self.output_dir / category
if category_dir.exists():
count = self.batch_resize_images(category_dir)
print(f" {category}: 已处理 {count} 张图片")
# 第五步:划分训练集和测试集
print("\n" + "=" * 60)
print("第五步:划分训练集和测试集...")
print("=" * 60)
self.split_train_test(train_ratio=0.8)
# 最终统计
print("\n" + "=" * 60)
print("下载和处理完成!")
print("=" * 60)
print("\n训练集统计:")
train_dir = self.output_dir
for category in self.keywords.keys():
category_dir = train_dir / category
if category_dir.exists():
count = len(list(category_dir.glob("*.png")))
print(f" {category}: {count} 张PNG图片")
print("\n测试集统计:")
test_dir = self.output_dir.parent / "test"
for category in self.keywords.keys():
category_dir = test_dir / category
if category_dir.exists():
count = len(list(category_dir.glob("*.png")))
print(f" {category}: {count} 张PNG图片")
print(f"\n图片保存在: {self.output_dir} (训练集) 和 {test_dir} (测试集)")
print("=" * 60)
def main():
"""主函数"""
import argparse
parser = argparse.ArgumentParser(description='下载行人图片数据集')
parser.add_argument('--output', type=str, default='data/train',
help='输出目录(默认: data/train)')
parser.add_argument('--max-images', type=int, default=500,
help='每个类别最大下载数量(默认: 500)')
parser.add_argument('--target-size', type=int, nargs=2, default=[224, 224],
metavar=('WIDTH', 'HEIGHT'),
help='目标图片尺寸(默认: 224 224)')
args = parser.parse_args()
downloader = ImageDownloader(
output_dir=args.output,
max_images_per_category=args.max_images,
target_size=tuple(args.target_size)
)
downloader.download_all()
if __name__ == "__main__":
main()