百度批量下載圖片,縮放圖片為512×512,不改變圖片原圖
所用關(guān)鍵工具:
Open Web Scraper瀏覽器插件
懂點(diǎn)python
步驟:
百度搜索“貓”
鼠標(biāo)右鍵,選擇檢查,或按F12
選擇插件Web Scraper瀏覽器插件
選擇Create new sitemap
復(fù)制搜索出來(lái)圖片的網(wǎng)址,Sitempa name起個(gè)名稱,Start URL搜索的網(wǎng)址地址復(fù)制粘貼
選擇Add new selector
ID名稱隨便起,Type選擇Image,Multiple勾選上(不勾上后期只能看到1個(gè)數(shù)據(jù)),然后點(diǎn)Select
出現(xiàn)這個(gè)按住Shift,然后鼠標(biāo)選擇圖片,系統(tǒng)會(huì)自動(dòng)選擇相同的元素,選中會(huì)變紅。選完后按Done selecting。
點(diǎn)擊Element preview,會(huì)出現(xiàn)Selected element count:11,告訴你選擇了多少個(gè)圖片,然后按Data preview,
就會(huì)看到地址了,不過(guò)是webp格式,全選復(fù)制到excel表格,用下載工具直接無(wú)法下載。要把他們的后綴批量加上 ?.webp才能下載
下面就用python程序進(jìn)行下載和保存。
import pandas as pd
import requests
保存到excel表格進(jìn)行讀取
df = pd.read_excel('image_temp.xlsx')
n=0
批量保存
ps = df.iloc[:, 0]
for x in ps:
? ?response = requests.get(x)
? ?n+=1
? ?with open(f'./image_in/'+str(n)+'.webp', 'wb') as f:
? ? ? ? ? ?f.write(response.content)
此程序AI直接給的,運(yùn)行無(wú)報(bào)錯(cuò)一次通過(guò)
import os
from PIL import Image
從此文件夾讀取圖片,自己改圖片文件夾所在位置
directory = r'./image_in'
縮放圖片,縮放至512×512的尺寸,判斷圖片的長(zhǎng)寬,大的就按512,小的不夠部分用白色填充。
for filename in os.listdir(directory):
? ?if filename.endswith('.jpg') or filename.endswith('.png'):
? ? ? ?# Open the image file
? ? ? ?with Image.open(os.path.join(directory, filename)) as img:
? ? ? ? ? ?# Calculate the new size while maintaining the aspect ratio
? ? ? ? ? ?width, height = img.size
? ? ? ? ? ?aspect_ratio = width / height
? ? ? ? ? ?new_size = (512, 512)
# Determine which dimension to scale based on the aspect ratio
? ? ? ? ? ?if aspect_ratio >= 1:
? ? ? ? ? ? ? ?new_width = 512
? ? ? ? ? ? ? ?new_height = int(new_width / aspect_ratio)
? ? ? ? ? ?else:
? ? ? ? ? ? ? ?new_height = 512
? ? ? ? ? ? ? ?new_width = int(new_height * aspect_ratio)
# Create a new image with the desired size and fill color
? ? ? ? ? ?resized_img = Image.new('RGB', new_size, (255, 255, 255))
# Paste the resized image onto the new image with centered alignment
? ? ? ? ? ?x_offset = int((new_size[0] - new_width) / 2)
? ? ? ? ? ?y_offset = int((new_size[1] - new_height) / 2)
? ? ? ? ? ?resized_img.paste(img.resize((new_width, new_height), resample=Image.LANCZOS), (x_offset, y_offset))
# Save the resized image with the same filename and extension
? ? ? ? ? ?resized_filename = os.path.splitext(filename)[0] + '_resized' + os.path.splitext(filename)[1]
? ? ? ? ? ?resized_img.save(os.path.join("./image_out", resized_filename))