爬取百度图片
首先,我们需要获取百度图片的链接,用抓包工具抓到的链接是https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E5%A3%81%E7%BA%B8&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=©right=&word=%E5%A3%81%E7%BA%B8&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&selected_tags=&cg=wallpaper&pn=30&rn=30&gsm=1e&1544511218076=
可以看出有几个参数在变化,word就是你搜索的内容,pn就是图片的个数,gsm就是时间戳,我们经过修改后变为
url = “https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592”
“&is=&fp=result&queryWord=”+ kind +"&cl=2&lm=-1&ie=utf-8&oe=utf-8"
“&adpicid=&st=-1&z=0&ic=0&hd=0&latest=0©right=0&word=" + kind + “”
"&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&selected_tags=&”
"pn=" + str(
num) + “&rn=30&gsm=1e&” + str(int(time.time() * 1000)) + “=”
这样我们就能爬取图片了
def getPicture(html, kind):
global cnt
result = re.findall('https://ss[0-2].bdstatic.com/(.*?).jpg', html)
result = list(set(result))
# if not os.path.exists(path + '/' + kind):
# os.mkdir(path + '/' + kind)
for i in result:
new_url = 'https://ss1.bdstatic.com/' + i + '.jpg'
try:
picture_Name = requests.get(new_url).content
except BaseException:
continue
with open(path + '/' + kind+str(cnt) + '.jpg', 'wb') as f:
f.write(picture_Name)
print("第{}图片加载完成".format(cnt))
cnt += 1
这里就用正则表达式获取图片的链接,然后保存下来就行了
图片处理
爬取到图片之后,我们大概需要1w张照片作为图片数据库,将这些照片存到一个文件夹下面,
要先引入Opencv库然后就要对你所需要进行处理的照片做一些格式的加工
import cv2 as cv
img = cv.imread("zzzz.jpg")
print(img.shape)
res_img = cv.resize(img, (1000, 513))
cv.imwrite("img2.jpg", res_img)
我选取的图片是(1000,513)的大小
为了方面处理,我改为了(1000,500)
第一个参数代表图片的高,第二个代表宽
图片生成
这里要先引入photomosaic库
import photomosaic as pm
image = pm.imread("img2.jpg")
pool = pm.make_pool("D:\图片数据库\集合\*.jpg", sample_size=10000)
mosaic = pm.basic_mosaic(image, pool, (100, 50))
pm.imsave('img4.jpg', mosaic)
pool就是你的图片数据库
mosaic是你每一行和每一列需要的图片数