电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Python使用5行代碼批量做小姐姐的素描圖

瀏覽:112日期:2022-06-15 09:07:02
目錄1. 流程分析2. 具體實現3. 百度圖片爬蟲+生成素描圖

我給大家帶來的是 50行代碼,生成一張素描圖。讓自己也是一個素描“大師”。那廢話不多說,我們直接先來看看效果吧。

Python使用5行代碼批量做小姐姐的素描圖

上圖的右邊就是我們的效果,那具體有哪些步驟呢?

1. 流程分析

Python使用5行代碼批量做小姐姐的素描圖

對于上面的流程來說是非常簡單的,接下來我們來看看具體的實現。

2. 具體實現

安裝所需要的庫:

pip install opencv-python

導入所需要的庫:

import cv2

編寫主體代碼也是非常的簡單的,代碼如下:

import cv2SRC = ’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.pyimport reimport osimport timeimport collectionsfrom collections import namedtupleimport requestsfrom concurrent import futuresfrom tqdm import tqdmfrom enum import EnumBASE_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.statusif error_msg: status = self.HTTPStatus.errorcounter[status] += 1if 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_counterif __name__ == ’__main__’: max_works = 20 bd_spider = BaiDuSpider(max_works) print(bd_spider.main())

# Sketch_the_generated_code.pyimport cv2def 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.pyimport osfrom natsort import natsortedIMAGES_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.pyimport timefrom Sketch_the_generated_code import drawingfrom Crawler.Spider import BaiDuSpiderfrom image_list.image_list_path import image_listimport osMAX_WORDS = 20if __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 批量做素描圖內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 楼承板-开闭口楼承板-无锡海逵楼承板| DDoS安全防护官网-领先的DDoS安全防护服务商 | 铝板冲孔网,不锈钢冲孔网,圆孔冲孔网板,鳄鱼嘴-鱼眼防滑板,盾构走道板-江拓数控冲孔网厂-河北江拓丝网有限公司 | 欧美日韩国产一区二区三区不_久久久久国产精品无码不卡_亚洲欧洲美洲无码精品AV_精品一区美女视频_日韩黄色性爱一级视频_日本五十路人妻斩_国产99视频免费精品是看4_亚洲中文字幕无码一二三四区_国产小萍萍挤奶喷奶水_亚洲另类精品无码在线一区 | 送料机_高速冲床送料机_NC伺服滚轮送料机厂家-东莞市久谐自动化设备有限公司 | 正压密封性测试仪-静态发色仪-导丝头柔软性测试仪-济南恒品机电技术有限公司 | 帽子厂家_帽子工厂_帽子定做_义乌帽厂_帽厂_制帽厂 | 卸料器-卸灰阀-卸料阀-瑞安市天蓝环保设备有限公司 | 袋式过滤器,自清洗过滤器,保安过滤器,篮式过滤器,气体过滤器,全自动过滤器,反冲洗过滤器,管道过滤器,无锡驰业环保科技有限公司 | 大功率金属激光焊接机价格_不锈钢汽车配件|光纤自动激光焊接机设备-东莞市正信激光科技有限公司 定制奶茶纸杯_定制豆浆杯_广东纸杯厂_[绿保佳]一家专业生产纸杯碗的厂家 | 礼仪庆典公司,礼仪策划公司,庆典公司,演出公司,演艺公司,年会酒会,生日寿宴,动工仪式,开工仪式,奠基典礼,商务会议,竣工落成,乔迁揭牌,签约启动-东莞市开门红文化传媒有限公司 | 超声波破碎仪-均质乳化机(供应杭州,上海,北京,广州,深圳,成都等地)-上海沪析实业有限公司 | 铁盒_铁罐_马口铁盒_马口铁罐_铁盒生产厂家-广州博新制罐 | 奶茶加盟,奶茶加盟店连锁品牌-甜啦啦官网 | 选宝石船-陆地水上开采「精选」色选机械设备-青州冠诚重工机械有限公司 | 贵州科比特-防雷公司厂家提供贵州防雷工程,防雷检测,防雷接地,防雷设备价格,防雷产品报价服务-贵州防雷检测公司 | 磁棒电感生产厂家-电感器厂家-电感定制-贴片功率电感供应商-棒形电感生产厂家-苏州谷景电子有限公司 | 标准件-非标紧固件-不锈钢螺栓-非标不锈钢螺丝-非标螺母厂家-三角牙锁紧自攻-南京宝宇标准件有限公司 | 上海办公室装修,写字楼装修—启鸣装饰设计工程有限公司 | 绿萝净除甲醛|深圳除甲醛公司|测甲醛怎么收费|培训机构|电影院|办公室|车内|室内除甲醛案例|原理|方法|价格立马咨询 | 工控机,嵌入式主板,工业主板,arm主板,图像采集卡,poe网卡,朗锐智科 | 高压无油空压机_无油水润滑空压机_水润滑无油螺杆空压机_无油空压机厂家-科普柯超滤(广东)节能科技有限公司 | 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 无缝钢管-聊城无缝钢管-小口径无缝钢管-大口径无缝钢管 - 聊城宽达钢管有限公司 | 制丸机,小型中药制丸机,全自动制丸机价格-甘肃恒跃制药设备有限公司 | 体坛网_体坛+_体坛周报新闻客户端| 防水接头-电缆防水接头-金属-电缆密封接头-不锈钢电缆接头 | 挤塑板-XPS挤塑板-挤塑板设备厂家[襄阳欧格] | 智能垃圾箱|垃圾房|垃圾分类亭|垃圾分类箱专业生产厂家定做-宿迁市传宇环保设备有限公司 | 防爆电机_ybx3系列电机_河南省南洋防爆电机有限公司 | 间苯二酚,间苯二酚厂家-淄博双和化工 | 四川职高信息网-初高中、大专、职业技术学校招生信息网 | 步入式高低温测试箱|海向仪器 | 拉力机-万能试验机-材料拉伸试验机-电子拉力机-拉力试验机厂家-冲击试验机-苏州皖仪实验仪器有限公司 | 精密钢管,冷拔精密无缝钢管,精密钢管厂,精密钢管制造厂家,精密钢管生产厂家,山东精密钢管厂家 | 钢格栅板_钢格板网_格栅板-做专业的热镀锌钢格栅板厂家-安平县迎瑞丝网制造有限公司 | 写方案网_方案策划方案模板下载| 泰州物流公司_泰州货运公司_泰州物流专线-东鑫物流公司 | 喷码机,激光喷码打码机,鸡蛋打码机,手持打码机,自动喷码机,一物一码防伪溯源-恒欣瑞达有限公司 | 科研ELISA试剂盒,酶联免疫检测试剂盒,昆虫_植物ELISA酶免试剂盒-上海仁捷生物科技有限公司 | 岸电电源-60HZ变频电源-大功率变频电源-济南诚雅电子科技有限公司 |