欢迎访问本站,希望站内信息可以帮助到您! 博主个人微信:xituxiaoshutong100

图片变漫画效果

OpenCV 迷途小书童 0评论

软硬件环境

  • windows 10 64bit
  • nvidia gtx 1066
  • opencv 4.4.0

原理

本文介绍如何使用opencv来实现图片的漫画效果。这里主要关心2个知识点,第一是边缘edge,第二个是调色板color palette

示例代码

import sys
import cv2
import numpy as np


def color_quantization(img, k):
    # Transform the image
    data = np.float32(img).reshape((-1, 3))

    # Determine criteria
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.001)

    # 采用K-Means方法
    ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
    center = np.uint8(center)
    result = center[label.flatten()]
    result = result.reshape(img.shape)
    return result


def edge_mask(img, line_size, blur_value):
    # 图片灰度化
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 降噪
    gray_blur = cv2.medianBlur(gray, blur_value)

    # 检测边缘
    edges = cv2.adaptiveThreshold(gray_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, line_size, blur_value)

    return edges


if __name__ == '__main__':

    # 几个常量,可适当调整
    line_size = 7
    blur_value = 7
    total_color = 9

    # 读取图片
    img = cv2.imread(sys.argv[1])

    # 创建边缘mask
    edges = edge_mask(img, line_size, blur_value)

    # reduce colors
    img_color = color_quantization(img, total_color)

    # 双向过滤器降噪
    img_blurred = cv2.bilateralFilter(img_color, d=7, sigmaColor=200, sigmaSpace=200)

    # 将2者结合起来, 漫画效果来了
    img_cartoon = cv2.bitwise_and(img_blurred, img_blurred, mask=edges)
    cv2.imwrite('result.jpg', img_cartoon)

执行上述代码

python demo.py branty.jpg

opencv

opencv

喜欢 (0)
发表我的评论
取消评论

表情