- OpenCV 4 with Python Blueprints
- Dr. Menua Gevorgyan Arsen Mamikonyan Michael Beyeler
- 218字
- 2021-06-24 16:49:57
Applying pencil sketch transformation
With the tricks that we learned from the previous sections in our bag, we are now ready to take a look at the entire procedure.
The final code can be found in the convert_to_pencil_sketch function within the tools.py file.
The following procedure shows you how to convert a color image into grayscale. After that, we aim to blend the grayscale image with its blurred negative:
- First, we convert an RGB image (imgRGB) into grayscale:
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
As you can see, we have used cv2.COLOR_RGB2GRAY as a parameter to the cv2.cvtColor function, which changes the color spaces. Note that it does not matter whether the input image is RGB or BGR (which is the default for OpenCV); we will get a nice grayscale image in the end.
- Then, we invert the image and blur it with a large Gaussian kernel of size (21,21):
inv_gray = 255 - gray_image
blurred_image = cv2.GaussianBlur(inv_gray, (21, 21), 0, 0)
- We use dodge to blend the original grayscale image with the blurred inverse:
gray_sketch = cv2.divide(gray_image, 255 - blurred_image,
scale=256)
The resulting image looks like this:
Image credit—"Lenna" by Conor Lawless is licensed under CC BY 2.0
Did you notice that our code can be optimized further? Let's take a look at how to optimize with OpenCV next.
推薦閱讀
- R語言經典實例(原書第2版)
- ThinkPHP 5實戰
- The Modern C++ Challenge
- 程序員面試筆試寶典
- 自己動手寫Java虛擬機
- Magento 2 Theme Design(Second Edition)
- Learning SQLite for iOS
- JavaScript+Vue+React全程實例
- Scala謎題
- TradeStation交易應用實踐:量化方法構建贏家策略(原書第2版)
- Ext JS 4 Web Application Development Cookbook
- 深入理解Android:Wi-Fi、NFC和GPS卷
- SQL經典實例(第2版)
- Apache Spark 2.x for Java Developers
- 常用工具軟件立體化教程(微課版)