- OpenCV 4 with Python Blueprints
- Dr. Menua Gevorgyan Arsen Mamikonyan Michael Beyeler
- 206字
- 2021-06-24 16:50:00
Combining colors and outlines to produce a cartoon
The last step is to combine the two previously achieved effects. Simply fuse the two effects together into a single image using cv2.bitwise_and. The complete function is as follows:
def cartoonize(rgb_image, *,
num_pyr_downs=2, num_bilaterals=7):
# STEP 1 -- Apply a bilateral filter to reduce the color palette of
# the image.
downsampled_img = rgb_image
for _ in range(num_pyr_downs):
downsampled_img = cv2.pyrDown(downsampled_img)
for _ in range(num_bilaterals):
filterd_small_img = cv2.bilateralFilter(downsampled_img, 9, 9, 7)
filtered_normal_img = filterd_small_img
for _ in range(num_pyr_downs):
filtered_normal_img = cv2.pyrUp(filtered_normal_img)
# make sure resulting image has the same dims as original
if filtered_normal_img.shape != rgb_image.shape:
filtered_normal_img = cv2.resize(
filtered_normal_img, rgb_image.shape[:2])
# STEP 2 -- Convert the original color image into grayscale.
img_gray = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2GRAY)
# STEP 3 -- Apply amedian blur to reduce image noise.
img_blur = cv2.medianBlur(img_gray, 7)
# STEP 4 -- Use adaptive thresholding to detect and emphasize the edges
# in an edge mask.
gray_edges = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 9, 2)
# STEP 5 -- Combine the color image from step 1 with the edge mask
# from step 4.
rgb_edges = cv2.cvtColor(gray_edges, cv2.COLOR_GRAY2RGB)
return cv2.bitwise_and(filtered_normal_img, rgb_edges)
The result looks like this:
In the next section, we'll set up the main script and design a GUI application.
推薦閱讀
- SQL Server 從入門到項目實踐(超值版)
- C及C++程序設計(第4版)
- Flink SQL與DataStream入門、進階與實戰
- Java從入門到精通(第4版)
- Java 9 Programming Blueprints
- STM32F0實戰:基于HAL庫開發
- The Complete Coding Interview Guide in Java
- Protocol-Oriented Programming with Swift
- Flowable流程引擎實戰
- Spring Boot實戰
- Mastering Apache Storm
- Mastering Adobe Captivate 7
- OpenCV with Python Blueprints
- C++ System Programming Cookbook
- 零基礎C#學習筆記