几行代码帮肖战哥哥美颜

我爱死肖战哥哥了,但苦于网上一张一张下载他的照片实在是太慢了,于是我准备用刚学的python来直接在网上爬取一下哥哥的图片:

import requests
import re
from urllib.request import urlretrieve

link = "https://image.baidu.com/search/index?isource=infinity&iname=baidu&tn=baiduimage&word="
pictures = []
urls = []
pattern = re.compile('"thumbURL":"(.+?.jpg)"')
hd = {"user-agent": "Mozilla/5.0"}
path = r'F:\XZ'  # 存储路径


def getImg(urls):
    for url in urls:
        obj = requests.get(url, headers=hd, timeout=1)
        pictures.extend(pattern.findall(obj.text))


def downloadpic(pictures):
    count = 0
    for picture in pictures:
        count += 1
        try:
            urlretrieve(picture, path + "/" + "ugly %d" % count + ".jpg")
        except OSError as ie:
            print("第%d张图片下载失败" % count)
        else:
            print("第%d张图片已下载" % count)


keywords = ["肖战", "肖战1", "肖战2", "肖战3", "肖战4"]
for keyword in keywords:
    urls.append(link + keyword)
getImg(urls)
downloadpic(pictures)

好,现在图片我们已经准备完毕,下一步我们就要开始对哥哥的图片进行美化:

我们先拿其中一张图片来试一下效果:

原图:

ugly 1

from PIL import Image

im = Image.open(r"F:\XZ\ugly 1.jpg")
r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))
im.show()

效果:tmpkdo9kcda

有没有感觉哥哥变帅了很多呢?我们继续。

from PIL import ImageFilter, Image

out = im.filter(ImageFilter.FIND_EDGES)
out.show()

效果:

tmp1qhc55ch

嗯,这张也帅爆了!继续

from PIL import ImageFilter, Image

im = Image.open(r"F:\XZ\ugly 1.jpg")
out = im.filter(ImageFilter.EMBOSS)
k = out.point(lambda i: i*2)
k.show()

效果:

tmp1ldd9kru

不知道小伙伴们觉得哪张图片肖战哥哥最帅呢?

好了,我们已经知道如何处理一张图片,接下来我们需要处理我们刚刚爬取的所有图片:

import os
from PIL import Image, ImageFilter
path = r"F:\XZ"
count = 0
for filename in os.listdir(path):
    print(filename)
    count += 1
    if filename.endswith(".jpg"):
        print(path + "/" + filename)
        im = Image.open(path + "/" + filename)
        out = im.filter(ImageFilter.FIND_EDGES)
        try:
            out.save(path + "/" + "moreugly %d" % count + ".jpg")
        except:
            print("第%d张图片处理失败" % count)
        else:
            print("第%d张图片已处理完" % count)

教程到此结束,和我同样喜欢肖战哥哥的小飞侠们记得转发哦,让更多的人知道我们肖战哥哥的帅气!

如果我的教程对你有帮助的话,记得点赞、关注。

我的公众号:

我会在公众号上跟你们分享更多的有趣的知识。

Learn and progress together with me!

猜你喜欢

转载自blog.csdn.net/qq_45359344/article/details/107027911