Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python code to make sketches in batches

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to use Python code to do sketches in batches". The editor shows you the operation process through actual cases. The operation method is simple and fast, and it is practical. I hope this article "how to use Python code to do sketches in batches" can help you solve the problem.

1. Process analysis

For the above process is very simple, let's take a look at the specific implementation.

two。 Concrete realization

Install the required libraries:

Pip install opencv-python

Import the required libraries:

Import cv2

Writing the body code is also very simple, the code is as follows:

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)

In fact, the above code is not difficult, then in order to make my friends understand better, I wrote the following code:

"" project = "Code", file_name = "study.py", author = "AI Yuechuang" time = "8:35 on 2020-5-19", product_name = PyCharm, official account: AI Yuechuang code is far away from bugs with the god animal protecting I love animals. They taste delicious. "" import cv2# original image path SRC = "images/image_1.jpg" # read picture image_rgb = cv2.imread (SRC) # cv2.imshow ("rgb", image_rgb) # original image # cv2.waitKey (0) # exit () image_gray = cv2.cvtColor (image_rgb, cv2.COLOR_BGR2GRAY) # cv2.imshow ("gray", image_gray) # Grayscale image # cv2.waitKey (0) # exit () image_bulr = cv2.GaussianBlur (image_gray) Ksize= (21, 21), sigmaX=0, sigmaY=0) cv2.imshow ("image_blur", image_bulr) # Gaussian virtual cv2.waitKey (0) exit () # divide: extract two distinct lines and content image_blend = cv2.divide (image_gray, image_bulr, scale=255) # cv2.imshow ("image_blend", image_blend) # Sketch cv2.waitKey (0) # cv2.imwrite ("result1.jpg", image_blend)

The above code, we added some real-time display code on the basis of the original, to facilitate the understanding of the students.

In fact, some students will ask, can't I generate sketches directly with the software?

What are the benefits of that program?

The advantage of the program is that if you have a large number of pictures, it is very convenient and efficient to use the program to generate a batch at this time.

In this way, we finished turning the picture of the little sister into a sketch, skr~.

3. Baidu picture crawler + generate sketch map

However, this is not our massive picture, in order to achieve the word massive, I wrote a Baidu picture crawler, but this article does not teach how to write crawler code, here I will directly release the crawler code, runes and software engineering specifications:

# 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} & sailing seating, setting tableships, widthpieces, heightening, facebreaking, listing, peeling, filling, writing, etc., etc. 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) # returns the address of the picture Run yield {img_url for img_url in img_list} elif res.status_code = = 404 with other functions: print ("- access failed, resource cannot be found -") yield None elif res.status_code = = 403: print ("* access failed Server denied access * ") yield None else: print (" > Network connection failed ") try: os.mkdir (self.img_type) except FileExistsError: pass img_num = input (" Please enter the number to download (1 digit represents 30, if you enter 1, download 30) 2 is 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 (" input error " Please re-enter the number of downloads > ") def main (self): # get the image type and the number of downloads 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_ counterkey + = counter [key] else: total_ counterkey] = counter [key] else: # can add error reporting function 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): # sort by file name # files.sort () files = natsorted (files) # iterate through all files for file in files: # if the suffix is .jpg if os.path.splitext (file) [1] = ".jpg": # splice into a full path # print (file) filePath = os.path.join (root) File) print (filePath) # add to the array 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 ("Please enter the type of picture you want to download Anything is fine.) bd_spider = BaiDuSpider (MAX_WORDS, img_type) print (bd_spider.main ()) time.sleep (10) # set the sleep time here so that there is enough time to add it, so it can be read, removed or too short will cause an error, so for index, path in enumerate (image_list (img_type)): drawing (src = path, id = index)

So the final directory structure is as follows:

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 pycache__ image_list │ │ image_list_path.py │ ││ └─ _ _ pycache__ │ image_list_path.cpython-37.pyc │└─ _ _ pycache__ Sketch_the_generated_code.cpython-37.pyc on "how to do batch sketches with Python code" ends here Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report