1.爬取指定关键字图片
'''
爬取指定关键字图片
'''
import re
import requests
import traceback
import os
def dowmloadPic(html, keyword, startNum):
headers = {'user-agent': 'Mozilla/5.0'}
pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
num = len(pic_url)
i = startNum
subroot = root + '/' + word
print('找到关键词:' + keyword + '的图片,现在开始下载图片...')
for each in pic_url:
a = '第' + str(i + 1) + '张图片,图片地址:' + str(each) + '\n'
b = '正在下载' + a
print(b)
path = subroot + '/' + str(i + 1)
try:
if not os.path.exists(subroot):
os.mkdir(subroot)
if not os.path.exists(path):
pic = requests.get(each, headers=headers, timeout=10)
with open(path + '.jpg', 'wb') as f:
f.write(pic.content)
f.close()
except:
continue
i += 1
return i
if __name__ == '__main__':
headers = {'user-agent': 'Mozilla/5.0'}
words = ['人拉灰色行李箱','人背灰色包包','人背灰色双肩包','人背灰色腰包','人拿灰色手提包','人背灰色单肩包','人拿灰色手提袋']
root = './download_images'
for word in words:
root = root + word + '&'
if not os.path.exists(root):
os.mkdir(root)
for word in words:
lastNum = 0
if word.strip() == "exit":
break
pageId = 0
for i in range(15):
url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + "&pn=" + str(
pageId) + "&gsm=?&ct=&ic=0&lm=-1&width=0&height=0"
pageId += 20
html = requests.get(url, headers=headers)
lastNum = dowmloadPic(html.text, word, lastNum, )
类似生成如下文件夹,每个文件夹都会有显示
2、每个文件夹进行合并成一个大的文件夹
import os
import shutil
determination =r'G:\pachong\1white'
if not os.path.exists(determination):
os.makedirs(determination)
path = r'G:\pachong\white'
first_dir = os.listdir(path)
for first in first_dir:
dir = path + '/' + str(first)
imgs = os.listdir(dir)
for img in imgs:
source_img = dir + '/' + str(img)
deter = determination + '/' + str(first) + '_' + '_' + str(img)
shutil.copyfile(source_img, deter)
3.合并后进行筛选、转化三通道RGB
import os.path
from PIL import Image
from PIL import ImageFile
MAGES = True
import cv2
from tqdm import tqdm
from PIL import Image
import os
ImageFile.LOAD_TRUNCATED_IMAGES = True
import glob
path = r"F:\1213bag\all_kind\111colour_all\bag_colour_all_v3\666\white"
files = os.listdir(path)
b = 0
i = 0
a = 0
for file in files:
original = path + os.sep + files[b]
new = path + os.sep + "whiteo" + str(b+1) + ".jpg"
os.rename(original,new)
b +=1
for pic in tqdm(glob.glob("F:/1213bag/all_kind/111colour_all/bag_colour_all_v3/666/white/*.jpg")):
try:
img = Image.open(pic)
if len(img.getbands()) != 3:
img = img.convert("RGB")
pic_new = os.path.join(pic)
img.save(pic_new)
a +=1
i += 1
size = img.size
w = size[0]
h = size[1]
if w<100 or h<100:
img.close()
os.remove(pic)
except:
print('read image failed已删除!')
os.remove(pic)
print('图像image的总数量: ', i)
print('总图像不是RGB的数量:', a)
4、去除重复图像
import shutil
import numpy as np
from PIL import Image
import os
def 比较图片大小(dir_image1, dir_image2):
with open(dir_image1, "rb") as f1:
size1 = len(f1.read())
with open(dir_image2, "rb") as f2:
size2 = len(f2.read())
if (size1 == size2):
result = "大小相同"
else:
result = "大小不同"
return result
def 比较图片尺寸(dir_image1, dir_image2):
image1 = Image.open(dir_image1)
image2 = Image.open(dir_image2)
if (image1.size == image2.size):
result = "尺寸相同"
else:
result = "尺寸不同"
return result
def 比较图片内容(dir_image1, dir_image2):
image1 = np.array(Image.open(dir_image1))
image2 = np.array(Image.open(dir_image2))
if (np.array_equal(image1, image2)):
result = "内容相同"
else:
result = "内容不同"
return result
def 比较两张图片是否相同(dir_image1, dir_image2):
result = "两张图不同"
大小 = 比较图片大小(dir_image1, dir_image2)
if (大小 == "大小相同"):
尺寸 = 比较图片尺寸(dir_image1, dir_image2)
if (尺寸 == "尺寸相同"):
内容 = 比较图片内容(dir_image1, dir_image2)
if (内容 == "内容相同"):
result = "两张图相同"
return result
if __name__ == '__main__':
load_path = r'F:\1213bag\all_kind\111colour_all\bag_colour_all_v3\666\white'
save_path = r'G:\pachong\13411sf'
os.makedirs(save_path, exist_ok=True)
file_map = {}
image_size = 0
for parent, dirnames, filenames in os.walk(load_path):
for filename in filenames:
image_size = os.path.getsize(os.path.join(parent, filename))
file_map.setdefault(os.path.join(parent, filename), image_size)
file_map = sorted(file_map.items(), key=lambda d: d[1], reverse=False)
file_list = []
for filename, image_size in file_map:
file_list.append(filename)
file_repeat = []
for currIndex, filename in enumerate(file_list):
dir_image1 = file_list[currIndex]
dir_image2 = file_list[currIndex + 1]
result = 比较两张图片是否相同(dir_image1, dir_image2)
if (result == "两张图相同"):
file_repeat.append(file_list[currIndex + 1])
print("\n相同的图片:", file_list[currIndex], file_list[currIndex + 1])
else:
print('\n不同的图片:', file_list[currIndex], file_list[currIndex + 1])
currIndex += 1
if currIndex >= len(file_list) - 1:
break
for image in file_repeat:
shutil.move(image, save_path)
print("正在移除重复照片:", image)
处理前会有重复图片和一些小图: 还有一些下载失败无法显示的图,点开无法显示 经过以上一系列处理之后,则如下图所示:
|