如何用 Python 将图像卡通化

2025-06-07

如何用 Python 将图像卡通化

在本教程中,我将向您展示如何使用 OpenCV 在 Python 中为图像添加卡通效果。

OpenCV 是一个用于计算机视觉和机器学习的开源 Python 库。它主要针对实时计算机视觉和图像处理。它用于对图像执行不同的操作,使用不同的技术对图像进行转换。

许多应用程序可以将您的照片变成卡通,但您只需几行 Python 代码就可以自己完成此操作。

这是我们的测试图像:

在此处输入图片描述

让我们跳到代码。



import numpy as np
import cv2


Enter fullscreen mode Exit fullscreen mode

之后我们读取我们的图像:



filename = 'elon.jpeg'


Enter fullscreen mode Exit fullscreen mode

然后我们将定义我们的resizeImage



def resizeImage(image):
    scale_ratio = 0.3
    width = int(image.shape[1] * scale_ratio)
    height = int(image.shape[0] * scale_ratio)
    new_dimensions = (width, height)
    resized = cv2.resize(image, new_dimensions, interpolation = cv2.INTER_AREA)

    return resized


Enter fullscreen mode Exit fullscreen mode

我们需要找到轮廓:



def findCountours(image):

    contoured_image = image
    gray = cv2.cvtColor(contoured_image, cv2.COLOR_BGR2GRAY) 
    edged = cv2.Canny(gray, 30, 100)
    contours, hierarchy = cv2.findContours(edged, 
    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cv2.drawContours(contoured_image, contours, contourIdx=-1, color=1, thickness=1)
    cv2.imshow('Image after countouring', contoured_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return contoured_image


Enter fullscreen mode Exit fullscreen mode

之后,我们进行颜色量化:



def ColorQuantization(image, K=4):
    Z = image.reshape((-1, 3)) 


Enter fullscreen mode Exit fullscreen mode

然后我们将图像转换为 numpy float32:



    Z = np.float32(Z) 


Enter fullscreen mode Exit fullscreen mode

我们还需要定义标准并应用 kmeans:



    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001)
    compactness, label, center = cv2.kmeans(Z, K, None, criteria, 1, cv2.KMEANS_RANDOM_CENTERS)


Enter fullscreen mode Exit fullscreen mode

然后我们转换为uint8并应用到原始图像:



   center = np.uint8(center)
   res = center[label.flatten()]
   res2 = res.reshape((image.shape))

   return res2


Enter fullscreen mode Exit fullscreen mode


if __name__ == "__main__":

    image = cv2.imread(filename)
    resized_image = resizeImage(image)
    coloured = ColorQuantization(resized_image)
    contoured = findCountours(coloured)
    final_image = contoured
    save_q = input("Save the image? [y]/[n] ")

    if save_q == "y":

        cv2.imwrite("cartoonized_"+ filename, final_image)
        print("Image saved!")


Enter fullscreen mode Exit fullscreen mode

这是我们的最终结果:
在此处输入图片描述

谢谢大家。

文章来源:https://dev.to/stokry/how-to-cartoonize-an-image-with-python-1e01
PREV
速度提示:在 Gatsby 中使用 Typefaces.js 本地托管字体
NEXT
如何使用 Heroku/Netlify 部署全栈 MERN 应用!开始吧!你做到了!