Python使用5行代码批量做小姐姐的素描图

目录
  • 1. 流程分析
  • 2. 具体实现
  • 3. 百度图片爬虫+生成素描图

我给大家带来的是 50行代码,生成一张素描图。让自己也是一个素描“大师”。那废话不多说,我们直接先来看看效果吧。

上图的右边就是我们的效果,那具体有哪些步骤呢?

1. 流程分析

对于上面的流程来说是非常简单的,接下来我们来看看具体的实现。

2. 具体实现

安装所需要的库:

pip install opencv-python

导入所需要的库:

import cv2

编写主体代码也是非常的简单的,代码如下:

import cv2
SRC = 'images/image_1.jpg'

image_rgb = cv2.imread(SRC)
image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY)
image_blur = cv2.GaussianBlur(image_gray, ksize=(21, 21), sigmaX=0, sigmaY=0)
image_blend = cv2.divide(image_gray, image_blur, scale=255)
cv2.imwrite('result.jpg', image_blend)

那上面的代码其实并不难,那接下来为了让小伙伴们能更好的理解,我编写了如下代码:

"""
project = 'Code', file_name = 'study.py', author = 'AI悦创'
time = '2020/5/19 8:35', product_name = PyCharm, 公众号:AI悦创
code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
"""
import cv2

# 原图路径
SRC = 'images/image_1.jpg'

# 读取图片
image_rgb = cv2.imread(SRC)
# cv2.imshow('rgb', image_rgb) # 原图
# cv2.waitKey(0)
# exit()
image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY)
# cv2.imshow('gray', image_gray) # 灰度图
# cv2.waitKey(0)
# exit()
image_bulr = cv2.GaussianBlur(image_gray, ksize=(21, 21), sigmaX=0, sigmaY=0)
cv2.imshow('image_blur', image_bulr) # 高斯虚化
cv2.waitKey(0)
exit()

# divide: 提取两张差别较大的线条和内容
image_blend = cv2.divide(image_gray, image_bulr, scale=255)
# cv2.imshow('image_blend', image_blend) # 素描
cv2.waitKey(0)
# cv2.imwrite('result1.jpg', image_blend)

那上面的代码,我们是在原有的基础上添加了,一些实时展示的代码,来方便同学们理解。
其实有同学会问,我用软件不就可以直接生成素描图吗?
那程序的好处是什么?
程序的好处就是如果你的图片量多的话,这个时候使用程序批量生成也是非常方便高效的。
这样我们的就完成,把小姐姐的图片变成了素描,skr~。

3. 百度图片爬虫+生成素描图

不过,这还不是我们的海量图片,为了达到海量这个词呢,我写了一个百度图片爬虫,不过本文不是教如何写爬虫代码的,这里我就直接放出爬虫代码,符和软件工程规范:

# Crawler.Spider.py
import re
import os
import time
import collections
from collections import namedtuple

import requests
from concurrent import futures
from tqdm import tqdm
from enum import Enum

BASE_URL = 'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={keyword}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word={keyword}&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn={page}&rn=30&gsm=&1568638554041='

HEADERS = {
 'Referer': 'http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fr=&sf=1&fmq=1567133149621_R&pv=&ic=0&nc=1&z=0&hd=0&latest=0©right=0&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=%E5%A3%81%E7%BA%B8',
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
 'X-Requested-With': 'XMLHttpRequest', }

class BaiDuSpider:
 def __init__(self, max_works, images_type):
  self.max_works = max_works
  self.HTTPStatus = Enum('Status', ['ok', 'not_found', 'error'])
  self.result = namedtuple('Result', 'status data')
  self.session = requests.session()
  self.img_type = images_type
  self.img_num = None
  self.headers = HEADERS
  self.index = 1

 def get_img(self, img_url):
  res = self.session.get(img_url)
  if res.status_code != 200:
   res.raise_for_status()

  return res.content

 def download_one(self, img_url, verbose):
  try:
   image = self.get_img(img_url)
  except requests.exceptions.HTTPError as e:
   res = e.response
   if res.status_code == 404:
    status = self.HTTPStatus.not_found
    msg = 'not_found'
   else:
    raise
  else:
   self.save_img(self.img_type, image)
   status = self.HTTPStatus.ok
   msg = 'ok'

  if verbose:
   print(img_url, msg)

  return self.result(status, msg)

 def get_img_url(self):
  urls = [BASE_URL.format(keyword=self.img_type, page=page) for page in self.img_num]
  for url in urls:
   res = self.session.get(url, headers=self.headers)
   if res.status_code == 200:
    img_list = re.findall(r'"thumbURL":"(.*?)"', res.text)
    # 返回出图片地址,配合其他函数运行
    yield {img_url for img_url in img_list}
   elif res.status_code == 404:
    print('-----访问失败,找不到资源-----')
    yield None
   elif res.status_code == 403:
    print('*****访问失败,服务器拒绝访问*****')
    yield None
   else:
    print('>>> 网络连接失败 <<<')
    yield None

 def download_many(self, img_url_set, verbose=False):
  if img_url_set:
   counter = collections.Counter()
   with futures.ThreadPoolExecutor(self.max_works) as executor:
    to_do_map = {}
    for img in img_url_set:
     future = executor.submit(self.download_one, img, verbose)
     to_do_map[future] = img
    done_iter = futures.as_completed(to_do_map)

   if not verbose:
    done_iter = tqdm(done_iter, total=len(img_url_set))
   for future in done_iter:
    try:
     res = future.result()
    except requests.exceptions.HTTPError as e:
     error_msg = 'HTTP error {res.status_code} - {res.reason}'
     error_msg = error_msg.format(res=e.response)
    except requests.exceptions.ConnectionError:
     error_msg = 'ConnectionError error'
    else:
     error_msg = ''
     status = res.status

    if error_msg:
     status = self.HTTPStatus.error

    counter[status] += 1

    if verbose and error_msg:
     img = to_do_map[future]
     print('***Error for {} : {}'.format(img, error_msg))
   return counter
  else:
   pass

 def save_img(self, img_type, image):
  with open('{}/{}.jpg'.format(img_type, self.index), 'wb') as f:
   f.write(image)
  self.index += 1

 def what_want2download(self):
  # self.img_type = input('请输入你想下载的图片类型,什么都可以哦~ >>> ')
  try:
   os.mkdir(self.img_type)
  except FileExistsError:
   pass
  img_num = input('请输入要下载的数量(1位数代表30张,列如输入1就是下载30张,2就是60张):>>> ')
  while True:
   if img_num.isdigit():
    img_num = int(img_num) * 30
    self.img_num = range(30, img_num + 1, 30)
    break
   else:
    img_num = input('输入错误,请重新输入要下载的数量>>> ')

 def main(self):
  # 获取图片类型和下载的数量
  total_counter = {}
  self.what_want2download()
  for img_url_set in self.get_img_url():
   if img_url_set:
    counter = self.download_many(img_url_set, False)
    for key in counter:
     if key in total_counter:
      total_counter[key] += counter[key]
     else:
      total_counter[key] = counter[key]

   else:
    # 可以为其添加报错功能
    pass

  time.sleep(.5)
  return total_counter

if __name__ == '__main__':
 max_works = 20
 bd_spider = BaiDuSpider(max_works)
 print(bd_spider.main())
# Sketch_the_generated_code.py
import cv2
def drawing(src, id=None):
 image_rgb = cv2.imread(src)
 image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY)
 image_blur = cv2.GaussianBlur(image_gray, ksize=(21, 21), sigmaX=0, sigmaY=0)
 image_blend = cv2.divide(image_gray, image_blur, scale=255)
 cv2.imwrite(f'Drawing_images/result-{id}.jpg', image_blend)
# image_list.image_list_path.py
import os
from natsort import natsorted

IMAGES_LIST = []

def image_list(path):
 global IMAGES_LIST
 for root, dirs, files in os.walk(path):
  # 按文件名排序
  # files.sort()
  files = natsorted(files)
  # 遍历所有文件
  for file in files:
   # 如果后缀名为 .jpg
   if os.path.splitext(file)[1] == '.jpg':
    # 拼接成完整路径
    # print(file)
    filePath = os.path.join(root, file)
    print(filePath)
    # 添加到数组
    IMAGES_LIST.append(filePath)
 return IMAGES_LIST
# main.py
import time

from Sketch_the_generated_code import drawing
from Crawler.Spider import BaiDuSpider
from image_list.image_list_path import image_list
import os

MAX_WORDS = 20

if __name__ == '__main__':
 # now_path = os.getcwd()
 # img_type = 'ai'
 img_type = input('请输入你想下载的图片类型,什么都可以哦~ >>> ')
 bd_spider = BaiDuSpider(MAX_WORDS, img_type)
 print(bd_spider.main())
 time.sleep(10) # 这里设置睡眠时间,让有足够的时间去添加,这样读取就,去掉或者太短会报错,所以
 for index, path in enumerate(image_list(img_type)):
  drawing(src = path, id = index)

所以最终的目录结构如下所示:

C:.
│  main.py
│  Sketch_the_generated_code.py
│
├─Crawler
│  │  Spider.py
│  │
│  └─__pycache__
│          Spider.cpython-37.pyc
│
├─drawing
│  │  result.jpg
│  │  result1.jpg
│  │  Sketch_the_generated_code.py
│  │  study.py
│  │
│  ├─images
│  │      image_1.jpg
│  │
│  └─__pycache__
│          Sketch_the_generated_code.cpython-37.pyc
│
├─Drawing_images
├─image_list
│  │  image_list_path.py
│  │
│  └─__pycache__
│          image_list_path.cpython-37.pyc
│
└─__pycache__
        Sketch_the_generated_code.cpython-37.pyc

至此,全部代码已经完成。

到此这篇关于Python使用5行代码批量做小姐姐的素描图的文章就介绍到这了,更多相关Python 批量做素描图内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python实现图片彩色转化为素描

    本文实例为大家分享了Python将图片彩色转化为素描的具体代码,供大家参考,具体内容如下 第一种: from PIL import Image, ImageFilter, ImageOps img = Image.open('E:\\picture\\1.png') def dodge(a, b, alpha): return min(int(a*255/(256-b*alpha)), 255) def draw(img, blur=25, alpha=1.0): img1 = img.conv

  • python opencv图像处理(素描、怀旧、光照、流年、滤镜 原理及实现)

    图像素描特效 图像素描特效主要经过以下几个步骤: 调用cv.cvtColor()函数将彩色图像灰度化处理: 通过cv.GaussianBlur()函数实现高斯滤波降噪: 边缘检测采用Canny算子实现: 最后通过cv.threshold()反二进制阈值化处理实现素描特效. #coding:utf-8 import cv2 as cv import numpy as np #读取原始图像 img = cv.imread('d:/paojie.png') #图像灰度处理 gray = cv.cvtC

  • python如何将图片转换素描画

    代码如下 # -*- coding:utf-8 -*- import cv2 import numpy as np from tkinter import filedialog, Tk from os import getcwd from re import findall def open_path(): # 图片路径 root = Tk() root.withdraw() file_path = (filedialog.askopenfilename(title='选择图片文件', file

  • 基于python实现把图片转换成素描

    这篇文章主要介绍了基于python实现把图片转换成素描,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 导语: 你是否还在为当时年少时没有选择自己的梦想而伤心,是否还在为自己的无法成为绘画名家而苦恼,这一切都不需要担心.python都能帮你实现,诶!python怎么能画画呢,一些简单的图案没问题,但是我要是想画素描那肯定没有办法了呀! 需求分析: 通过python代码脚本,实现绘制素描 安装工具 pip install pillow pip in

  • python实现图片素描效果

    代码如下: from PIL import Image #图像处理模块 import numpy as np a = np.asarray(Image.open("这里是原图片的路径").convert('L')).astype('float') #将图像以灰度图的方式打开并将数据转为float存入np中 depth = 10. # (0-100) grad = np.gradient(a) #取图像灰度的梯度值 grad_x, grad_y =grad #分别取横纵图像梯度值 gra

  • Python使用5行代码批量做小姐姐的素描图

    目录 1. 流程分析 2. 具体实现 3. 百度图片爬虫+生成素描图 我给大家带来的是 50行代码,生成一张素描图.让自己也是一个素描"大师".那废话不多说,我们直接先来看看效果吧. 上图的右边就是我们的效果,那具体有哪些步骤呢? 1. 流程分析 对于上面的流程来说是非常简单的,接下来我们来看看具体的实现. 2. 具体实现 安装所需要的库: pip install opencv-python 导入所需要的库: import cv2 编写主体代码也是非常的简单的,代码如下: import

  • Python用20行代码实现批量抠图功能

    目录 前言 1.准备 2.编写代码 3.结果分析 前言 抠图前 vs Python自动抠图后 在日常的工作和生活中,我们经常会遇到需要抠图的场景,即便是只有一张图片需要抠,也会抠得我们不耐烦,倘若遇到许多张图片需要抠,这时候你的表情应该会很有趣. Python能够成为这样的一种工具:在只有一张图片,需要细致地抠出人物的情况下,能帮你减少抠图步骤:在有多张图片需要抠的情况下,能直接帮你输出这些人物的基本轮廓,虽然不够细致,但也够用了. DeepLabv3+ 是谷歌 DeepLab语义分割系列网络的

  • Python用5行代码实现批量抠图的示例代码

    前言 对于会PhotoShop的人来说,抠图是非常简单的操作了,有时候几秒钟就能扣好一张图.不过一些比较复杂的图,有时候还是要画点时间的,今天就给大家带了一个非常快速简单的办法,用Python来批量抠取人像. 效果展示 开始吧,我也不看好什么自动抠图,总觉得不够精确,抠不出满意的图.下面我就直接展示一下效果图吧.我们先看看原图 这张图片背景未纯色,我们平时用PhotoShop抠起来也比较简单,对我们计算机来说也不是什么难题,下面是效果图: 因为本身是PNG图片,而且原图是白色背景,所以看不出什么

  • Python通过90行代码搭建一个音乐搜索工具

    下面小编把具体实现代码给大家分享如下: 之前一段时间读到了这篇博客,其中描述了作者如何用java实现国外著名音乐搜索工具shazam的基本功能.其中所提到的文章又将我引向了关于shazam的一篇论文及另外一篇博客.读完之后发现其中的原理并不十分复杂,但是方法对噪音的健壮性却非常好,出于好奇决定自己用python自己实现了一个简单的音乐搜索工具-- Song Finder, 它的核心功能被封装在SFEngine 中,第三方依赖方面只使用到了 scipy. 工具demo 这个demo在ipython

  • python用700行代码实现http客户端

    本文用python在TCP的基础上实现一个HTTP客户端, 该客户端能够复用TCP连接, 使用HTTP1.1协议. 一. 创建HTTP请求 HTTP是基于TCP连接的, 它的请求报文格式如下: 因此, 我们只需要创建一个到服务器的TCP连接, 然后按照上面的格式写好报文并发给服务器, 就实现了一个HTTP请求. 1. HTTPConnection类 基于以上的分析, 我们首先定义一个HTTPConnection类来管理连接和请求内容: class HTTPConnection: default_

  • Python三百行代码实现飞机大战

    目录 一. 动态效果图如下 二. 思路框架 三. Python代码实现 四. 小结 一. 动态效果图如下 先来看下飞机大战游戏最终实现的动态效果图. 二. 思路框架 plane_sprite.py文件内容 1.导入需要使用的模块 import random import pygame 在导入pygame之前,需要先使用命令: pip install pygame 进行包模块的安装 2.设置屏幕大小和刷新帧率等常量 3.创建继承于pygame.sprite.Sprite的基类GameSprite

  • python用10行代码实现对黄色图片的检测功能

    本文实例讲述了python用10行代码实现对黄色图片的检测功能.分享给大家供大家参考.具体如下: 原理:将图片转换为YCbCr模式,在图片中寻找图片色值像素,如果在皮肤色值内的像素面积超过整个画面的1/3,就认为是黄色图片. 申明:简单场景还是够用了,稍微复杂一点就不准确了,例如:整幅画面是人的头像,皮肤色值的像素必然超过50%,被误认为黄色图片就太武断了. 需要安装python图片库PIL支持 porn_detect.py如下: import sys,PIL.Image as Image im

  • Python实现3行代码解简单的一元一次方程

    本文所述实例为Python用3行代码实现解一元一次方程,代码简洁高效,具体用法如下: >>> solve("x - 2*x + 5*x - 46*(235-24) = x + 2") 3236.0 功能代码如下: def solve(eq,var='x'): eq1 = eq.replace("=","-(")+")" c = eval(eq1,{var:1j}) return -c.real/c.imag

  • Python只用40行代码编写的计算器实例

    本文实例讲述了Python只用40行代码编写的计算器.分享给大家供大家参考,具体如下: 效果图: 代码: from tkinter import * reset=True def buttonCallBack(event): global label global reset num=event.widget['text'] if num=='C': label['text']="0" return if num in "=": label['text']=str(

  • Python用20行代码实现完整邮件功能

    目录 Python实现完整邮件 一.邮箱端设置 1.首先登录网页版126邮箱 2.打开 设置-POP3/SMTP/IMAP配置界面 3.新增一个授权码 二.python发送邮件 1.安装邮件模块 2.调用模块 3.设置邮件内容 4.添加附件 三.python读取邮件 Python实现完整邮件 先上效果: 一.邮箱端设置 首先,要对邮件进行一下设置,在邮箱端获取一个授权码. 1.首先登录网页版126邮箱 2.打开 设置-POP3/SMTP/IMAP配置界面 3.新增一个授权码 二.python发送

随机推荐