如何使用Python对图像进行卡通化

作者 : 开心源码 本文共1581个字,预计阅读时间需要4分钟 发布时间: 2022-05-14 共179人阅读

在本教程中,我将向你展现如何使用OpenCV在Python中为图像赋予卡通效果。

OpenCV是用于计算机视觉和机器学习的开源python库。它主要针对实时计算机视觉和图像解决。它用于对图像执行不同的操作,而后使用不同的技术对其进行转换。

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

这是我们的测试图像:

elon.jpeg

代码:

import numpy as npimport cv2

之后,我们阅读了图像:

filename = 'elon.jpeg'

而后我们将定义我们的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

我们需要找到轮廓:

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

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

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

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

    Z = np.float32(Z) 

我们还需要定义critera并应用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)

而后我们将其转换uint8并应用于原始图像

 center = np.uint8(center)   res = center[label.flatten()]   res2 = res.reshape((image.shape))   return res2
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!")

这是我们的最终结果:

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 如何使用Python对图像进行卡通化

发表回复